代码笔记21 Resnet backbone加载
仅作记录
Resnet骨架的搭建与参数加载
import torch.nn as nn
import torch.utils.model_zoo as model_zoo
# Imagenet resnet
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',
}
def conv3x3(in_planes, out_planes, stride=1):
return nn.Conv2d(in_channels=in_planes, out_channels=out_planes,
kernel_size=3, padding=1, stride=stride, bias=False)
class Resbackbone(nn.Module):
def __init__(self):
super(Resbackbone, self).__init__()
self.backbone = 'resnet50'
block = Bottleneck
layers = [3, 4, 6, 3]
# RGB encoder
self.conv1 = nn.Conv2d(in_channels=3, out_channels=64,
kernel_size=7, padding=3, stride=2, 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.inplanes = 64
self.layer1 = self._make_layer(block, 64, layers[0], stride=1)
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)
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(in_channels=self.inplanes, out_channels=planes * block.expansion,
kernel_size=1, stride=stride, bias=False),
nn.BatchNorm2d(planes * block.expansion))
layers = []
layers.append(block(inplanes=self.inplanes, planes=planes, stride=stride, downsample=downsample))
self.inplanes = planes * block.expansion
for i in range(1, blocks):
layers.append(block(inplanes=self.inplanes, planes=planes))
return nn.Sequential(*layers)
def _load_resnet_pretrained(self):
pretrain_dict = model_zoo.load_url(model_urls[self.backbone])
model_dict = {}
state_dict = self.state_dict()
for name, para in pretrain_dict.items():
if name in state_dict:
if name.startswith('conv1'):
model_dict[name] = para
elif name.startswith('bn1'):
model_dict[name] = para
elif name.startswith('layer'):
model_dict[name] = para
state_dict.update(model_dict)
self.load_state_dict(state_dict)
print('resnet {} paras loaded!'.format(self.backbone))
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None):
super(Bottleneck, self).__init__()
self.conv1 = nn.Conv2d(in_channels=inplanes, out_channels=planes,
kernel_size=1, stride=1,bias=False)
self.bn1 = nn.BatchNorm2d(planes)
self.conv2 = nn.Conv2d(in_channels=planes, out_channels=planes,
kernel_size=3, stride=stride, bias=False)
self.bn2 = nn.BatchNorm2d(planes)
self.conv3 = nn.Conv2d(in_channels=planes, out_channels=4 * planes,
kernel_size=1, stride=1, bias=False)
self.bn3 = nn.BatchNorm2d(4 * planes)
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
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
if __name__ == '__main__':
backbone = Resbackbone()
backbone._load_resnet_pretrained()
for name,para in backbone.state_dict(keep_vars=True).items():
print(name,para.shape,para.requires_grad)