pytorch 中 Subtraction, the `-` operator, with a bool tensor is not supported.解决方案

在运行某头发分割github代码时,pytorch 报错 “Subtraction, the - operator, with a bool tensor is not supported.”
原代码为:

tp = y_pred * y == 1
tn = y_pred + y == 0
fp = y_pred - y == 1
fn = y - y_pred == 1

原因是pytorch最新版本中,不支持bool型与int型减法
测试:

a = torch.tensor([1, 1, 1, 0, 0, 0])
b = torch.tensor([True, False, True, False, True, False])

c = a + b
d = a * b
e = a - b

print(c)
print(d)
print(e)

显示:

RuntimeError: Subtraction, the `-` operator, with a bool tensor is not supported. If you are trying to invert a mask, use the `~` or `logical_not()` operator instead.

解决方案:
计算时把bool转化为int型的tensor
b.int()

a = torch.tensor([1, 1, 1, 0, 0, 0])
b = torch.tensor([True, False, True, False, True, False])

c = a + b
d = a * b
e = a - b.int()

print(c)
print(d)
print(e)

结果显示:

tensor([2, 1, 2, 0, 1, 0])
tensor([1, 0, 1, 0, 0, 0])
tensor([ 0,  1,  0,  0, -1,  0])

以此原理,原代码改为:

tp = y_pred * y == 1
tn = y_pred + y == 0
fp = y_pred.int() - y == 1
fn = y - y_pred.int() == 1

成功运行!!

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值