Pytorch : AttributeError: 'function' object has no attribute 'cuda'

Pytorch : AttributeError: 'function' object has no attribute 'cuda'

import torch
import models
model_names = sorted(name for name in models.__dict__
                     if name.islower() and not name.startswith("__")
                     and callable(models.__dict__[name]))
model = models.__dict__['resnet18']
model = torch.nn.DataParallel(model,device_ids = [0])  #PROBLEM CAUSING LINE
model.to('cuda:0')

要运行此代码,您需要克隆此存储库:https://github.com/SoftwareGift/FeatherNets_Face-Anti-spoofing-Attack-Detection-Challenge-CVPR2019.git

请运行将这段代码放在克隆目录的根文件夹中。

我收到跟随错误 AttributeError: 'function' object has no attribute 'cuda' 我也尝试过使用 torch.device 对象来实现相同的功能,但它会导致相同的错误。 请询问所需的任何其他详细信息。 PyTorch 新手在这里 python:3.7 pytorch:1.3.1

替换

model = torch.nn.DataParallel(model,device_ids = [0])

model = torch.nn.DataParallel(model(), device_ids=[0])

(注意 DataParallel 中模型后的 ())。区别很简单:models 模块包含创建模型的 classes/functions 而不是模型的 实例 。如果跟踪导入,您会发现 models.__dict__['resnet18'] 解析为 this 函数。由于 DataParallel 包装了一个实例,而不是 class 本身,因此它是不兼容的。 () 调用此模型构建 function/class 构造函数来创建此模型的实例。

下面是一个更简单的例子

class MyNet(nn.Model):
    def __init__(self):
        self.linear = nn.Linear(4, 4)
    def forward(self, x):
        return self.linear(x)

model = nn.DataParallel(MyNet) # this is what you're doing
model = nn.DataParallel(MyNet()) # this is what you should be doing

您的错误消息抱怨 function(因为没有 ()model 属于 function 类型)没有属性 cuda,这是一个nn.Model实例.

的方法