Implementing element-wise logical and tensor operation

Torch.dtype is the data type of torch.tensor, the torch.dtype doesn’t have bool type, similar to bool type is torch.uint8, your can see torch.dtype here. So if do logical_and operation on two tensor, you should expect to get 0/1s numerical values not True/False bool values. And tensor with uint8 type have logical_and operation &, you need change the tensor data type to unint8 first.

a = torch.tensor([[0, 1], [0.0, 2.3]])
b = torch.tensor([[1, 1], [0.0, 0.0]])
c = torch.zeros_like(a) # all zero with same shape of a
result =  (~torch.eq(a, c)) & (~torch.eq(b, c))
'''
result is a 
 tensor([[0, 1],
        [0, 0]], dtype=torch.uint8)
'''
result.numpy().astype('bool') # change to bool ndarray in numpy
1 Like