创建张量,其中直到给定索引的所有元素均为 1,其余为 0

Create tensors where all elements up to a given index are 1s, the rest are 0s

我有一个占位符 lengths = tf.placeholder(tf.int32, [10])。分配给此占位符的 10 个值中的每一个都 <= 25。我现在想创建一个二维张量,称为 masks,形状为 [10, 25],其中长度为 25 的 10 个向量中的每一个都有前 n 个元素设置为 1,其余设置为 0 - nlengths 中的对应值。

使用 TensorFlow 的内置方法执行此操作的最简单方法是什么?

例如:

lengths = [4, 6, 7, ...]

-> masks = [[1, 1, 1, 1, 0, 0, 0, 0, ..., 0],
            [1, 1, 1, 1, 1, 1, 0, 0, ..., 0],
            [1, 1, 1, 1, 1, 1, 1, 0, ..., 0],
            ...
           ]

您可以将长度重塑为 (10, 1) 张量,然后将其与另一个 sequence/indices 0,1,2,3,...,25 进行比较,由于广播,如果索引将导致 True小于长度,否则 False;然后你可以将布尔结果转换为 10:

lengths = tf.constant([4, 6, 7])
n_features = 25
​
import tensorflow as tf
​
masks = tf.cast(tf.range(n_features) < tf.reshape(lengths, (-1, 1)), tf.int8)

with tf.Session() as sess:
    print(sess.run(masks))

#[[1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
# [1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
# [1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]]