【问题标题】:Binary mask in TensorflowTensorflow 中的二进制掩码
【发布时间】:2017-03-19 13:02:38
【问题描述】:

我想沿张量的特定维度屏蔽所有其他值,但看不到生成此类蒙版的好方法。例如

#Masking on the 2nd dimension
a = [[1,2,3,4,5],[6,7,8,9,0]
mask = [[1,0,1,0,1],[1,1,1,1,1]]
b = a * mask #would return [[1,0,3,0,5],[6,0,8,0,0]]

有没有简单的方法来生成这样的掩码?

理想情况下,我想做如下的事情:

mask = tf.ones_like(input_tensor)
mask[:,::2] = 0
mask * input_tensor

但是切片分配似乎不像在 Numpy 中那么简单。

【问题讨论】:

    标签: arrays tensorflow masking


    【解决方案1】:

    目前,Tensorflow does not support 类似 numpy 的分配。

    这里有几个解决方法:

    tf.变量

    tf.Tensor 无法更改,但tf.Variable 可以。

    a = tf.constant([[1,2,3,4,5],[6,7,8,9,10]])
    
    mask = tf.Variable(tf.ones_like(a, dtype=tf.int32))
    mask = mask[0,1::2]
    mask = tf.assign(mask, tf.zeros_like(mask))
    # mask = [[1,0,1,0,1],[1,1,1,1,1]]
    
    tf.InteractiveSession()
    tf.global_variables_initializer().run()
    print(mask.eval())
    

    tf.sparse_to_dense()

    indices = tf.range(1, 5, 2)
    indices = tf.stack([tf.zeros_like(indices), indices], axis=1)
    # indices = [[0,1],[0,3]]
    mask = tf.sparse_to_dense(indices, a.shape, sparse_values=0, default_value=1)
    # mask = [[1,0,1,0,1],[1,1,1,1,1]]
    
    tf.InteractiveSession()
    print(mask.eval())
    

    【讨论】:

    • 实际上,这并不能回答 OP 的问题。他们问你如何以编程方式生成这样的掩码?
    • @Multihunter,已修复。
    • 请注意,对于 tf.variable 解决方案,您可能需要设置 trainable=False
    【解决方案2】:

    您可以使用 python 轻松地以编程方式创建这样的张量掩码。然后将其转换为张量。 TensorFlow API 中没有这样的支持。 tf.tile([1,0], num_of_repeats) 可能是创建此类掩码的快速方法,但如果您的列数为奇数,也不是那么好。

    (顺便说一句,如果你最终创建了一个布尔掩码,请使用tf.boolean_mask()

    【讨论】:

    • 我可以保证在我的情况下,我想要屏蔽的维度有偶数个元素,所以这很完美。谢谢!
    • 我不认为 tf.boolean_mask() 保留了原始张量的尺寸。而是返回一维形状的非屏蔽元素。
    【解决方案3】:

    有一个更有效的解决方案,但这肯定会完成工作

    myshape = myTensor.shape
    # create tensors of your tensor's indices:
    row_idx, col_idx = tf.meshgrid(tf.range(myshape[0]), tf.range(myshape[1]), indexing='ij')
    # create boolean mask of odd numbered columns on a particular row.
    mask = tf.where((row_idx == N) * (col_idx % 2 == 0), False, True)
    
    masked = tf.boolean_mask(myTensor, mask)
    

    一般而言,您可以将此方法用于任何此类基于索引的掩码,并适用于 rank-n 张量

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-13
      • 1970-01-01
      • 2015-04-15
      • 2013-08-09
      • 2019-06-03
      • 2018-07-21
      相关资源
      最近更新 更多