class LeNet(nn.model):
def __init__(self,classes):
super(LeNet,self).__init__()
self.conv1=nn.Conv2d(3,6,5)
self.conv2=nn.Conv2d(6,16,5)
self.fc1=nn.Linear(16*5*5,120)
self.fc2=nn.Linear(120,84)
self.fc3=nn.Linear(84,classes)
def forward(self,x):
out=F.relu(self.conv1(x))
out=F.max_pool2d(out,2)
out=F.relu(self.conv2(out))
out=F.max_pool2d(out,2)
out=out.view(out.size(0),-1)
out=F.relu(self.fc1(out))
out=F.relu(self.fc2(out))
out=self.fc3(out)
return out
torch.nn里面有很多子模块:
nn.Parameter :张量子类,表示可学习参数,如weight,bias
nn.Module :所有网络层基类,管理网络属性
nn.function:函数具体实现,如卷积,池化,激活函数等
nn.int:参数初始化方法
parameters:管理nn.Parameter类
modules:存储管理nn.Module类
buffers:存储管理缓冲属性,如BN层中的running_mean
***_hooks:存储管理钩子函数
nn.Sequetial :按顺序包装多个网络
nn.ModuleList:像python的list一样包装多个网络层
nn.ModuleDict:想pythonde字典一样
使用sequential包装lenet
class LeNetSequential(nn.Module):
def __init__(self,class):
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)
)
def forward(self,x):
x=self.features(x)
x=x.view(x.size()[0],-1)
x=self.classifier(x)
return x
nn.Sequential是nn.module的容器,用于按顺序包装一组网络层
顺序性:各网络层之间按照顺序构建
自带forward():自带的forward里,通过for循环依次执行前向传播运算
主要方法:append():在ModuleList后面添加网络层
extend():拼接两个ModuleList
insert():在指定Module List中位置插入网络层
构建20个全连接层:
class ModuleList(nn.Module):
def __init__(self):
super(ModuleList,self).__init__()
self.linears=nn.ModuleList([nn.Linear(10,10) for i in range(20)])
def forward(self,x):
for i ,linear in enumerate(self.linears):
x=linear(x)
return x
主要的方法:
clear():清空ModuleDict
items():返回可迭代的键值对
keys():返回字典的键
values():返回字典的值
pop()返回一对键值,并从字典中删除
class ModuleDict(nn.Mudle):
def __init__(self):
super(ModuleDict,self).__init__()
self.choice=nn.ModuleDict({
'conv':nn.Conv2d(10,10,3),
'pool':MaxPool2d(3)
})
self.activations=nn.MmoduleDict({
'relu':nn.ReLU(),
'prelu':nn.PReLU()
})
def forward(self,x,choice,act):
x=self.chioce[choice](x)
x=self.activations[act](x)
return x