1. 程式人生 > >pytorch 訓練資料以及測試 全部程式碼(6) 網路

pytorch 訓練資料以及測試 全部程式碼(6) 網路

ResNet101和ASPP

model = ResNet(nInputChannels, Bottleneck, [3, 4, 23, 3], os, pretrained=pretrained)
nInputChannels=3,os=16,其中Bottleneck是一個網路:class Bottleneck(nn.Module)

先看Bottleneck網路:

class Bottleneck(nn.Module):
    expansion = 4

    def __init__(self, inplanes, planes, stride=1, rate=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,
                               dilation=rate, padding=rate, 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
        self.rate = rate

    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

這是一個bottleneck,輸入是x,輸出是output+residual。這兩個tensor的shape是一樣的才能允許相加,如果輸入的shape不等於輸出的shape那麼一定存在downsample,進行shape的變化。所有的卷積都不新增bias,所有的輸入經過relu函式之後都改變了數值,使得和輸出是一樣的。

這裡的卷積大小計算重申一下: [n+2p-r(k-1)+1]/s +1

再看resnet101網路,裡面有6個函式,下面就一個一個講解

class ResNet(nn.Module):

    def __init__(self, nInputChannels, block, layers, os=16, pretrained=False):
        pass
    def _make_layer(self, block, planes, blocks, stride=1, rate=1):
        pass
    def _make_MG_unit(self, block, planes, blocks=[1,2,4], stride=1, rate=1):
        pass
    def forward(self, input):
        pass
    def _init_weight(self):
        pass
    def _load_pretrained_model(self):
        pass