Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pytorch equivalent of Numpy's logical_and and kin?

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.

like image 986
Sean Lake Avatar asked Feb 08 '19 10:02

Sean Lake


2 Answers

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)
like image 133
kHarshit Avatar answered Oct 13 '22 10:10

kHarshit


logic and:

a * b

logic or:

a + b
like image 2
lbsweek Avatar answered Oct 13 '22 11:10

lbsweek