Warm tip: This article is reproduced from serverfault.com, please click

python-具有多个条件的掩码列表/张量?

(python - mask list/tensor with multiple conditions?)

发布于 2021-01-07 01:03:31

以下代码掩码很好

mask = targets >= 0
targets = targets[mask]

但是,当我尝试使用两个条件进行屏蔽时,会出现错误 RuntimeError: Boolean value of Tensor with more than one value is ambiguous

mask = (targets >= 0 and targets <= 5)
targets = targets[mask]

有没有办法做到这一点?

Questioner
josh
Viewed
0
Akshay Sehgal 2021-01-07 09:30:27

你在使用括号时犯了一个错误。将每个条件括起来,以便 NumPy 将它们视为单独的数组。

targets = np.random.randint(0,10,(10,))

mask = (targets>=0) & (targets<=5) #<----------

print(mask)
targets[mask]
[ True False  True False False  True  True  True False  True]
array([4, 1, 3, 1, 5, 3])

你可以使用多个掩码创建一些复杂的逻辑,然后使用它们直接索引数组。示例 - XNOR 可以写为~(mask1 ^ mask2)

在此处输入图片说明