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

PyTorch线性回归模型报错:张量设备不匹配(cuda:0与cpu)求助

问题解决:PyTorch设备不匹配导致的RuntimeError

问题根源

你把模型移到了cuda:0,但输入的张量torch.from_numpy(x_train)默认是在CPU上的——PyTorch要求模型和所有输入张量必须在同一设备上运行,这就是报错的核心原因。

快速修复

修改预测代码,先把输入张量移到cuda设备,之后转numpy前再移回CPU(因为numpy不支持cuda张量):

# 替换你原来的预测代码
x_input = torch.from_numpy(x_train).requires_grad_().to('cuda:0')  # 将输入张量移至cuda
predicted_tensor = model(x_input)
predicted = predicted_tensor.data.cpu().numpy()  # 先转回CPU再转numpy

完整修正代码示例

import torch
import numpy as np
from torch import nn

# 生成模拟训练数据
x_train = np.random.rand(100, 1).astype(np.float32)
y_train = 3 * x_train + 2 + np.random.randn(100, 1).astype(np.float32) * 0.1

# 定义线性回归模型
class LinearRegression(nn.Module):
    def __init__(self):
        super().__init__()
        self.linear = nn.Linear(1, 1)
    
    def forward(self, x):
        return self.linear(x)

# 初始化模型并移至cuda
model = LinearRegression().to('cuda:0')
criterion = nn.MSELoss()
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)

# 训练循环(注意训练时也要把输入/标签移到cuda)
epochs = 1000
for epoch in range(epochs):
    # 把训练数据转成张量并移到cuda
    inputs = torch.from_numpy(x_train).to('cuda:0')
    labels = torch.from_numpy(y_train).to('cuda:0')
    
    optimizer.zero_grad()
    outputs = model(inputs)
    loss = criterion(outputs, labels)
    loss.backward()
    optimizer.step()

# 预测环节(修正后)
x_input = torch.from_numpy(x_train).requires_grad_().to('cuda:0')
predicted_tensor = model(x_input)
predicted = predicted_tensor.data.cpu().numpy()
print(predicted[:5])

报错信息解读

RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu!

这条错误直接明确:当前计算涉及的张量分别分布在cuda和CPU上,PyTorch不允许跨设备执行模型运算,必须保证模型参数、输入、标签等所有相关张量都在同一个设备(要么全CPU,要么全cuda)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 12:50:22