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 least two devices, cuda:0 and cpu! (when checking arugment for argument mat1 in method wrapper_addmm)
- 错误原因在于,我们初学者的计算机大部分都是单gpu的,而目前封装好的函数大部分是默认支持多gpu同步训练。因此我们首先需要确定本次实验所要使用的设备,然后将所有的网络模型以及tensor全部加入到该设备上去。
- 参考学习链接:https://tangshusen.me/Dive-into-DL-PyTorch/#/
二、解决方法
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
net = net.to(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
batch_size = 256
train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size)
num_inputs = 784
num_outputs = 10
class FlattenLayer(nn.Module):
def __init__(self):
super(FlattenLayer, self).__init__()
def forward(self, x):
return x.view(x.shape[0], -1)
from collections import OrderedDict
net = nn.Sequential(
OrderedDict([
('flatten', FlattenLayer()),
('linear', nn.Linear(num_inputs, num_outputs))
])
)
init.normal_(net.linear.weight, mean=0, std=0.01)
init.constant_(net.linear.bias, val=0)
loss = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(net.parameters(), lr=0.1)
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
net = net.to(device)
def accuracy(y_hat, y):
return (y_hat.argmax(dim=1) == y).float().mean().item()
def evaluate_accuracy(data_iter, net):
acc_sum, n = 0.0, 0
for 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
def train_ch3_my(net, train_iter, test_iter, loss, num_epochs, batch_size,
params=None, lr=None, optimizer=None):
for epoch in range(num_epochs):
train_l_sum, train_acc_sum, n = 0.0, 0.0, 0
for 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 is not None:
optimizer.zero_grad()
elif params is not None and params[0].grad is not None:
for param in params:
param.grad.data.zero_()
l.backward()
if optimizer is None:
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))
num_epochs = 5
train_ch3_my(net, train_iter, test_iter, loss, num_epochs, batch_size, None, None, optimizer)
|