mask list/tensor with multiple conditions?

Viewed 2256

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?

2 Answers

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

Use np.logical_and to create a mask for conjunction since it returns a new mask that combines both conditions instead of returning a boolean.

targets = np.array([-1,0,1,2,3,4,5,6])
mask = np.logical_and(targets >= 0, targets <= 5) # == [0,1,1,1,1,1,0]

print(targets[mask]) # [0,1,2,3,4,5]

Edit: I see that you're using pytorch, the process is basically the same, simply use torch.logical_and.

Related