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

在Google Colab运行PyTorch基础代码遇类型不匹配错误求解

PyTorch RuntimeError:数据类型不匹配问题解决

问题描述

在DataCamp学习PyTorch深度学习时,一段基础神经网络代码在DataCamp服务器可正常运行,但在Google Colab中执行时触发RuntimeError,提示mat1 and mat2 must have the same dtype, but got Long and Float。代码通过nn.Sequential构建线性模型,传入自定义张量时出错。

原代码

import torch
import torch.nn as nn

input_tensor = torch.tensor([[1, 2, 3, 4, 5, 6, 7, 8]])
model = nn.Sequential(nn.Linear(8, 15),
                      nn.Linear(15, 1)
                     )

output = model(input_tensor)
print(output)

错误信息

---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-31-1092509e4a88> in <cell line: 6>()
      4                      )
      5 
----> 6 output = model(input_tensor)
      7 print(output)

5 frames
/usr/local/lib/python3.10/dist-packages/torch/nn/modules/linear.py in forward(self, input)
    114 
    115     def forward(self, input: Tensor) -> Tensor:
--> 116         return F.linear(input, self.weight, self.bias)
    117 
    118     def extra_repr(self) -> str:

RuntimeError: mat1 and mat2 must have the same dtype, but got Long and Float

问题原因与解决方法

原因

创建input_tensor时,PyTorch默认会根据传入的整数数据生成LongTensor(整数类型张量),而nn.Linear层的权重和偏置参数默认是FloatTensor(浮点类型张量)。矩阵乘法要求参与运算的张量数据类型必须一致,因此触发类型不匹配错误。

解决办法

只需将输入张量转换为浮点类型即可,有两种实现方式:

  1. 创建张量时显式指定数据类型:
input_tensor = torch.tensor([[1, 2, 3, 4, 5, 6, 7, 8]], dtype=torch.float32)
  1. 对已创建的张量进行类型转换:
input_tensor = input_tensor.float()

修改后重新运行代码,即可正常输出模型结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 18:33:12