qicheng wang
qicheng wang

Reputation: 43

Pytorch: TypeError: list is not a Module subclass

I want to extract some layers from a model, so I write

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

but get error: list is not a Moudule subclass. I know I should write

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

but why I must add the * ??? If I just wanna to get the [] including the layers, I must write

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

In this situation, the * does not work and get error

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

Why???

Upvotes: 1

Views: 3401

Answers (1)

Harshit Kumar
Harshit Kumar

Reputation: 12857

list(model.children())[:7] returns a list, but the input of nn.Sequential() requires the modules to be an OrderedDict or to be added directly, not in a python list.

nn.Sequential Modules will be added to it in the order they are passed in the constructor. Alternatively, an OrderedDict of modules can be passed in.

# 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))

That's why you need to unpack the list using *. It can only be used inside a function, hence, it doesn't work in your last case. Read * in python

Upvotes: 1

Related Questions