#当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.]]
[ 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.]]
import tensorflow as tf#当tf.sparse_to_dense的第一个参数是1阶的tensor时
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.]
import tensorflow as tf#当tf.sparse_to_dense的第一个参数是0阶的tensor时
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的形式是这样的[ * , * , * , * , * , * , * , * , * , * ]