PinkBanter
PinkBanter

Reputation: 1976

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]?

Upvotes: 18

Views: 25233

Answers (1)

PinkBanter
PinkBanter

Reputation: 1976

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]

Upvotes: 29

Related Questions