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结构图

在这里插入图片描述
在这里插入图片描述

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)

在这里插入图片描述

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值