Skip to content

Instantly share code, notes, and snippets.

@oplatek
Last active May 12, 2016 09:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oplatek/29902eab12e6e6305e391a4211a5b049 to your computer and use it in GitHub Desktop.
Save oplatek/29902eab12e6e6305e391a4211a5b049 to your computer and use it in GitHub Desktop.
def lengths2mask2d(lengths, max_len):
batch_size = lengths.get_shape().as_list()[0]
# Filled the row of 2d array with lengths
lengths_transposed = tf.expand_dims(lengths, 1)
lengths_tiled = tf.tile(lengths_transposed, [1, max_len])
# Filled the rows of 2d array 0, 1, 2,..., max_len ranges
rng = tf.to_int64(tf.range(0, max_len, 1))
range_row = tf.expand_dims(rng, 0)
range_tiled = tf.tile(range_row, [batch_size, 1])
# Use the logical operations to create a mask
return tf.to_float(tf.less(range_tiled, lengths_tiled))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment