我在tensorflow中有一个长度的张量,让我们说它看起来像这样:
[[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]
]
我希望创建1s和0s的掩码,其数量为1对应于此张量的条目,填充0s到总长度为8。我想创建这个张量:
{{1}}
我该怎么做?
答案 0 :(得分:17)
现在可以通过tf.sequence_mask
来实现。更多详情here。
答案 1 :(得分:15)
这可以使用各种TensorFlow transformations:
来实现# 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]))
答案 2 :(得分:0)
我的版本比以前的答案要短一些。不确定它是否更有效
def mask(self, seq_length, max_seq_length):
return tf.map_fn(
lambda x: tf.pad(tf.ones([x], dtype=tf.int32), [[0, max_seq_length - x]]),
seq_length)