深度学习——使用块的网络VGG(笔记)

使用块的网络VGG

1.AlexNet比LeNet更深更大来得到精度,能不能更深和更大?

选项:

①更多的全连接层(太贵)

②更多的卷积层

③将卷积层组合成块

2.VGG块的选择

①深或者宽?

5*5卷积

3*3卷积

选择深且窄的效果更好

②VGG块

3*3卷积(填充1):学习到更多的特征且参数更少(n层,m通道)

2*2最大池化层(步幅2)

3.VGG架构

①多个VGG块后连接成全连接层

②不同次数的重复块得到的不同架构VGG-16,VGG-19

4.VGG进度

①LeNet(1995)

2卷积+池化层

2全连接层

②AlexNet

更大更深

ReLu,DropOut数据增强

③VGG

更大更深的AlexNet(重复的VGG块)

【总结】

①VGG使用可重复使用的卷积块来构建深度卷积神经网络

②不同的卷积块个数和超参数可以得到不同复杂度的变种。

【代码实现】

import torch
from torch import nn
from d2l import torch as d2l

# 函数由三个参数 卷积层数量num_convs,输入通道in_channels,输出通道out_channels
# VGG块
def vgg_block(num_convs, in_channels, out_channels):
    layers = []
    for _ in range(num_convs):
        layers.append(nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1))
        layers.append(nn.ReLU())
        in_channels = out_channels  # 上一次的输出是下一次的输入
    layers.append(nn.MaxPool2d(kernel_size=2, stride=2))
    return nn.Sequential(*layers)


# VGG网络  超参数变量conv_arch:每个VGG块里卷积层个数和输出通道数
conv_arch = ((1, 64), (1, 128), (2, 256), (2, 512), (2, 512))


# 定义VGG-11
def vgg(conv_arch):
    conv_blks = []
    in_channels = 1
    # 卷积层部分
    for (num_convs, out_channels) in conv_arch:
        conv_blks.append(vgg_block(num_convs, in_channels, out_channels))
        in_channels = out_channels

    return nn.Sequential(
        *conv_blks, nn.Flatten(),
        # 全连接层部分
        nn.Linear(out_channels * 7 * 7, 4096), nn.ReLU(), nn.Dropout(0.5),
        nn.Linear(4096, 4096), nn.ReLU(), nn.Dropout(0.5),
        nn.Linear(4096, 10)
    )


net = vgg(conv_arch)

# 模型训练
ratio = 4
small_conv_arch = [(pair[0], pair[1] // ratio) for pair in conv_arch]
net = vgg(small_conv_arch)
lr, num_epochs, batch_size = 0.05, 10, 128
train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size, resize=224)

d2l.train_ch6(net, train_iter, test_iter, num_epochs, lr, d2l.try_gpu())
d2l.plt.show()

你可能感兴趣的:(深度学习,网络,人工智能)