【问题标题】:Pytorch Resnet model error if FC layer is changed in Colab如果在 Colab 中更改 FC 层,则 Pytorch Resnet 模型错误
【发布时间】:2021-03-02 15:13:18
【问题描述】:

如果我只是从 Colab 中的 Pytorch 导入 Resnet 模型,并使用它来训练我的数据集,则没有问题。但是,当我尝试更改最后一个 FC 层以将输出特征从 1000 更改为 9(这是我的数据集的类数)时,会出现以下错误。

RuntimeError: Tensor for 'out' is on CPU, Tensor for argument #1 'self' is on CPU, but expected them to be on GPU (while checking arguments for addmm)

工作版本:

import torchvision.models as models
#model = Net()
model=models.resnet18(pretrained=True)

# defining the optimizer
optimizer = Adam(model.parameters(), lr=0.07)
# defining the loss function
criterion = CrossEntropyLoss()
# checking if GPU is available
if torch.cuda.is_available():
    model = model.cuda()
    criterion = criterion.cuda()

有错误的版本:

import torchvision.models as models
#model = Net()
model=models.resnet18(pretrained=True)

# defining the optimizer
optimizer = Adam(model.parameters(), lr=0.07)
# defining the loss function
criterion = CrossEntropyLoss()
# checking if GPU is available
if torch.cuda.is_available():
    model = model.cuda()
    criterion = criterion.cuda()
model.fc = torch.nn.Linear(512, 9)

错误发生在训练发生的阶段,也就是

outputs = model(images)

我应该如何解决这个问题?

【问题讨论】:

    标签: pytorch google-colaboratory resnet


    【解决方案1】:

    简单的错误,fc层应该在声明模型为cuda之前实例化。 即

    model=models.resnet18(pretrained=True)
    model.fc = torch.nn.Linear(512, 9)
    if torch.cuda.is_available():
        model = model.cuda()
    

    【讨论】:

      猜你喜欢
      • 2019-03-04
      • 2020-09-09
      • 2018-10-12
      • 1970-01-01
      • 2021-10-24
      • 2020-07-21
      • 1970-01-01
      • 2017-10-24
      • 1970-01-01
      相关资源
      最近更新 更多