天天看點

pytorch4——搭建VGG16

0.基礎知識

0.1. torch.nn.init.kaiming_normal_(m.weight, mode=‘fan_out’, nonlinearity=‘relu’)

  • 用正态分布來,填充輸入張量

0.2.torch.nn.init.constant_(m.weight, 1)

用常量1,來填充輸入張量

0.3.nn.BatchNorm2d

  • 2維資料歸一化層(把資料按比例縮放,使之落入一個小小的特定區間)

    使得資料在進行Relu之前不會因為資料過大而導緻網絡性能的不穩定

0.4.torch.nn.init.normal_(tensor, mean=0, std=1),

  • 用服從正态分布N(mean,std)的資料來填充張量tensor

1.VGG16結構圖

pytorch4——搭建VGG16
pytorch4——搭建VGG16

1.1.導包

import torch
import torch.nn as nn
from hub import *

__all__=[
    'VGG','vgg11','vgg11_bn','vgg13','vgg13_bn','vgg16','vgg16_bn',
    'vgg_19','vgg19_bn',
]


model_urls={
    'vgg11': 'https://download.pytorch.org/models/vgg11-bbd30ac9.pth',
    'vgg13': 'https://download.pytorch.org/models/vgg13-c768596a.pth',
    'vgg16': 'https://download.pytorch.org/models/vgg16-397923af.pth',
    'vgg19': 'https://download.pytorch.org/models/vgg19-dcbb9e9d.pth',
    'vgg11_bn': 'https://download.pytorch.org/models/vgg11_bn-6002323d.pth',
    'vgg13_bn': 'https://download.pytorch.org/models/vgg13_bn-abd245e5.pth',
    'vgg16_bn': 'https://download.pytorch.org/models/vgg16_bn-6c64b313.pth',
    'vgg19_bn': 'https://download.pytorch.org/models/vgg19_bn-c79401a0.pth',
}

           

1.2.定義VGG類方法

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():
            
             #如果m是2維卷積層
            if isinstance(m, nn.Conv2d):
                #按照《深入整流器:在ImageNet分類上超越人類水準的性能》中描述的方法,用正态分布填充輸入張量
                nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
                if m.bias is not None:
                    nn.init.constant_(m.bias, 0)
                    
             #如果m,是2維資料歸一化層(把資料按比例縮放,使之落入一個小小的特定區間)
            #使得資料在進行Relu之前不會因為資料過大而導緻網絡性能的不穩定        
            elif isinstance(m, nn.BatchNorm2d):
                nn.init.constant_(m.weight, 1)
                nn.init.constant_(m.bias, 0)
                
                #如果m是線性層 
            elif isinstance(m, nn.Linear):
                
                #torch.nn.init.normal_(tensor, mean=0, std=1),用服從正态分布N(mean,std)的資料來填充張量tensor
                nn.init.normal_(m.weight, 0, 0.01)
                nn.init.constant_(m.bias, 0)
           

1.3.神經網絡層合成函數

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'], 
}

#print(cfgs['A'])


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

           

1.4.調用合成vgg16

def vgg16(pretrained=False,progress=True,**kwargs):
    return _vgg('vgg16','D',False,pretrained,progress,**kwargs)
r"""VGG 16-layer model (configuration "D")
`"Very Deep Convolutional Networks For Large-Scale Image Recognition" <https://arxiv.org/pdf/1409.1556.pdf>`_
Args:
    pretrained (bool): If True, returns a model pre-trained on ImageNet
    progress (bool): If True, displays a progress bar of the download to stderr
"""
           

1.5.輸出vgg16網絡層參數

VGG_16_Net =vgg16()
print(VGG_16_Net)
           
pytorch4——搭建VGG16