RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu! (when checking arugment for argument mat1 in method wrapper_addmm)
# 1.规定唯一设备(如果cuda可用则使用cuda:0,否则使用cpu)
device = torch.device("cuda:0"if torch.cuda.is_available()else"cpu")# 2.将网络结构net加入到device中去
net = net.to(device)# 3.多个函数中每次从迭代器中读出tensor都需要加入到device中去for X, y in data_iter:
X = X.to(device)
y = y.to(device)
三、完整代码
import torch
from torch import nn
from torch.nn import init
import numpy as np
import sys
sys.path.append("..")import d2lzh_pytorch as d2l
# 1.设定批次大小,生成读取数据迭代器
batch_size =256
train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size)# 2.构建网络结构
num_inputs =784
num_outputs =10# 2.1扁平层,将二维图像压为一维classFlattenLayer(nn.Module):def__init__(self):super(FlattenLayer, self).__init__()defforward(self, x):# x shape: (batch, *, *, ...)return x.view(x.shape[0],-1)from collections import OrderedDict
net = nn.Sequential(
OrderedDict([('flatten', FlattenLayer()),('linear', nn.Linear(num_inputs, num_outputs))]))# 3.初始化待训练参数
init.normal_(net.linear.weight, mean=0, std=0.01)
init.constant_(net.linear.bias, val=0)# 4.定义损失函数以及优化方法
loss = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(net.parameters(), lr=0.1)# 5.规定设备,并将net放入设备上
device = torch.device("cuda:0"if torch.cuda.is_available()else"cpu")
net = net.to(device)# 6.定义准确度函数、根据测试集计算准确度函数defaccuracy(y_hat, y):return(y_hat.argmax(dim=1)== y).float().mean().item()defevaluate_accuracy(data_iter, net):
acc_sum, n =0.0,0for X, y in data_iter:
X = X.to(device)
y = y.to(device)
acc_sum +=(net(X).argmax(dim=1)== y).float().sum().item()
n += y.shape[0]return acc_sum / n
# 7.重写train_ch3函数,在读取tensor时将tensor加入到device上deftrain_ch3_my(net, train_iter, test_iter, loss, num_epochs, batch_size,
params=None, lr=None, optimizer=None):for epoch inrange(num_epochs):
train_l_sum, train_acc_sum, n =0.0,0.0,0for X, y in train_iter:
X = X.to(device)
y = y.to(device)
y_hat = net(X)
l = loss(y_hat, y).sum()if optimizer isnotNone:
optimizer.zero_grad()elif params isnotNoneand params[0].grad isnotNone:for param in params:
param.grad.data.zero_()
l.backward()if optimizer isNone:
d2l.sgd(params, lr, batch_size)else:
optimizer.step()
train_l_sum += l.item()
train_acc_sum +=(y_hat.argmax(dim=1)== y).sum().item()
n += y.shape[0]
test_acc = evaluate_accuracy(test_iter, net)print('epoch %d, loss %.4f, train acc %.3f, test acc %.3f'%(epoch +1, train_l_sum / n, train_acc_sum / n, test_acc))# 8.进行模型训练
num_epochs =5
train_ch3_my(net, train_iter, test_iter, loss, num_epochs, batch_size,None,None, optimizer)
Error:all tensors must be on devices[0] 初学者解决方案一、问题简介二、解决方法三、完整代码一、问题简介作为Pytorch初学者,我跟随教程实现图像分类数据集 FashionMinist 的 softmax 多分类项目。过程中最后一步调用d2lzh_pytorch包中的train_ch3函数,产生如下报错提示。RuntimeError: Expected all tensors to be on the same device, but found at lea