【问题标题】:Boolean mask Tensorflow, tf.boolean_mask - Maintain dimensions of original tensor布尔掩码 Tensorflow,tf.boolean_mask - 保持原始张量的尺寸
【发布时间】:2018-10-30 21:58:48
【问题描述】:

我有一个长度相同的一维 tensor 和一个 Booleans 的一维数组。

我想使用布尔数组作为张量上的掩码,这样 True 会保留张量中的原始元素值,而 False 会将张量中的原始元素值设置为零。

例如

Tensor = [1,2,3,4,5]
Array = [True, False, False, False, True]

将布尔掩码应用于张量:

Desired result = [1, 0, 0, 0, 5]
Result with tf.boolean_mask = [1, 5]

我曾尝试使用tf.boolean_mask(tensor, array),但是,这会将生成的张量的维度减少为仅包含True 元素,在上例中为2 个维度。

如何在保持张量原始尺寸的同时将布尔掩码应用于张量?

【问题讨论】:

    标签: python tensorflow mask


    【解决方案1】:

    你可以使用tf.where:

    tf.where(array, tensor, tf.zeros_like(tensor))
    

    【讨论】:

      【解决方案2】:

      您可以将布尔掩码转换为 tf.int32 张量并使用 tf.multiply

      mask = tf.constant([True, False, False, False, True])
      A = tf.range(1,6)
      
      with tf.Session() as sess:
         res = sess.run( \
                tf.multiply(A, tf.cast(mask, tf.int32)) \
               ) # [1, 0, 0, 0, 5]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-05-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-08-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多