【从零学习PyTorch】 如何残差网络resnet作为pre-model +代码讲解+残差网络resnet是个啥
2021-02-19 19:21
标签:struct sample dataset blcok 才有 oss 多个 image chm 看的多个Kaggle上 图片分类比赛 的代码,发现基本都会选择resnet网络作为前置网络进行训练,那么如何实现这个呢? 有一个非常好用的库,叫做torchvision。 这个model,就跟我之前讲的自己写一个class Net(nn.module),之后net = Net()的net是一样的!经典的网络一般是不需要重新写的,我们需要站在他们的肩膀上,简单修改就可以了。 代码中,pretrained=False是不加载参数,也就是说这个model中的参数是初始化的而不是训练好的。这里我们自然是需要之前训练的参数作为我们的初始参数。所以我们改成True即可,这里会自动下载一个参数文件。 这里可以看一下这个的源码,resnet18,resnet50,resnet101其实模型构建都一样,就是参数略有差别。如果pretrained是True的时候,会自动调用model.load_state_dict()这个函数,其实就是加载模型的函数。模型文件会从一个model_zoo.load_url下载参数。 我们可以看到,resnet18啊50啊101啊10086啊都是修改了ResNet的一个参数,那这个参数什么意思呢? 我们来分析一下这段代码: 在初始化的时候,有两个参数,block和layers。 _make_layer包含四个参数,第一个就是block类型,第二个是planes也就是输出的channel的数量,第三个blocks是每个blcoks中包含多少的子结构,其实就是layers所存储的数组,第四个是步长 接下来我们看一下两种block的源码 两种block:Bottleneck和Basicblock两个block都继承了torch.nn.Module。(这里总算是回到了torch模型三定义里面了,复杂的模型果然不一样) resnet18调用的参数是 核心就是: 然后这个blocks就是传入的参数layers[0], 我们再看layer2中,传入的参数是stride=2,这倒是downsample不再是None了,然后发现: 从layer2到layer4,没一层都会增加一本的channel,所以residual,也就是block会采用下采样。而对于每一层而言,channel都是相同的,因为在每一层的第一个block的第一个卷积层,就会把channel放大一倍,然后这一层的之后都是多少channel进去,多少channel出来。 现在我算是彻底明白34到底是怎么计算来的 模型一开始有一个卷积层,最后有一个全连接层,这是2层 然后【3,4,6,3】是Resnet34的参数,使用Basicblock,每个block2个卷积层 所以(3+4+6+3)*2+2 = 34 对于Resnet50,其实输入参数一样,还是【3,4,6,3】,只是Resnet50使用的Bottleneck,是三层卷积层,所以是(3+4+6+3)*3+2 = 50 【从零学习PyTorch】 如何残差网络resnet作为pre-model +代码讲解+残差网络resnet是个啥 标签:struct sample dataset blcok 才有 oss 多个 image chm 原文地址:https://www.cnblogs.com/PythonLearner/p/12925691.html
本文主要分为两个部分
第一部分:实现
这个是torchvision的官方文档
这个库有三个部分:
import torchvision
model = torchvision.models.resnet50(pretrained=False)
从零学习pytorch 第5课 PyTorch模型搭建三要素import torchvision
model = torchvision.models.resnet50(pretrained=True)
def resnet18(pretrained=False, **kwargs):
"""Constructs a ResNet-18 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = ResNet(BasicBlock, [2, 2, 2, 2], **kwargs)
if pretrained:
model.load_state_dict(model_zoo.load_url(model_urls[‘resnet18‘]))
return model
def resnet50(pretrained=False, **kwargs):
"""Constructs a ResNet-50 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = ResNet(Bottleneck, [3, 4, 6, 3], **kwargs)
if pretrained:
model.load_state_dict(model_zoo.load_url(model_urls[‘resnet50‘]))
return model
model_urls = {
‘resnet18‘: ‘https://download.pytorch.org/models/resnet18-5c106cde.pth‘,
‘resnet34‘: ‘https://download.pytorch.org/models/resnet34-333f7ec4.pth‘,
‘resnet50‘: ‘https://download.pytorch.org/models/resnet50-19c8e357.pth‘,
‘resnet101‘: ‘https://download.pytorch.org/models/resnet101-5d3b4d8f.pth‘,
‘resnet152‘: ‘https://download.pytorch.org/models/resnet152-b121ed2d.pth‘,
}
我们更进一步,看看ResNet的代码:class ResNet(nn.Module):
def __init__(self, block, layers, num_classes=1000):
self.inplanes = 64
super(ResNet, self).__init__()
self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,
bias=False)
self.bn1 = nn.BatchNorm2d(64)
self.relu = nn.ReLU(inplace=True)
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
self.layer1 = self._make_layer(block, 64, layers[0])
self.layer2 = self._make_layer(block, 128, layers[1], stride=2)
self.layer3 = self._make_layer(block, 256, layers[2], stride=2)
self.layer4 = self._make_layer(block, 512, layers[3], stride=2)
self.avgpool = nn.AvgPool2d(7, stride=1)
self.fc = nn.Linear(512 * block.expansion, num_classes)
for m in self.modules():
if isinstance(m, nn.Conv2d):
n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
m.weight.data.normal_(0, math.sqrt(2. / n)) # 卷积参数变量初始化
elif isinstance(m, nn.BatchNorm2d):
m.weight.data.fill_(1) # BN参数初始化
m.bias.data.zero_()
def _make_layer(self, block, planes, blocks, stride=1):
downsample = None
if stride != 1 or self.inplanes != planes * block.expansion:
downsample = nn.Sequential(
nn.Conv2d(self.inplanes, planes * block.expansion,
kernel_size=1, stride=stride, bias=False),
nn.BatchNorm2d(planes * block.expansion),
)
layers = []
layers.append(block(self.inplanes, planes, stride, downsample))
self.inplanes = planes * block.expansion
for i in range(1, blocks):
layers.append(block(self.inplanes, planes))
return nn.Sequential(*layers)
def forward(self, x):
x = self.conv1(x)
x = self.bn1(x)
x = self.relu(x)
x = self.maxpool(x)
x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
x = self.layer4(x)
x = self.avgpool(x)
x = x.view(x.size(0), -1)
x = self.fc(x)
return x
def __init__(self, block, layers, num_classes=1000):
def _make_layer(self, block, planes, blocks, stride=1):
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None):
super(Bottleneck, self).__init__()
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
self.bn1 = nn.BatchNorm2d(planes)
self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride,
padding=1, bias=False)
self.bn2 = nn.BatchNorm2d(planes)
self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False)
self.bn3 = nn.BatchNorm2d(planes * 4)
self.relu = nn.ReLU(inplace=True)
self.downsample = downsample
self.stride = stride
def forward(self, x):
residual = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
out = self.relu(out)
out = self.conv3(out)
out = self.bn3(out)
if self.downsample is not None:
residual = self.downsample(x)
out += residual
out = self.relu(out)
return out
简单看了一下,就是:
Conv2d->BatchNorm2d->ReLU->Conv2d->BatchNorm2d->ReLU->Conv2d->BatchNorm2d(->downsample)->ReLU这样的。之后画个图记忆深刻一点,虽然不知道记这些东西有没有用吧,跟同专业的人装装逼应该没问题。def conv3x3(in_planes, out_planes, stride=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=1, bias=False)
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, downsample=None):
super(BasicBlock, self).__init__()
self.conv1 = conv3x3(inplanes, planes, stride)
self.bn1 = nn.BatchNorm2d(planes)
self.relu = nn.ReLU(inplace=True)
self.conv2 = conv3x3(planes, planes)
self.bn2 = nn.BatchNorm2d(planes)
self.downsample = downsample
self.stride = stride
def forward(self, x):
residual = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
if self.downsample is not None:
residual = self.downsample(x)
out += residual
out = self.relu(out)
return out
Basicblock少了一个卷积层,相比Bottleneck。resnet18模型流程
model = ResNet(BasicBlock,[2,2,2,2],**kwargs)
在代码中,最难理解的就是self.layer1 = self.._make_layer(block,64,layers[0])
因为是resnet18,所以block是Basicblock,layer[0]=2layers.append(block(self.inplanes,planes, stride, downsample))
sefl.inplanes = 64,planes = 64,strid=1
然后就按照上面那个流程图,构造出一个两层卷积的Basicblock。for i in range(1, blocks):
layers.append(block(self.inplanes, planes))
总之,layers中有layer[0]个blocks,(layer[0]不能是0.)
每一层中,如果stride=1,就没有downsamle,如果stride=2,就有downsample,而且是这个layers中第一个block才有downsample,之后的block依然没有downsample=总结
上图是一个Resnet34的结构图
文章标题:【从零学习PyTorch】 如何残差网络resnet作为pre-model +代码讲解+残差网络resnet是个啥
文章链接:http://soscw.com/index.php/essay/57668.html