一、容器containers(也都集成nn.module)
1.nn.Sequetial:按顺序包装多个网络层(使用容器的时候,容器里面的model属于容器,而这个容器属于本网络)注意哦,这个容器后面括号里都是参数所以要用逗号隔开
eg#我们习惯将卷积层池化层认为是特征提取部分,全连接层为分类,所以这么写
class L_net(nn.Module):
def __init__(self,classes):#参数classes为分类数
super(LeNetSequential,self).__init__()
self.features=nn.Sequential(#注意哦,这里开始用容器装层了
nn.Conv2d(3,6,5),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2,stride=2),
nn.Conv2d(6,16,5),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2,stride=2),
)
self.classifier=nn.Sequential(#这里是第二个容器,
nn.Linear(16*5*5,120),
nn.ReLU(),,
nn.Linear(120,84),
nn.ReLU(),
nn.Linear(84,classes),
)
而使用的前向算法也换了形式(毕竟没有self.各种层了)
def forward(self,x):
x=self.features(x)
x=x.view(x.size()[0],-1)
x=self.classifier(x)
return x
a=L_net(10)
print(a)
2.nn.ModuleList:像python中list一样包装多个网络层
主要方法:append()(在ModuleList中添加网络层······还不如那个直接写进度快呢┭┮﹏┭┮)
extend()(拼接两个ModuleList)
insert() (指定在ModuleList中位置插入网络层)
eg class ModuleList1(nn.Module):
def __init__(self):
super(ModuleList1,self).__init__()
self.linears=nn.ModuleList([nn.Linear(10,10) for i in range(20)])
#设置了一个Modulelist容器,名字为linears。并且里面有20个10-10的线性模型,(果然和列表一样呢)
def forward(self,x):
for i ,linear in enumerate(self.linears):
x=linear(x)
return x
a=ModuleList1()
print(a)
3.nn.ModuleDict:像python中dict一样包装多个网络层
主要方法:clear():清空ModuleDict
items():返回可迭代的键值对(key-value pairs)
keys():返回字典的键
values():返回字典的值
pop():返回一对键值并从字典中删除
class ModuleDict(nn.Module):
def __init__(self):
super(ModuleDict,self).__init__()
self.choices=nn.ModuleDict({#定义一个字典容器,forward中想用那个就根据key值找
"conv":nn.Conv2d(10,10,3),
"pool":nn.MaxPool2d(3),
})
self.activations=nn.ModuleDict({
'relu':nn.ReLU(),
'prelu':nn.PReLU()
})
def forward(self,x,choice,act):
#choice是调用choices层中key对应choice的模型,act同理
x=self.choices[choice](x)
x=self.activations[act](x)
return x
net =ModuleDict()
print(net)
总结:
nn.Sequential:顺序性
nn.ModuleLsit:迭代性(大量重复模型)
nn.ModuleDict:索引性(用于可选择的网络层)