【发布时间】:2021-07-19 07:31:42
【问题描述】:
我正在尝试通过以下方式推动我的模式和数据、图像和标签在 GPU 上运行:
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
接着是:
count = 0
loss_list = []
iteration_list = []
accuracy_list = []
epochs = 30
for epoch in range(epochs):
for i, (images, labels) in enumerate(trainloader):
net = net.to(device)
images.to(device)
labels.to(device)
optimizer.zero_grad()
outputs = net(images)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
count += 1
if count % 50 == 0:
correct = 0
total = 0
for i, (images, labels) in enumerate(testloader):
images.to(device)
labels.to(device)
outputs = net(images)
predicted = torch.max(outputs.data, 1)[1]
total += len(labels)
correct += (predicted == labels).sum()
accuracy = 100 * correct / float(total)
loss_list.append(loss.data)
iteration_list.append(count)
accuracy_list.append(accuracy)
if count % 500 == 0:
print("Iteration: {} Loss: {} Accuracy: {} %".format(count, loss.data, accuracy))
我明确地将我的模型和数据推送到设备,但是我遇到了错误:
RuntimeError Traceback (most recent call last)
<ipython-input-341-361b906da73d> in <module>()
12
13 optimizer.zero_grad()
---> 14 outputs = net(images)
15 loss = criterion(outputs, labels)
16 loss.backward()
4 frames
/usr/local/lib/python3.7/dist-packages/torch/nn/modules/conv.py in _conv_forward(self, input, weight, bias)
394 _pair(0), self.dilation, self.groups)
395 return F.conv2d(input, weight, bias, self.stride,
--> 396 self.padding, self.dilation, self.groups)
397
398 def forward(self, input: Tensor) -> Tensor:
RuntimeError: Input type (torch.FloatTensor) and weight type (torch.cuda.FloatTensor) should be the same
我觉得我通过将模型和数据都推送到 GPU 来做正确的事情,但我不知道为什么它不起作用。有人知道出了什么问题吗?提前谢谢你。
【问题讨论】: