首页 > 解决方案 > 从索引张量中获取掩码?

问题描述

如果我有一个形状为“batch_size * length * hidden_​​size”的张量,并且我有另一个形状为“batch_size * 2”的索引跨度张量,其中索引跨度张量表示我想从第一个张量中选择的开始和结束索引。说如果索引跨度张量有值

[[1,3], [2, 4]]

然后我想从第一个张量中得到以下掩码

[[0, 1, 1, 1, 0, 0, ...], [0, 0, 1, 1, 1, 0, 0, ...]]

有没有办法用 Tensorflow 做到这一点?

标签: tensorflow

解决方案


我们可以使用range(获取索引)和 tf.sparse_to_dense(填充索引)的组合来获得上述内容:

batch_size = 2
length_hidden_size = 10

# Use range to populate the indices
r = tf.map_fn(lambda x: tf.range(x[0], x[1]+1),a)

# convert to full indices
mesh = tf.meshgrid(tf.range(tf.shape(r)[1]), tf.range(tf.shape(r)[0]))[1]
full_indices = tf.reshape(tf.stack([mesh, r], axis=2), [-1,2])

# Set 1s to the full indices
val = tf.ones(tf.shape(full_indices)[0])
dense = tf.sparse_to_dense(full_indices,tf.constant([batch_size,length_hidden_size]), val, validate_indices=False)

with tf.Session() as sess:
   print(sess.run(dense))
#[[0. 1. 1. 1. 0. 0. 0. 0. 0. 0.]
# [0. 0. 1. 1. 1. 0. 0. 0. 0. 0.]]

推荐阅读