Reputation: 29
I have a sequential values...
v = tf.constant([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14], dtype=tf.int32).
and the sequence_mask..
[
[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],
]
if I want to fill the sequence_mark by elements of the tensor 'v' to get the result like this..
[
[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],
]
How can I do.
Upvotes: 0
Views: 54
Reputation: 59691
You can do that like this:
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]]
If v
is an array of values that are not just a simple sequence, you can do:
# v is a vector of values
result = tf.reshape(tf.gather(v, c), tf.shape(m)) * m_int
Upvotes: 1