You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 13:06:06