我试着对下面的CNN进行如下训练,但我一直在犯同样的错误.cuda()我不知道如何修复它.以下是我迄今为止的一段代码.

import matplotlib.pyplot as plt
import numpy as np
import torch
from torch import nn
from torch import optim
import torch.nn.functional as F
import torchvision
from torchvision import datasets, transforms, models
from torch.utils.data.sampler import SubsetRandomSampler


data_dir = "/home/ubuntu/ML2/ExamII/train2/"
valid_size = .2

# Normalize the test and train sets with torchvision
train_transforms = transforms.Compose([transforms.Resize(224),
                                           transforms.ToTensor(),
                                           ])

test_transforms = transforms.Compose([transforms.Resize(224),
                                          transforms.ToTensor(),
                                          ])

# ImageFolder class to load the train and test images
train_data = datasets.ImageFolder(data_dir, transform=train_transforms)
test_data = datasets.ImageFolder(data_dir, transform=test_transforms)


# Number of train images
num_train = len(train_data)
indices = list(range(num_train))
# Split = 20% of train images
split = int(np.floor(valid_size * num_train))
# Shuffle indices of train images
np.random.shuffle(indices)
# Subset indices for test and train
train_idx, test_idx = indices[split:], indices[:split]
# Samples elements randomly from a given list of indices
train_sampler = SubsetRandomSampler(train_idx)
test_sampler = SubsetRandomSampler(test_idx)
# Batch and load the images
trainloader = torch.utils.data.DataLoader(train_data, sampler=train_sampler, batch_size=1)
testloader = torch.utils.data.DataLoader(test_data, sampler=test_sampler, batch_size=1)


#print(trainloader.dataset.classes)

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = models.resnet50(pretrained=True)

model.fc = nn.Sequential(nn.Linear(2048, 512),
                                 nn.ReLU(),
                                 nn.Dropout(0.2),
                                 nn.Linear(512, 10),
                                 nn.LogSigmoid())
                                 # nn.LogSoftmax(dim=1))
# criterion = nn.NLLLoss()
criterion = nn.BCELoss()
optimizer = optim.Adam(model.fc.parameters(), lr=0.003)
model.to(device)

#Train the network
for epoch in range(2):  # loop over the dataset multiple times

    running_loss = 0.0
    for i, data in enumerate(trainloader, 0):
        # get the inputs; data is a list of [inputs, labels]
        inputs, labels = data

        # zero the parameter gradients
        optimizer.zero_grad()

        # forward + backward + optimize
        outputs = model(inputs)
        loss = criterion(outputs, labels)
        loss.backward()
        optimizer.step()

        # print statistics
        running_loss += loss.item()
        if i % 2000 == 1999:    # print every 2000 mini-batches
            print('[%d, %5d] loss: %.3f' %
                  (epoch + 1, i + 1, running_loss / 2000))
            running_loss = 0.0

print('Finished Training')

然而,我在控制台中不断遇到这个错误:

运行时错误:输入类型(torch.FloatTensor)和权重类型(torch.cuda.FloatTensor)应该相同`

有没有关于如何修复的 idea ?我读到可能这个模型还没有被推到我的GPU中,但不知道如何修复它.谢谢

推荐答案

你得到这个错误是因为你的模型在GPU上,但是你的数据在CPU上.所以,你需要把你的输入张量发送到GPU.

inputs, labels = data                         # this is what you had
inputs, labels = inputs.cuda(), labels.cuda() # add this line

或者像这样,为了与代码的其余部分保持一致:

device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")

inputs, labels = inputs.to(device), labels.to(device)

如果你的输入张量在GPU上,但你的模型权重不在GPU上,那么same error将会升高.在这种情况下,你需要将模型权重发送到GPU.

model = MyModel()

if torch.cuda.is_available():
    model.cuda()

这是cuda()cpu()的文档,它们是相反的.

Python-3.x相关问答推荐

CSV-DAT 转换时将引号添加到数据中

合并所有文件并获取特定列数据

将水平堆叠的数据排列成垂直

按字母顺序排序列表 (OrderFilter),条件是值为 '' 的条目位于列表 DRF 的末尾

将数据框中的值与另一个数据框中的多列进行比较,以获取条目以有效方式匹配的列表列表

删除给定数组中所有元素为True的所有子数组

如何使用 django rest 框架在 self forienkey 中删除多达 n 种类型的数据?

为什么 Multiprocessing 的 Lock 不会阻止其他进程使用对象?

如何将虚拟变量列转换为多列?

Python - 如何从同一台客户端机器运行多个Flask应用程序

运行 PyCharm 测试时如何解决django.core.exceptions.ImproperlyConfigured:找不到 GDAL 库?

if 语句中冒号的语法错误

迭代器也是可迭代的吗?

在 ubuntu 20.04 中安装 libpq-dev 时出现问题

在python中打印下标

变量类型注解NameError不一致

使用 asyncio 的多个循环

为什么变量 = 对象不像变量 = 数字那样工作

如何为 Python 3.x 安装 psycopg2?

调用 Python doctest 时如何启用省略号?