我试着对下面的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相关问答推荐

网站抓取:当我使用Chrome DevTools中的网络选项卡时,找不到正确的URL来提供我想要的数据

Python根据阈值对数字进行分组

在 sum() 中将字符串转换为 int (或 float)

我们可以在每个可以使用 Pandas Join 的用例中使用 Pandas merge 吗?

我无法直接在 VSCode 中运行该程序,但可以使用 VScode 中的终端运行它

Python - 根据条件附加 NULL 值

如何获取自定义文件上传路径的对象ID?

如何获取实例化 `types.GenericAlias` 的下标类?

公开数据中的卫星图像网页抓取优化

获取以特定字母开头的姓氏

聚合(aggregate)为最多包含两个元素的列表

如何将数据框中的每一行转换为具有属性的 node ?

python3源的类图查看器应用程序

Pythonic,自定义警告

numpy.ndarray 与 pandas.DataFrame

如何在多核上运行 Keras?

ImportError:无法在 PyQt5 中导入名称QStringList

python 3的蓝牙库

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

尾部斜杠的 FastAPI 重定向返回非 ssl 链接