[英]How can I put the sequential values to the sequence_mask?
我有一个顺序值...
v = tf.constant([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14], dtype=tf.int32).
和序列掩码..
[
[True, True, False, False, False],
[True, True, True, True, False],
[True, True, True, False, False],
[True, True, True, True, True],
[True, False, False, False, False],
]
如果我想用张量'v'的元素填充sequence_mark以获得这样的结果..
[
[0, 1, 0, 0, 0],
[2, 3, 4, 5, 0],
[6, 7, 8, 0, 0],
[9, 10, 11, 12, 13],
[14, 0, 0, 0, 0],
]
我能怎么做。
你可以这样做:
import tensorflow as tf
# Sequence lengths
s = tf.constant([2, 4, 3, 5, 1])
# Make mask
m = tf.sequence_mask(s, 5)
# Mask as integers
m_int = tf.dtypes.cast(m, tf.int32)
# Cumsum over mask, starting from 0
c = tf.cumsum(tf.reshape(m_int, [-1]), exclusive=True)
# Reshape cumsum to original shape and apply mask
result = tf.reshape(c, tf.shape(m)) * m_int
with tf.Session() as sess:
print(sess.run(result))
# [[ 0 1 0 0 0]
# [ 2 3 4 5 0]
# [ 6 7 8 0 0]
# [ 9 10 11 12 13]
# [14 0 0 0 0]]
如果v
是一个不只是简单序列的值数组,您可以执行以下操作:
# v is a vector of values
result = tf.reshape(tf.gather(v, c), tf.shape(m)) * m_int
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.