python - 如何将带有 boolean_mask 的掩码应用于最后一个维度

标签 python tensorflow tensorflow2.0

我正在尝试将三角形 mask 应用于张量的最后两个维度。

我正在做这样的事情:

a, b, c, d = 2, 2, 2, 2
tensor = tf.random.uniform((a, b, c, d))

lower_triangular = tf.linalg.band_part(tf.reshape(tf.ones((c, d)), shape=(1, 1, c, d)), -1, 0)

tf.boolean_mask(tensor, lower_triangular == 0)

最后一条指令失败,出现以下异常

/usr/local/lib/python3.6/dist-packages/tensorflow/python/util/dispatch.py in wrapper(*args, **kwargs)
    199     """Call target, and fall back on dispatchers if there is a TypeError."""
    200     try:
--> 201       return target(*args, **kwargs)
    202     except (TypeError, ValueError):
    203       # Note: convert_to_eager_tensor currently raises a ValueError, not a

/usr/local/lib/python3.6/dist-packages/tensorflow/python/ops/array_ops.py in boolean_mask_v2(tensor, mask, axis, name)
   1824   ```
   1825   """
-> 1826   return boolean_mask(tensor, mask, name, axis)
   1827 
   1828 

/usr/local/lib/python3.6/dist-packages/tensorflow/python/util/dispatch.py in wrapper(*args, **kwargs)
    199     """Call target, and fall back on dispatchers if there is a TypeError."""
    200     try:
--> 201       return target(*args, **kwargs)
    202     except (TypeError, ValueError):
    203       # Note: convert_to_eager_tensor currently raises a ValueError, not a

/usr/local/lib/python3.6/dist-packages/tensorflow/python/ops/array_ops.py in boolean_mask(tensor, mask, name, axis)
   1744     if axis_value is not None:
   1745       axis = axis_value
-> 1746       shape_tensor[axis:axis + ndims_mask].assert_is_compatible_with(shape_mask)
   1747 
   1748     leading_size = gen_math_ops.prod(shape(tensor)[axis:axis + ndims_mask], [0])

/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/tensor_shape.py in assert_is_compatible_with(self, other)
   1132     """
   1133     if not self.is_compatible_with(other):
-> 1134       raise ValueError("Shapes %s and %s are incompatible" % (self, other))
   1135 
   1136   def most_specific_compatible_shape(self, other):

ValueError: Shapes (2, 2, 2, 2) and (1, 1, 2, 2) are incompatible

如果我创建一个与我的张量形状完全相同的 mask ,我会得到一个奇怪的结果:

a, b, c, d = 2, 2, 2, 2
tensor = tf.random.uniform((a, b, c, d))

lower_triangular = tf.linalg.band_part(tf.ones((a, b, c, d)), -1, 0)

result = tf.boolean_mask(tensor, lower_triangular == 0)
result.shape

结果的形状为 TensorShape([4]) 不确定这是在做什么。

敷面膜的正确方法应该是怎样的?

最佳答案

The result has a shape TensorShape([4]) not sure what is this doing.

你有一个像这样的张量:

   [[[[0.7786709 , 0.67790854],
     [0.72038054, 0.8475332 ]],

    [[0.945917  , 0.496732  ],
     [0.05510616, 0.44530773]]],


   [[[0.05596864, 0.59605396],
     [0.5459013 , 0.80567217]],

    [[0.1393286 , 0.74939907],
     [0.1695472 , 0.55127   ]]]]

还有像这样的面具:

  [[[[False,  True],
     [False, False]],

    [[False,  True],
     [False, False]]],


   [[[False,  True],
     [False, False]],

    [[False,  True],
     [False, False]]]]

所以,你最终会得到这样的结果:

[0.67790854, 0.496732  , 0.59605396, 0.74939907]

我们可以看到掩码“过滤”掉了掩码为假的所有值并将结果展平。

因此,如果您的掩码中 True 值的总数为 n,并且您匹配了张量和掩码的维度,那么您最终会得到一个形状为 的张量>[n].

我不清楚您对蒙版操作的期望结果是什么,但是,如果扁平化让您感到惊讶,那么听起来您可能只是想要这样的结果?:

  [[[[0.        , 0.67790854],
     [0.        , 0.        ]],

    [[0.        , 0.496732  ],
     [0.        , 0.        ]]],


   [[[0.        , 0.59605396],
     [0.        , 0.        ]],

    [[0.        , 0.74939907],
     [0.        , 0.        ]]]]

你可以通过乘以掩码得到它(当然,我们需要先转换它)。

也许是这样的:

tf.cast(lower_triangular == 0, tf.float32) * tensor

W.R.T 原始错误信息:

如果要应用与张量具有相同秩的掩码,则所有维度都需要相等。而您可以应用维数较少的掩码(我怀疑您正试图这样做)。

例如:

tf.boolean_mask(tensor, lower_triangular[0,0] == 0)

给出:

[[[0.945917  , 0.496732  ],
  [0.05510616, 0.44530773]]]

我们还可以控制掩码应用于哪个。所以,例如:

tf.boolean_mask(tensor, lower_triangular[0,0] == 0, axis=2)

返回:

[[[0.67790854],
  [0.496732  ]],

  [[0.59605396],
  [0.74939907]]]

蒙版应用于第 2 个轴(而不是默认的第 0 个轴)

关于python - 如何将带有 boolean_mask 的掩码应用于最后一个维度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63554912/

相关文章:

python - 运行 2 个 python 脚本而不互相影响

python - 如何修复 - 导入 keras 时出现 ImportError : DLL load failed,

python - 如何防止 TensorFlow eval 梯度

python - ValueError : Cannot feed value of shape (60000, ) 对于张量 'Placeholder_1:0' ,其形状为 '(60000, 1)'

Tensorflow 对象检测 API : Train from exported model checkpoint

python - 函数中的嵌套渐变带 (TF2.0)

ubuntu - Tensorflow 2.9 nvidia 图形兼容性问题

python - Pandas - 将两个数据帧中最近的事件与条件连接起来

python - 使用字典理解python删除多个关键项目

python - 在 __init__() 中不创建对象的最佳方法是什么