python - 如何将整数的pytorch张量转换为 boolean 值的张量?

标签 python casting boolean pytorch tensor

我想将整数张量转换为 boolean 值张量。

具体来说,我希望能够有一个函数来转换 tensor([0,10,0,16])tensor([0,1,0,1])
这在 Tensorflow 中很简单,只需使用 tf.cast(x,tf.bool) .

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

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

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

最佳答案

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

# 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+ 版本中,上述操作将返回 '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])
如果您确实想要单个位(0 s 或 1 s),请使用:
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;博士 :简单的一个类轮
t.bool().int()

关于python - 如何将整数的pytorch张量转换为 boolean 值的张量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53562417/

相关文章:

python - 就地修改子类字符串

python - 如何使用 confluent-kafka-python 确定是否存在 kafka 主题

c# - 在 C# 中将对象 T 转换为 List<T>

c++ - 添加和比较时签署约定

c++ - 转换一个由迭代器指向的对象

python - 如何为 Linux 和 Windows 分发带有嵌入式 Firebird SQL 的 Python 程序

python - pygame Sprite 似乎拉伸(stretch)/增长而不是沿 x 轴移动

java - 检查两个数组是否具有相同顺序的相同元素的方法

linux - 测试返回值 : command not found

java - Java 中按位运算符对 boolean 值的影响