1.
先導入使用的包,並聲明可用的網絡和預訓練好的模型
import torch.nn as nn import torch.utils.model_zoo as model_zoo #聲明可調用的網絡 __all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101', 'resnet152'] #用於加載的預訓練好的模型 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', }
2.
定義要使用到的1*1和3*3的卷積層
#卷積核為3*3,padding=1,stride=1(默認,根據實際傳入參數設定),dilation=1,groups=1,bias=False的二維卷積 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) #卷積核為1*1,padding=1,stride=1(默認,根據實際傳入參數設定),dilation=1,groups=1,bias=False的二維卷積 def conv1x1(in_planes, out_planes, stride=1): """1x1 convolution""" return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)
注意:這里bias設置為False,原因是:
下面使用了Batch Normalization,而其對隱藏層 有去均值的操作,所以這里的常數項
可以消去
因為Batch Normalization有一個操作,所以上面
的數值效果是能由
所替代的
因此我們在使用Batch Norm的時候,可以忽略各隱藏層的常數項 。
這樣在使用梯度下降算法時,只用對 ,
和
進行迭代更新
3.
實現兩層的殘差塊
比如:
#這個實現的是兩層的殘差塊,用於resnet18/34 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): identity = 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: #當連接的維度不同時,使用1*1的卷積核將低維轉成高維,然后才能進行相加 identity = self.downsample(x) out += identity #實現H(x)=F(x)+x或H(x)=F(x)+Wx out = self.relu(out) return out
4.實現3層的殘差塊
如圖:
#這個實現的是三層的殘差塊,用於resnet50/101/152 class Bottleneck(nn.Module): expansion = 4 def __init__(self, inplanes, planes, stride=1, downsample=None): super(Bottleneck, self).__init__() self.conv1 = conv1x1(inplanes, planes) self.bn1 = nn.BatchNorm2d(planes) self.conv2 = conv3x3(planes, planes, stride) self.bn2 = nn.BatchNorm2d(planes) self.conv3 = conv1x1(planes, planes * self.expansion) self.bn3 = nn.BatchNorm2d(planes * self.expansion) self.relu = nn.ReLU(inplace=True) self.downsample = downsample self.stride = stride def forward(self, x): identity = 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: identity = self.downsample(x) #當連接的維度不同時,使用1*1的卷積核將低維轉成高維,然后才能進行相加 out += identity #實現H(x)=F(x)+x或H(x)=F(x)+Wx out = self.relu(out) return out
5.整個網絡實現
class ResNet(nn.Module): #參數block指明殘差塊是兩層或三層,參數layers指明每個卷積層需要的殘差塊數量,num_classes指明分類數,zero_init_residual是否初始化為0 def __init__(self, block, layers, num_classes=1000, zero_init_residual=False): super(ResNet, self).__init__() self.inplanes = 64 #一開始先使用64*7*7的卷積核,stride=2, padding=3 self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False) #3通道的輸入RGB圖像數據變為64通道的數據 self.bn1 = nn.BatchNorm2d(64) self.relu = nn.ReLU(inplace=True) #以上是第一層卷積--1 self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) #然后進行最大值池化操作--2 self.layer1 = self._make_layer(block, 64, layers[0])#下面就是所有的卷積層的設置--3 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.AdaptiveAvgPool2d((1, 1)) #進行自適應平均池化--4 self.fc = nn.Linear(512 * block.expansion, num_classes)#全連接層--5 for m in self.modules(): if isinstance(m, nn.Conv2d): #kaiming高斯初始化,目的是使得Conv2d卷積層反向傳播的輸出的方差都為1 nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') elif isinstance(m, nn.BatchNorm2d): #初始化m.weight,即gamma的值為1;m.bias即beta的值為0 nn.init.constant_(m.weight, 1) nn.init.constant_(m.bias, 0) # 在每個殘差分支中初始化最后一個BN,即BatchNorm2d # 以便殘差分支以零開始,並且每個殘差塊的行為類似於一個恆等式。 # This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677 if zero_init_residual: for m in self.modules(): if isinstance(m, Bottleneck):#Bottleneck的最后一個BN是m.bn3 nn.init.constant_(m.bn3.weight, 0) elif isinstance(m, BasicBlock):#BasicBlock的最后一個BN是m.bn2 nn.init.constant_(m.bn2.weight, 0) #實現一層卷積,block參數指定是兩層殘差塊或三層殘差塊,planes參數為輸入的channel數,blocks說明該卷積有幾個殘差塊 def _make_layer(self, block, planes, blocks, stride=1): downsample = None #即如果該層的輸入的channel數inplanes和其輸出的channel數planes * block.expansion不同, #那要使用1*1的卷積核將輸入x低維轉成高維,然后才能進行相加 if stride != 1 or self.inplanes != planes * block.expansion: downsample = nn.Sequential( conv1x1(self.inplanes, planes * block.expansion, stride), nn.BatchNorm2d(planes * block.expansion), ) layers = [] #只有卷積和卷積直接的連接需要低維轉高維 layers.append(block(self.inplanes, planes, stride, downsample)) self.inplanes = planes * block.expansion for _ 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
6.不同層次網絡實現
#18層的resnet 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 #34層的resnet def resnet34(pretrained=False, **kwargs): """Constructs a ResNet-34 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(BasicBlock, [3, 4, 6, 3], **kwargs) if pretrained:#是否使用已經訓練好的預訓練模型,在此基礎上繼續訓練 model.load_state_dict(model_zoo.load_url(model_urls['resnet34'])) return model #50層的resnet 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 #101層的resnet def resnet101(pretrained=False, **kwargs): """Constructs a ResNet-101 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(Bottleneck, [3, 4, 23, 3], **kwargs) if pretrained:#是否使用已經訓練好的預訓練模型,在此基礎上繼續訓練 model.load_state_dict(model_zoo.load_url(model_urls['resnet101'])) return model #152層的resnet def resnet152(pretrained=False, **kwargs): """Constructs a ResNet-152 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(Bottleneck, [3, 8, 36, 3], **kwargs) if pretrained:#是否使用已經訓練好的預訓練模型,在此基礎上繼續訓練 model.load_state_dict(model_zoo.load_url(model_urls['resnet152'])) return model