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]
?
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With