首页 > 解决方案 > Pytorch:TypeError:列表不是模块子类

问题描述

我想从模型中提取一些层,所以我写

nn.Sequential(list(model.children())[:7])

但得到错误:列表不是 Moudule 子类。我知道我应该写

nn.Sequential(*list(model.children)[:7])

但为什么我必须添加 * ??? 如果我只想获得包含图层的 [],我必须写

layer = list(model.children())[:7]
but not
layer = *list(model.children())[:7]

在这种情况下,* 不起作用并出现错误

    layer = *list(model_ft.children())[:3]
           ^
SyntaxError: can't use starred expression here

为什么???

标签: pythondeep-learningpytorchresnet

解决方案


list(model.children())[:7]返回一个列表,但 的输入nn.Sequential()要求模块是 OrderedDict 或直接添加,而不是在 python 列表中。

nn.Sequential模块将按照它们在构造函数中传递的顺序添加到其中。或者,可以传入一个 OrderedDict 模块。

# nn.Sequential(list(model.children)[:3]) means, which is wrong
nn.Sequential([Conv2d(3, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3)),
ReLU(inplace=True),
MaxPool2d(kernel_size=3, stride=2, padding=1, dilation=1, ceil_mode=False)])

# nn.Sequential(*list(model.children)[:3]) mean
nn.Sequential(Conv2d(3, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3)),
ReLU(inplace=True),
MaxPool2d(kernel_size=3, stride=2, padding=1, dilation=1, ceil_mode=False))

这就是为什么您需要使用*. 它只能在函数内部使用,因此,它在您的最后一种情况下不起作用。在 python 中读取*


推荐阅读