using tf.reverse()
, tf.reverse_sequence()
,并使用蒙版tf.sequence_mask()
.
第一种方式:
T = tf.constant([[1, 2, 3], [4, 5, 6]])
S = tf.constant([1, 2])
#expected_out T' = [[0, 1, 2], [0, 0, 4]]
t = tf.reverse_sequence(T, [2,1], seq_axis=1, batch_axis=0)
#[[2, 1, 3], [4, 5, 6]]
t = tf.reverse(t,[1])
#[[3, 1, 2], [6, 5, 4]]
mask = tf.sequence_mask([1,2],3)
t*tf.cast(~mask,"int32")
#[[0, 1, 2], [0, 0, 4]] ##
tf.reverse_sequence()
将从每个轴中选择多个元素,然后反转它们。这里我们选择反转第一个数组中的前两个元素和第二个数组中的第一个元素。然后我们反转整个序列,因为我们希望第一个元素移动到张量的末尾。这说明了第一个逆转的重要性,因为在第二个逆转中它们将恢复到原来的顺序。然后我们应用掩码使第一个不需要的元素 = 0。
此方法很灵活,您可以选择要为每个 elemnet 向左移动序列的数量,并将其与代码中的掩码相关联。