为给定索引创建具有特定深度的张量,并将其值设为1
索引张量:
[[1 3] [2 4] [0 4]]
输出张量(深度=5):
[[0. 1. 0. 1. 0.] [0. 0. 1. 0. 1.] [1. 0. 0. 0. 1.]]
回答:
你可以通过首先转换为完整索引,然后使用sparse_to_dense
函数将这些索引值设为1来实现上述效果。
#获取完整索引
mesh = tf.meshgrid(tf.range(indices.shape[1]), tf.range(indices.shape[0]))[1]
full_indices = tf.reshape(tf.stack([mesh, indices], axis=2), [-1,2])
#输出
#[[0 1] [0 3] [1 2] [1 4] [2 0] [2 4]]
#使用上述索引并将输出设为1。
#depth_x = 3, depth_y = 5
dense = tf.sparse_to_dense(full_indices,tf.constant([depth_x,depth_y]), tf.ones(tf.shape(full_indices)[0]))
# 输出
#[[0. 1. 0. 1. 0.]
#[0. 0. 1. 0. 1.]
#[1. 0. 0. 0. 1.]]