我想将整数张量转换为 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/