假设我有一个向量
[3, 2, 4]
我想生成一个相应的张量
[[1,1,1,0], [1,1,0,0],[1,1,1,1]]
请告诉我们该怎么做?谢谢
答案 0 :(得分:1)
这应该有效:
import tensorflow as tf
sess = tf.Session()
# Input tensor
indices = tf.placeholder_with_default([3, 2, 4], shape=(None,))
max_index = tf.reduce_max(indices)
def to_ones(index):
ones = tf.ones((index, ), dtype=indices.dtype)
zeros = tf.zeros((max_index - index, ), dtype=indices.dtype)
return tf.concat([ones, zeros], axis=0)
# Output tensor
result = tf.map_fn(to_ones, indices)
print(result)
:
Tensor("map/TensorArrayStack/TensorArrayGatherV3:0", shape=(?, ?), dtype=int32)
print(sess.run(result))
:
[[1 1 1 0]
[1 1 0 0]
[1 1 1 1]]
print(sess.run(result, feed_dict={indices: [1, 3, 3, 7]}))
:
[[1 0 0 0 0 0 0]
[1 1 1 0 0 0 0]
[1 1 1 0 0 0 0]
[1 1 1 1 1 1 1]]