PyTorch运行BCEWithLogitsLoss报Float无法转Long错误如何解决?
错误信息翻译
RuntimeError: result type Float can't be cast to the desired output type Long 对应中文为:运行时错误:浮点类型的计算结果无法转换为期望的输出类型长整型。
报错原因
BCEWithLogitsLoss损失函数要求输入的标签张量与预测值张量数据类型一致,均为浮点型。你创建标签张量t时未指定数据类型,默认按整数输入赋值为Long长整型,和浮点型的预测值p计算时类型不匹配,触发报错。
解决方法
两种方案任选其一即可:
- 创建
t时直接指定为浮点类型
t = torch.tensor([[1, 0, 1, 1]], dtype=torch.float32).T p = torch.rand(4,1) torch.nn.BCEWithLogitsLoss()(p, t)
- 对已创建的
t手动转换为浮点类型
t = torch.tensor([[1, 0, 1, 1]]).T.float() p = torch.rand(4,1) torch.nn.BCEWithLogitsLoss()(p, t)
内容的提问来源于stack exchange,提问作者aroyc
相关产品推荐
相关产品推荐

