python – 如何像这样创建一个Ones和0的2D张量:

我需要根据这样的输入张量创建一个1和0的张量

input = tf.constant([3, 2, 4, 1, 0])

输出=

0 0 0 0 0

0 0 0 1 0

0 0 1 1 0

0 0 1 1 1

0 1 1 1 1

本质上,输入张量1的每个值的索引(i)指定我开始在该列中放置1的行.

最佳答案 这是TensorFlow操作的实现.请参阅评论了解详情

import tensorflow as tf

input = tf.placeholder(tf.int32, [None])
# Find indices that sort the input
# There is no argsort yet in the stable API,
# but you can do the same with top_k
_, order = tf.nn.top_k(-input, tf.shape(input)[0])
# Or use the implementation in contrib
order = tf.contrib.framework.argsort(input)
# Build triangular lower matrix
idx = tf.range(tf.shape(input)[0])
triangular = idx[:, tf.newaxis] > idx
# Reorder the columns according to the order
result = tf.gather(triangular, order, axis=1)
# Cast result from bool to int or float as needed
result = tf.cast(result, tf.int32)
with tf.Session() as sess:
    print(sess.run(result, feed_dict={input: [3, 2, 4, 1, 0]}))

输出:

[[0 0 0 0 0]
 [0 0 0 1 0]
 [0 0 1 1 0]
 [0 0 1 1 1]
 [0 1 1 1 1]]
点赞