我在tensorflow中有一个长度的张量,让我们说它看起来像这样:
[4, 3, 5, 2]
我想创建一个1和0的掩码,其数量为1对应于此张量的条目,填充0到总长度8.即我想创建此张量:
[[1,1,1,1,0,0,0,0], [1,1,1,0,0,0,0,0], [1,1,1,1,1,0,0,0], [1,1,0,0,0,0,0,0] ]
我怎么能这样做?
现在可以通过以下方式实现tf.sequence_mask
.有关详细信息,请访问https://www.tensorflow.org/versions/r0.11/api_docs/python/array_ops.html#sequence_mask
这可以使用各种TensorFlow转换来实现:
# Make a 4 x 8 matrix where each row contains the length repeated 8 times. lengths = [4, 3, 5, 2] lengths_transposed = tf.expand_dims(lengths, 1) # Make a 4 x 8 matrix where each row contains [0, 1, ..., 7] range = tf.range(0, 8, 1) range_row = tf.expand_dims(range, 0) # Use the logical operations to create a mask mask = tf.less(range_row, lengths_transposed) # Use the select operation to select between 1 or 0 for each value. result = tf.select(mask, tf.ones([4, 8]), tf.zeros([4, 8]))