深度学习_VGG网络

这篇博客详细介绍了如何使用PyTorch实现VGG模型,包括模型结构、权重初始化、特征抽取和全连接层的构建。通过make_features函数根据预定义的配置变量创建卷积层,然后在VGG类中定义前向传播过程和权重初始化方法。模型的构造考虑了卷积层、最大池化层以及全连接层的设置,适用于图像分类任务。
摘要由CSDN通过智能技术生成
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'
}


class VGG(nn.Module):
    def __init__(self, features, num_classes=1000, init_weights=False):
        super(VGG, self).__init__()
        self.features = features   #在全连接之前已经做了 卷积处理
        self.classifier = nn.Sequential(  # 是否需要展平?多维的输入一维化,常用在从卷积层到全连接层的过渡。Flatten不影响batch的大小
            nn.Linear(512*7*7, 4096),
            nn.ReLU(True),
            nn.Dropout(p=0.5),   #以一定概率随机失活 防止过拟合
            nn.Linear(4096, 4096),
            nn.ReLU(True),
            nn.Dropout(p=0.5),
            nn.Linear(4096, num_classes)
        )
        if init_weights:
            self._initialize_weights()   #初始化权重函数

    def forward(self, x):
        # N x 3 x 224 x 224
        x = self.features(x)
        # N x 512 x 7 x 7
        x = torch.flatten(x, start_dim=1)  #第0 个维度是batch,所以从第二个维度进行展平
        # N x 512*7*7
        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')
                nn.init.xavier_uniform_(m.weight)
                if m.bias is not None:
                    nn.init.constant_(m.bias, 0)
            elif isinstance(m, nn.Linear):
                nn.init.xavier_uniform_(m.weight)
                # nn.init.normal_(m.weight, 0, 0.01)
                nn.init.constant_(m.bias, 0)   #偏置置为0


def make_features(cfg: list):  #传入的就是配置变量
    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)
            layers += [conv2d, nn.ReLU(True)]
            in_channels = v
    return nn.Sequential(*layers)  #以非关键字形式传入参数

#M 最大池化
cfgs = {
    'vgg11': [64, 'M', 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],
    'vgg13': [64, 64, 'M', 128, 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],
    'vgg16': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512, 'M', 512, 512, 512, 'M'],
    'vgg19': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 256, 'M', 512, 512, 512, 512, 'M', 512, 512, 512, 512, 'M'],
}


def vgg(model_name="vgg16", **kwargs):   #实例化
    # assert model_name in cfgs, "Warning: model number {} not in cfgs dict!".format(model_name)
    # cfg = cfgs[model_name]
    #
    # model = VGG(make_features(cfg), **kwargs)
    try:
        cfg = cfgs[model_name]
    except:
        print("Warning: model number {} not in cfgs dict!".format(model_name))
        exit(-1)
        #features 是通过该函数的生成的   可变长度的字典变量
    model = VGG(make_features(cfg), **kwargs)

    return model



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值