python - 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
为什么???
解决方案
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 中读取*
推荐阅读
- python - exe中的可变偏移量
- angular - Angular 6 供应商和主 js 花费太多时间来加载数据
- java - 如何对 YouTube 视频使用字符串插值
- python - 使用数据存储对 python 3 进行本地测试
- c# - 3-case if(小于零,大于零,零)是否有内置函数?
- infinite-loop - Cobol:在文件匹配中找不到导致无限循环错误的原因
- java - 如果结果始终相同,那么种子随机数生成器在 Java 中的实际用途是什么?
- ios - iOS Swift UIViewController 旋转
- java - 如何确定旋转字符串算法的时间和空间复杂度
- asp.net-core - 在 Web API ASP.NET Core 中检查 api 密钥的简单方法