tensorflow - 从索引张量中获取掩码?
问题描述
如果我有一个形状为“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 做到这一点?
解决方案
我们可以使用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.]]
推荐阅读
- git - 在干净的存储库上撤消 git rm cached -r
- transform - 在 Dataweave Mule 4 中拆分值
- python-3.x - 如何从python3中的文件解析burp套件请求?
- typo3 - 数据库和日志文件中 sys_log 的不同设置
- symfony - 在 Symfony 中使用 Action 类而不是 Controller
- c - 为什么 C 将 unsigned short int 解释为 unsigned long?
- php - 如何向 Woocommerce 产品标题链接添加标题?
- java - Oracle 连续查询通知是否仅限用于 Java 客户端?
- mysql - 谁知道每天有一笔交易的用户数量?
- docker - 2 个副本 pod 中有 1 个出现 ImagePullBackOff 错误