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

mask list/tensor with multiple conditions?

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

The following code masks fine

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

However, when I try masking with two conditions, it gives an error of RuntimeError: Boolean value of Tensor with more than one value is ambiguous

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

is there a way to do this?

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

You are making a mistake while using brackets. Bracket around each of the conditions so that NumPy considers them as individual arrays.

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])

You can create some complex logic using multiple masks and then directly index an array with them. Example - XNOR can be written as ~(mask1 ^ mask2)

enter image description here