Does Pytorch have an equivalent of Numpy's element-wise logical operators (logical_and
, logical_or
, logical_not
, and logical_xor
)? Calling the Numpy functions on Pytorch tensors seems to work well enough when using the CPU, even producing a Pytorch tensor as output. I mainly ask because I assume this would not work so well if the pytorch calculation were running in the GPU.
I've looked through Pytorch's documentation index at all functions containing the string "and" and none seem relevant.
Update: With Pytorch 1.2, PyTorch introduced torch.bool
datatype, which can be used using torch.BoolTensor
:
>>> a = torch.BoolTensor([False, True, True, False]) # or pass [0, 1, 1, 0]
>>> b = torch.BoolTensor([True, True, False, False])
>>> a & b # logical and
tensor([False, True, False, False])
PyTorch supports logical operations on ByteTensor
. You can use logical operations using &
, |
, ^
, ~
operators as follows:
>>> a = torch.ByteTensor([0, 1, 1, 0])
>>> b = torch.ByteTensor([1, 1, 0, 0])
>>> a & b # logical and
tensor([0, 1, 0, 0], dtype=torch.uint8)
>>> a | b # logical or
tensor([1, 1, 1, 0], dtype=torch.uint8)
>>> a ^ b # logical xor
tensor([1, 0, 1, 0], dtype=torch.uint8)
>>> ~a # logical not
tensor([1, 0, 0, 1], dtype=torch.uint8)
logic and:
a * b
logic or:
a + b
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With