pytorch参数转不到cuda,RuntimeError: Input type (torch.cuda.FloatTensor) and weight type(torch.FloatTensor

pytorch模型参数(卷积)转不到cuda
错误提示:RuntimeError: Input type (torch.cuda.FloatTensor) and weight type(torch.FloatTensor)
错误情况:

class my_layer(nn.Module):
    def __init__(self, num_layer):
        super(my_layer, self).__init__(**kwargs)
        self.dim=[1000, 500, 200]
        self.length = len(dim) - 1
        self.layers = []
        for i in range(self.length):
            self.layers.append(nn.Conv2d(dim[i], dim[i+1], 3, padding=1))
    
    def forward(x):
        for i in range(self.length):
            x = self.layers[i](x)
        return x

正确情况一(麻烦):

class my_layer(nn.Module):
    def __init__(self, num_layer):
        super(my_layer, self).__init__(**kwargs)
        self.dim=[1000, 500, 200]
        self.length = len(dim) - 1
        self.layername = []
        for i in range(self.length):
        	layer  = nn.Conv2d(nn.Conv2d(dim[i], dim[i+1], 3, padding=1)
        	layer_name = 'layer{}'.format(i + 1)
        	self.add_module(layer_name, layer)
            self.layername.append(layer_name )
    
    def forward(x):
        for i, layername in enumerate(self.layername):
            layer = getattr(self, layername)
            x = layer(x)
        return x

正确情况二:(推荐)
self.layers = nn.ModuleList(),其他都不变
问题就是模型加载到显卡的时候不能识别python原生list

class my_layer(nn.Module):
    def __init__(self, num_layer):
        super(my_layer, self).__init__(**kwargs)
        self.dim=[1000, 500, 200]
        self.length = len(dim) - 1
        self.layers = nn.ModuleList()
        for i in range(self.length):
            self.layers.append(nn.Conv2d(dim[i], dim[i+1], 3, padding=1))
    
    def forward(x):
        for i in range(self.length):
            x = self.layers[i](x)
        return x

你可能感兴趣的:(pytorch常见报错,pytorch,深度学习,python)