Logical operation in torch.where

I want to use multiple conditions in torch.where function.
But It seems to have some problems with the logical operation.

x = torch.randn(3, 2)
y = torch.ones(3, 2)
torch.where(x > 0 or x<0.1, x, y)
Error: bool value of Tensor with more than one value is ambiguous
torch.where(x > 0 | x<0.1, x, y)
Error: unsupported operand type(s) for |: ‘int’ and ‘Tensor’

There is no introduction of logical operation in pytorch docs.
So I want to know if this can be implemented or if there is an alternative method to do this.

Any help would be much appreciated.

You need to put the conditions in parentheses. This is because ‘|’ has higher precedence than the comparison operators. That’s why you got the error message saying “unsupported operand type(s) for |: ‘int’ and ‘Tensor’”

x = torch.randn(3, 2)
y = torch.ones(3, 2)
torch.where((x > 0) | (x < 0.1), x, y)
3 Likes

Thank you so much.
This is a mistake in python. :expressionless:

1 Like