nn.Sequential(*layers)中*的用法及错误TypeError: list is not a Module subclass
这里主要涉及一些nn.Sequential()的用法,nn.Sequential()是一个顺序容器,将神经网络的相关操作进行封装。1. nn.Sequential()容器定义从nn.Sequential()的定义来看,输入要么是orderdict,要么是一系列的模型,遇到list,必须用*号进行转化,否则会报错 TypeError: list is not a Module subclass2.
·
这里主要涉及一些nn.Sequential()的用法,nn.Sequential()是一个顺序容器,将神经网络的相关操作进行封装。
1. nn.Sequential()容器定义
从nn.Sequential()的定义来看,输入要么是orderdict,要么是一系列的模型,遇到list,必须用*号进行转化,否则会报错 TypeError: list is not a Module subclass
2. nn.Sequential()的几种构造方法
- 简单的顺序构造
import torch.nn as nn
model = nn.Sequential(
nn.Conv2d(1,20,5),
nn.ReLU(),
nn.Conv2d(20,64,5),
nn.ReLU()
)
print(model)
print(model[2]) # 通过索引获取第几个层
'''运行结果为:
Sequential(
(0): Conv2d(1, 20, kernel_size=(5, 5), stride=(1, 1))
(1): ReLU()
(2): Conv2d(20, 64, kernel_size=(5, 5), stride=(1, 1))
(3): ReLU()
)
Conv2d(20, 64, kernel_size=(5, 5), stride=(1, 1))
'''
- 为各层添加名称
import torch.nn as nn
from collections import OrderedDict
model = nn.Sequential(OrderedDict([
('conv1', nn.Conv2d(1,20,5)),
('relu1', nn.ReLU()),
('conv2', nn.Conv2d(20,64,5)),
('relu2', nn.ReLU())
]))
print(model)
print(model[2]) # 通过索引获取第几个层
'''运行结果为:
Sequential(
(conv1): Conv2d(1, 20, kernel_size=(5, 5), stride=(1, 1))
(relu1): ReLU()
(conv2): Conv2d(20, 64, kernel_size=(5, 5), stride=(1, 1))
(relu2): ReLU()
)
Conv2d(20, 64, kernel_size=(5, 5), stride=(1, 1))
'''
- 利用Sequential的父类Module中的方法add_module()
import torch.nn as nn
from collections import OrderedDict
model = nn.Sequential()
model.add_module("conv1",nn.Conv2d(1,20,5))
model.add_module('relu1', nn.ReLU())
model.add_module('conv2', nn.Conv2d(20,64,5))
model.add_module('relu2', nn.ReLU())
print(model)
print(model[2]) # 通过索引获取第几个层
参考:添加链接描述
更多推荐
已为社区贡献1条内容
所有评论(0)