学习tf.sparse_to_dense函数(代码实现)

#当tf.sparse_to_dense的第一个参数是2阶的tensor时
import tensorflow as tf   
BATCH_SIZE=5  
label=tf.expand_dims(tf.constant([1,3,5,7,9]),1)#真实标签  shape==>[5,1]
index=tf.expand_dims(tf.range(0, BATCH_SIZE),1)#真实标签的索引  shape==>[5,1]
concated = tf.concat([index, label],1)   #将标签和索引tensor在第二个维度上连接起来,新的concated的shape==>[5,2]
onehot_labels = tf.sparse_to_dense(concated, [BATCH_SIZE,10], 1.0, 0.0) # onehot_labels的shape==>[5,10]
with tf.Session() as sess:  
    onehot1=sess.run(onehot_labels)    
    print (onehot1)


[[ 0.  1.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  1.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  1.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  1.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  1.]]

#当tf.sparse_to_dense的第一个参数是1阶的tensor时
import tensorflow as tf   
BATCH_SIZE=5 
index=tf.constant([1,3,5,7,9])#shape==>[5]
onehot_labels = tf.sparse_to_dense(index, [10], 1.0, 0.0) # onehot_labels的shape==>[10]
with tf.Session() as sess:  
    onehot2=sess.run(onehot_labels)    
    print (onehot2)



输出结果是:
[ 0.  1.  0.  1.  0.  1.  0.  1.  0.  1.]

#当tf.sparse_to_dense的第一个参数是0阶的tensor时
import tensorflow as tf   
BATCH_SIZE=5 
index=tf.constant(3)# shape==>0
onehot_labels = tf.sparse_to_dense(index, [10], 1.0, 0.0)# onehot_labels的shape==>[10]

with tf.Session() as sess:  
    onehot3=sess.run(onehot_labels)    
    print (onehot3)




输出结果是:
[ 0.  0.  0.  1.  0.  0.  0.  0.  0.  0.]

注:1.当一个tensor的shape==>[5,2],说明该tensor是二阶的(因为5,2一共两个数字)
此tensor的形式是这样的[ [ * , *],[  * , *],[* , * ],[* , * ],[* , *] ]

        2. 当一个tensor的shape==>[10],说明该tensor是1阶的(因为只有1个数字10)
此tensor的形式是这样的[ * , * , * , * , * , * , * , * , * , *  ] 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值