關於torchvision.models中VGG的筆記


VGG 主要有兩種結構,分別是 VGG16 和 VGG19,兩者並沒有本質上的區別,只是網絡深度不一樣。

對於給定的感受野,采用堆積的小卷積核是優於采用大的卷積核的,因為多層非線性層可以增加網絡深度來保證學習更復雜的模式,而且代價還比較小(參數更少)。

比如,三個步長為 $1$ 的 $3 \times 3$ 卷積核的疊加,即對應 $7 \times 7$ 的感受野(即三個 $3 \times 3$ 連續卷積相當於一個 $7 \times 7$ 卷積),如果我們假設卷積輸入輸出的 channel 數均為 $C$,那么三個 $3 \times 3$ 連續卷積的參數總量為 $3 \times (9 C^2)$(一個卷積核的大小 $3 \times 3 \times C$,一層有 $C$ 個卷積核,總共有三層),而如果直接使用 $7 \times 7$ 卷積核,其參數總量為 $49 C^2$。很明顯 $27C^2 < 49C^2$,即減少了參數。

VGG的網絡結構非常簡單,全部都是 $(3,3)$ 的卷積核,步長為 $1$,四周補 $1$ 圈 $0$(使得輸入輸出的 $(H,W)$ 不變):

 

我們可以參考 torchvision.models 中的源碼:

class VGG(nn.Module):

    def __init__(self, features, num_classes=1000, init_weights=True):
        super(VGG, self).__init__()
        self.features = features
        self.avgpool = nn.AdaptiveAvgPool2d((7, 7))
        self.classifier = nn.Sequential(
            nn.Linear(512 * 7 * 7, 4096),
            nn.ReLU(True),
            nn.Dropout(),
            nn.Linear(4096, 4096),
            nn.ReLU(True),
            nn.Dropout(),
            nn.Linear(4096, num_classes),
        )
        if init_weights:
            self._initialize_weights()

    def forward(self, x):
        x = self.features(x)
        x = self.avgpool(x)
        x = torch.flatten(x, 1)
        x = self.classifier(x)
        return x

    def _initialize_weights(self):
        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
                if m.bias is not None:
                    nn.init.constant_(m.bias, 0)
            elif isinstance(m, nn.BatchNorm2d):
                nn.init.constant_(m.weight, 1)
                nn.init.constant_(m.bias, 0)
            elif isinstance(m, nn.Linear):
                nn.init.normal_(m.weight, 0, 0.01)
                nn.init.constant_(m.bias, 0)


def make_layers(cfg, batch_norm=False):
    layers = []
    in_channels = 3
    for v in cfg:
        if v == 'M':
            layers += [nn.MaxPool2d(kernel_size=2, stride=2)]
        else:
            conv2d = nn.Conv2d(in_channels, v, kernel_size=3, padding=1)
            if batch_norm:
                layers += [conv2d, nn.BatchNorm2d(v), nn.ReLU(inplace=True)]
            else:
                layers += [conv2d, nn.ReLU(inplace=True)]
            in_channels = v
    return nn.Sequential(*layers)


cfgs = {
    'A': [64, 'M', 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],
    'B': [64, 64, 'M', 128, 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],
    'D': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512, 'M', 512, 512, 512, 'M'],
    'E': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 256, 'M', 512, 512, 512, 512, 'M', 512, 512, 512, 512, 'M'],
}


def _vgg(arch, cfg, batch_norm, pretrained, progress, **kwargs):
    if pretrained:
        kwargs['init_weights'] = False
    model = VGG(make_layers(cfgs[cfg], batch_norm=batch_norm), **kwargs)
    if pretrained:
        state_dict = load_state_dict_from_url(model_urls[arch],
                                              progress=progress)
        model.load_state_dict(state_dict)
    return model
View Code

cfgs 中的 "A,B,D,E" 就分別對應上表中的 A,B,D,E 四種網絡結構。

'M' 代表最大池化層, nn.MaxPool2d(kernel_size=2, stride=2) 

從代碼中可以看出,經過 self.features 的一大堆卷積層之后,先是經過一個 nn.AdaptiveAvgPool2d((7, 7)) 的自適應平均池化層(自動選擇參數使得輸出的 tensor 滿足 $(H = 7,W = 7)$),再通過一個 torch.flatten(x, 1) 推平成一個 $(batch\_size, n)$ 的 tensor,再連接后面的全連接層。

 

torchvision.models.vgg19_bn(pretrained=False, progress=True, **kwargs)

pretrained: 如果設置為 True,則返回在 ImageNet 預訓練過的模型。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM