首页 文章

从索引的张量中获取掩码?

提问于
浏览
0

如果我有一个形状张量“batch_size * length * hidden_size”,并且我有另一个索引 Span 张量的形状“batch_size * 2”,其中索引 Span 张量指示我想从第一张量中选择的开始和结束索引 . 假设索引 Span 张量具有值

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

然后我想从第一个张量得到以下面具

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

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

1 回答

  • 0

    我们可以使用 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.]]
    

相关问题