How to convert a pytorch tensor of ints to a tensor of booleans?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to convert a pytorch tensor of ints to a tensor of booleans in Python. So Here I am Explain to you all the possible Methods here.

How to convert a pytorch tensor of ints to a tensor of booleans?

1. How to convert a pytorch tensor of ints to a tensor of booleans?

What you're looking for is to generate a boolean mask for the given integer tensor. For this, you can simply check for the condition: “whether the values in the tensor are greater than 0” using simple comparison operator (>) or using torch.gt(), which would then give us the desired result.

2. convert a pytorch tensor of ints to a tensor of booleans

What you're looking for is to generate a boolean mask for the given integer tensor. For this, you can simply check for the condition: “whether the values in the tensor are greater than 0” using simple comparison operator (>) or using torch.gt(), which would then give us the desired result.

Method 1

What you’re looking for is to generate a boolean mask for the given integer tensor. For this, you can simply check for the condition: “whether the values in the tensor are greater than 0” using simple comparison operator (>) or using torch.gt(), which would then give us the desired result.

# input tensor
In : t
Out: tensor([ 0, 10,  0, 16])

# generate the needed boolean mask
In : t > 0
Out: tensor([0, 1, 0, 1], dtype=torch.uint8)

# sanity check
In : mask = t > 0

Out: 'torch.ByteTensor'

Note: In PyTorch version 1.4+, the above operation would return 'torch.BoolTensor'

In : t > 0
Out: tensor([False,  True, False,  True])

# alternatively, use `torch.gt()` API
In : torch.gt(t, 0)
Out: tensor([False,  True, False,  True])

If you indeed want single bits (either 0s or 1s), cast it using:

In : (t > 0).type(torch.uint8)
Out: tensor([0, 1, 0, 1], dtype=torch.uint8)

# alternatively, use `torch.gt()` API
In : torch.gt(t, 0).int()
Out: tensor([0, 1, 0, 1], dtype=torch.int32)

The reason for this change has been discussed in this feature-request issue: issues/4764 – Introduce torch.BoolTensor …

TL;DR: Simple one liner

t.bool().int()

Method 2

Another option would be to simply do:

temp = torch.tensor([0,10,0,16])
temp.bool()
#Returns
tensor([False,  True, False,  True])

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.