Converting PyTorch boolean tensors to integers: A step-by-step guide

While referencing a Pytorch tutorial, I encountered a “RuntimeError: Variable data has to be a tensor, but got list” error in a section of the code.

Question:

Suppose, we have a tensor

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

What is the method to transform it into an integer tensor that has the same values as

[1, 0, 1, 0]

?


Solution:

It only takes one line of code to solve the problem.

To obtain an integer tensor from a tensor

t

that contains values

[True, False, True, False]

, follow these steps.

t = torch.tensor([True, False, True, False])
t_integer = t.long()
print(t_integer)
[1, 0, 1, 0]

Frequently Asked Questions

Posted in Uncategorized