如何将整数的 pytorch 张量转换为布尔值的张量?

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

我想将整数张量转换为布尔张量。

具体来说,我希望能够拥有一个将 tensor([0,10,0,16]) 转换为 tensor([0,1,0,1])

的函数

这在 Tensorflow 中是微不足道的,只需使用 tf.cast(x,tf.bool)

我希望强制转换将所有大于 0 的整数更改为 1,将所有等于 0 的整数更改为 0。这在大多数语言中等同于 !!

由于 pytorch 似乎没有专门的布尔类型可以转换为,这里最好的方法是什么?

编辑:我正在寻找一种矢量化解决方案,而不是遍历每个元素。

您可以使用如下所示的比较:

 >>> a = tensor([0,10,0,16])
 >>> result = (a == 0)
 >>> result
 tensor([ True, False,  True, False])

您正在寻找的是为给定的整数张量生成一个 布尔掩码 。为此,您可以简单地检查条件:“张量中的值是否大于 0”,使用简单的比较运算符 (>) 或使用 torch.gt(),这将给我们想要的结果.

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

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

# sanity check
In [93]: mask = t > 0      

In [94]: mask.type()      
Out[94]: 'torch.ByteTensor'

注意:在PyTorch 1.4+版本中,上述操作会return 'torch.BoolTensor'

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

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

如果您确实需要单个位(0s 或 1s),请使用:

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

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

此功能请求问题中讨论了此更改的原因:issues/4764 - Introduce torch.BoolTensor ...


TL;DR: 简单的一行

t.bool().int()

Convert boolean to number value:

a = torch.tensor([0,4,0,0,5,0.12,0.34,0,0])
print(a.gt(0)) # output in boolean dtype
# output: tensor([False,  True, False, False,  True,  True,  True, False, False])

print(a.gt(0).to(torch.float32)) # output in float32 dtype
# output: tensor([0., 1., 0., 0., 1., 1., 1., 0., 0.])

另一个选择是简单地做:

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

PyTorch 的to(dtype) 方法方便。您可以简单地调用 bool:

>>> t.bool()
tensor([False,  True, False,  True])
>>> t.bool().int()
tensor([0, 1, 0, 1], dtype=torch.int32)