课程目录(在更新,喜欢加个关注点个赞呗):
从零学习pytorch 第1课 搭建一个超简单的网络
从零学习pytorch 第1.5课 训练集、验证集和测试集的作用
从零学习pytorch 第2课 Dataset类
从零学习pytorch 第3课 DataLoader类运行过程
从零学习pytorch 第4课 初见transforms
从零学习pytorch 第5课 PyTorch模型搭建三要素
从零学习pytorch 第5.5课 Resnet34为例学习nn.Sequential和模型定义
从零学习PyTorch 第6课 权值初始化
从零学习PyTorch 第7课 模型Finetune与预训练模型
从零学习PyTorch 第8课 PyTorch优化器基类Optimier
代码摘取部分从github:
class ResidualBlock(nn.Module):
# 实现module:Residual Block
def __init__(self,inchannel,outchannel,stride=1,shortcut=None):
super(ResidualBlock.self).__init__()
self.left = nn.Sequential(
nn.Conv2d(inchannel,outchannel,3,stride,1,bias=False),
nn.BatchNorm2d(outchannel),
nn.ReLU(inplace=True),
nn.Conv2d(outchannel,outchannel,3,1,1,bias=False),
nn.BatchNorm2d(outchannel))
self.right = shortcut
def forward(self,x):
out=self.left(x)
residual = x if self.right is None else self.right(x)
out += residual
return F.relu(out)
class ResNet34(BasicModule):
# 实现主module:ResNet34
# ResNet34包含多个layer,每个layer又包含多个Residual block
def __init__(self,mum_classes=2):
super(ResNet34,self).__init__()
self.model_name = 'resnet34'
# 前几层是图像转换
self.pre = nn.Sequential(
nn.Conv2d(3,64,7,2,3,bias=False),
nn.BatchNorm2d(64),
nn.ReLU(inplace=True),
nn.MaxPool2d(3,2,1))
# 重复的layer,分别由3,4,6,3个residual block
self.layer1 = self._make_layer(64,128,3)
self.layer2 = self._make_layer(128,256,4,stride=2)
self.layer3 = self._make_layer(256,512,6,stride=2)
self.layer4 = self._make_layer(512,512,3,stride=2)
# 分类用的全连接
self.fc = nn.Linear(512,num_classes)
def _make_layer(self,inchannel,outchannel,block_num,stride=1):
#构建一个layer,包含多个residual block
shortcut = nn.Sequential(
nn.Conv2d(inchannel,outchannel,1,stride,bias=False),
nn.BatchNorm2d(outchannel))
layers = []
layers.append(ResidualBlock(inchannel,outchannel,stride,shortcut))
for i in range(1,block_num):
layers.append(ResidualBlock(outchannel,outchannel))
return nn.Sequential(*layers)
def forward(self,x):
x = self.pre(x)
x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
x = self.layer4(x)
x = F.avg_pool2d(x,7)
x = x.viwe(x,size(0),-1)
return self.fc(x)
大概一看,这是一个比较复杂的初始化,我们慢慢来看
从模型定义的三要素出发,
这里面的nn.Sequential到底是什么呢
torch.nn.Sequential就是一个Sequential的容器吧一系列的操作按照按照先后顺序包起来。
官方文档中写了两个使用例子:
# Example of using Sequential
model = nn.Sequential(
nn.Conv2d(1,20,5),
nn.ReLU(),
nn.Conv2d(20,64,5)
nn.ReLU())
model = nn.Sequential(
OrderedDict([
('conv1',nn.Conv2d(1,20,5)),
('relu1',nn.ReLU()),
('conv2',nn.Conv2d(20,64,5)),
('relu2',nn.ReLU())
]))
总之模型就是先继承,然后构建组建,然后组装
基本组件可以从torch.nn和torch.nn.functional中获取,同时为了方便使用,使用Sequential容器将一系列组件包起来,在forward()函数汇总组件组成模型。