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

PyTorch新手求助:损失函数出现RuntimeError类型转换问题

PyTorch BCEWithLogitsLoss 类型不匹配问题解决

运行代码时触发RuntimeError: result type Float can't be cast to the desired output type Long,尝试将数据转为LongTensor后又出现RuntimeError: mat1 and mat2 must have the same dtype,以下是问题原因和解决方法:

错误信息

RuntimeError                              Traceback (most recent call last)
<ipython-input-19-e09e5cb6e9d7> in <cell line: 13>()
     19 
     20   # 2. Calculate loss and accuracy
---> 21   loss = loss_fn(y_logits,
     22                  y_train)
     23   acc = acc_fn(y_pred,

2 frames
/usr/local/lib/python3.9/dist-packages/torch/nn/functional.py in binary_cross_entropy_with_logits(input, target, weight, size_average, reduce, reduction, pos_weight)
   3163         raise ValueError("Target size ({}) must be the same as input size ({})".format(target.size(), input.size()))
   3164 
-> 3165     return torch.binary_cross_entropy_with_logits(input, target, weight, pos_weight, reduction_enum)
   3166 
   3167 

RuntimeError: result type Float can't be cast to the desired output type Long

问题原因

  1. 损失函数类型要求:nn.BCEWithLogitsLoss要求输入的logits(模型输出)和目标标签(y_train/y_test)必须是相同的浮点类型,但你的标签是LongTensor类型,导致损失计算时类型转换冲突。
  2. 模型输入类型要求:PyTorch模型的线性层参数默认是float32类型,若将输入X转为LongTensor,会导致矩阵乘法时输入与权重 dtype 不匹配,触发第二个错误。

解决方法

只需调整标签的 dtype 为浮点型,保持输入X的原有浮点类型不变:

修改代码片段

在将数据发送到设备后,对标签执行浮点转换:

# Send data to device
X_train, X_test = X_train.to(device), X_test.to(device)
# 将y转换为float类型,与模型输出logits的dtype一致
y_train, y_test = y_train.to(device).float(), y_test.to(device).float()

# 注释掉错误的Long转换代码
# X_train, X_test = X_train.long(), X_test.long()
# y_train, y_test = y_train.long(), y_test.long()

原理说明

  • 模型输入X保持浮点型,确保能与线性层的float32权重正常进行矩阵运算。
  • 标签转为浮点型后,与模型输出的logits dtype 一致,满足BCEWithLogitsLoss的计算要求,不会再出现类型转换错误。

内容的提问来源于stack exchange,提问作者lab_matter

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 03:33:31