在写 CV 实(lian)验(dan)代码的时,经常需要使用预训练好的 CNN 模型作为自己模型的骨架网络 (Backbone),其中 VGG-16 和 ResNet-50 是较为常用的两种 Backbone。
在使用 Backbone 时通常会丢弃最后一层全连接,对于具体的任务有时还会有其他的一些修改,因此只需要加载部分预训练模型。
这里介绍部分加载预训练 ResNet-50 的 Pytorch 实现方法。
定义需要使用的部分 ResNet-50 结构
def Conv1p(in_planes, places, stride=2):
return nn.Sequential(
nn.Conv2d(in_channels=in_planes, out_channels=places, kernel_size=7, stride=stride, padding=3, bias=False),
nn.BatchNorm2d(places),
nn.ReLU(inplace=True),
nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
)
def Conv1(in_planes, places, stride=2):
return nn.Sequential(
nn.Conv2d(in_channels=in_planes, out_channels=places, kernel_size=7, stride=stride, padding=3, bias=False),
nn.BatchNorm2d(places),
nn.ReLU(inplace=True),
# nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
)
class Bottleneck(nn.Module):
def __init__(self,in_places,places, stride=1, downsampling=False, expansion=4):
super(Bottleneck,self).__init__()
self.expansion = expansion
self.downsampling = downsampling
self.bottleneck = nn.Sequential(