【问题标题】:Get mask from tensor of indices?从索引张量中获取掩码?
【发布时间】:2018-12-20 03:11:42
【问题描述】:

如果我有一个形状为“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


    【解决方案1】:

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

    【讨论】:

    • 如果掩码跨度的长度(每行中1的数量)不同,有没有办法做到这一点?
    猜你喜欢
    • 2022-01-24
    • 1970-01-01
    • 2022-10-23
    • 1970-01-01
    • 2020-05-02
    • 1970-01-01
    • 2019-12-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多