函数原型如下:
tf.sparse_to_dense(sparse_indices, output_shape, sparse_values, default_value, name=None)
这个函数的作用是将一个稀疏表示转换成一个密集张量。具体将稀疏张量sparse
转换成密集张量dense
的步骤如下:
# If sparse_indices is scalar
dense[i] = (i == sparse_indices ? sparse_values : default_value)
# If sparse_indices is a vector, then for each i
dense[sparse_indices[i]] = sparse_values[i]
# If sparse_indices is an n by d matrix, then for each i in [0, n)
dense[sparse_indices[i][0], ..., sparse_indices[i][d-1]] = sparse_values[i]
默认情况下,dense
中的填充值default_value
都是0
,除非该值被设置成一个标量。
sparse_indices
是稀疏矩阵中那些个别元素对应的索引值,有三种情况:
- 如果
sparse_indices
是个数,那么它只能指定一维矩阵的某一个元素。 - 如果
sparse_indices
是个向量,那么它可以指定一维矩阵的多个元素。 - 如果
sparse_indices
是个矩阵,那么它可以指定二维矩阵的多个元素。
output_shape
是输出的稀疏矩阵的shape
。sparse_values
是个别元素的值,分为两种情况:
- 如果
sparse_values
是个数,则所有索引指定的位置都用这个数。 - 如果
sparse_values
是个向量,则输出矩阵的某一行向量里某一行对应的数(所以这里向量的长度应该和输出矩阵的行数对应,不然报错)。
default_value
是未指定元素的默认值,一般如果是稀疏矩阵,就是0
了。
import tensorflow as tf
BATCH_SIZE = 5
# 真实标签,shape为[5, 1]
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)
# 将标签和索引tensor在第二个维度上连接起来,新的concated的shape为[5, 2]
concated = tf.concat([index, label], 1)
# onehot_labels的shape为[5, 10]
onehot_labels = tf.sparse_to_dense(concated, [BATCH_SIZE, 10], 1.0, 0.0)
with tf.Session() as sess:
print(sess.run(concated))
print("----------------")
onehot1 = sess.run(onehot_labels)
print(onehot1)
执行结果:
[[0 1]
[1 3]
[2 5]
[3 7]
[4 9]]
----------------
[[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.]]
如果output_shape
是一个行向量:
import tensorflow as tf
predicted_class = [1, 3, 5, 7, 9]
nb_classes = 10
one_hot = tf.sparse_to_dense(predicted_class, [nb_classes], 1.0)
with tf.Session() as sess:
onehot1 = sess.run(one_hot)
print(onehot1) # 输出“[0. 1. 0. 1. 0. 1. 0. 1. 0. 1.]”