你需要生成一个给定整数张量的布尔掩码。为此,可以使用简单比较运算符(
>
)或
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
还是
1
),请使用以下方式进行转换:
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 - 引入torch.BoolTensor ...。
TL;DR: 简单的一句话总结
t.bool().int()
bool(int)
。或者在 numpy 中:使用array.astype(...)
。 - Thomas Langastype
版本几乎肯定是矢量化的。 - Thomas Lang.astype
,因此一个人必须转换为 numpy->转换类型 -> 加载到 pytorch
,在我看来这是低效的。 - Umang Gupta