Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a tensor of booleans to ints in PyTorch?

Suppose, we have a tensor

t = torch.tensor([True, False, True, False])

How do we convert it to an integer tensor with values [1, 0, 1, 0]?

like image 257
Anjani Anjani Avatar asked Jun 02 '20 11:06

Anjani Anjani


People also ask

How do I get Dtype of a torch tensor?

A PyTorch tensor is homogenous, i.e., all the elements of a tensor are of the same data type. We can access the data type of a tensor using the ". dtype" attribute of the tensor. It returns the data type of the tensor.


1 Answers

The solution is just a single line of code.

To convert a tensor t with values [True, False, True, False] to an integer tensor, just do the following.

t = torch.tensor([True, False, True, False])
t_integer = t.long()
print(t_integer)
[1, 0, 1, 0]
like image 196
Anjani Anjani Avatar answered Oct 19 '22 19:10

Anjani Anjani