pythonpytorchintegerbooleantensor

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


Solution

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