动手学深度学习(Pytorch版)代码实践 -卷积神经网络-27含并行连结的网络GoogLeNet

27含并行连结的网络GoogLeNet


python 复制代码
import torch
from torch import nn
from torch.nn import functional as F
import liliPytorch as lp
import matplotlib.pyplot as plt

class Inception(nn.Module):
    # c1--c4是每条路径的输出通道数
    def __init__(self, in_channels, c1, c2, c3, c4, **kwargs):
        super().__init__()
        # super(Inception, self).__init__(**kwargs)
        # 线路1,单1x1卷积层
        self.p1_1 = nn.Conv2d(in_channels, c1, kernel_size=1)
        # 线路2,1x1卷积层后接3x3卷积层
        self.p2_1 = nn.Conv2d(in_channels, c2[0], kernel_size=1)
        self.p2_2 = nn.Conv2d(c2[0], c2[1], kernel_size=3, padding=1)
        # 线路3,1x1卷积层后接5x5卷积层
        self.p3_1 = nn.Conv2d(in_channels, c3[0], kernel_size=1)
        self.p3_2 = nn.Conv2d(c3[0], c3[1], kernel_size=5, padding=2)
        # 线路4,3x3最大汇聚层后接1x1卷积层
        self.p4_1 = nn.MaxPool2d(kernel_size=3, stride=1, padding=1)
        self.p4_2 = nn.Conv2d(in_channels, c4, kernel_size=1)

    def forward(self, x):
        # 经过每条路径,并应用 ReLU 激活函数
        p1 = F.relu(self.p1_1(x))
        p2 = F.relu(self.p2_2(F.relu(self.p2_1(x))))
        p3 = F.relu(self.p3_2(F.relu(self.p3_1(x))))
        p4 = F.relu(self.p4_2(self.p4_1(x)))
        # 在通道维度上连结输出
        return torch.cat((p1, p2, p3, p4), dim=1)

# 定义模型的各个模块
b1 = nn.Sequential(
    nn.Conv2d(1, 64, kernel_size=7, stride=2, padding=3), # 第一个卷积层
    nn.ReLU(),                                            # 激活函数
    nn.MaxPool2d(kernel_size=3, stride=2, padding=1)      # 最大汇聚层
)

b2 = nn.Sequential(
    nn.Conv2d(64, 64, kernel_size=1),                     # 1x1卷积层
    nn.ReLU(),                                            # 激活函数
    nn.Conv2d(64, 192, kernel_size=3, padding=1),         # 3x3卷积层
    nn.ReLU(),                                            # 激活函数
    nn.MaxPool2d(kernel_size=3, stride=2, padding=1)      # 最大汇聚层
)

b3 = nn.Sequential(
    Inception(192, 64, (96, 128), (16, 32), 32),          # 第一个Inception块
    Inception(256, 128, (128, 192), (32, 96), 64),        # 第二个Inception块
    nn.MaxPool2d(kernel_size=3, stride=2, padding=1)      # 最大汇聚层
)

b4 = nn.Sequential(
    Inception(480, 192, (96, 208), (16, 48), 64),         # 第一个Inception块
    Inception(512, 160, (112, 224), (24, 64), 64),        # 第二个Inception块
    Inception(512, 128, (128, 256), (24, 64), 64),        # 第三个Inception块
    Inception(512, 112, (144, 288), (32, 64), 64),        # 第四个Inception块
    Inception(528, 256, (160, 320), (32, 128), 128),      # 第五个Inception块
    nn.MaxPool2d(kernel_size=3, stride=2, padding=1)      # 最大汇聚层
)

b5 = nn.Sequential(
    Inception(832, 256, (160, 320), (32, 128), 128),      # 第一个Inception块
    Inception(832, 384, (192, 384), (48, 128), 128),      # 第二个Inception块
    nn.AdaptiveAvgPool2d((1, 1)),                         # 自适应平均汇聚层
    nn.Flatten()                                          # 展平层
)

# 将所有模块串联成一个完整的模型
net = nn.Sequential(
    b1,      # 第一模块
    b2,      # 第二模块
    b3,      # 第三模块
    b4,      # 第四模块
    b5,      # 第五模块
    nn.Linear(1024, 10)  # 最后一层全连接层,输出10个类别
)

# 创建一个随机输入张量,并通过每一层,打印输出形状
X = torch.rand(size=(1, 1, 96, 96))
for layer in net:
    X = layer(X)
    print(layer.__class__.__name__, 'output shape:\t', X.shape)

# 训练参数
lr, num_epochs, batch_size = 0.1, 10, 128
# 加载数据集
train_iter, test_iter = lp.loda_data_fashion_mnist(batch_size, resize=96)
# 训练模型
lp.train_ch6(net, train_iter, test_iter, num_epochs, lr, lp.try_gpu())
# 显示训练过程中的图表
plt.show()

# 训练结果:
# 损失 0.254, 训练准确率 0.904, 测试准确率 0.866
# 1534.2 examples/sec on cuda:0

# loss 0.246, train acc 0.906, test acc 0.891
# 1492.9 examples/sec on cuda:0

运行效果:

相关推荐
weiwei2284412 小时前
神经网络模型导出及开放标准格式ONNX
pytorch·onnx
饼干哥哥20 小时前
开源Skills|搭建亚马逊动态关键词库系统,每天抓SSS级机会词
人工智能·深度学习·数据分析
武子康3 天前
调查研究-191 SenseVoice 不只是 ASR:把语音从“转文字“升级成“理解状态“
人工智能·深度学习·openai
武子康4 天前
调查研究-189 Kronos 调研:金融 K 线基础模型,是真突破,还是量化圈的新玩具?
人工智能·深度学习·openai
程序猿追10 天前
那个右下角的小数字怎么“卡”住我打字——我用 HarmonyOS 自己写了一个字数限制输入框
pytorch·华为·harmonyos
xiao5kou4chang6kai410 天前
MATLAB机器学习、深度学习--从数据预处理到模型训练
深度学习·机器学习·matlab·数据预处理
renhongxia110 天前
世界模型作为AGI落地底层底座的作用
人工智能·深度学习·生成对抗网络·自然语言处理·知识图谱·agi
计算机科研狗@OUC10 天前
(cvpr26) AIMDepth: Asymmetric Image-Event Mamba for Monocular Depth Estimation
人工智能·深度学习·计算机视觉
闵孚龙10 天前
《PyTorch 深度修炼》Dataset 和 DataLoader:数据如何喂给模型
人工智能·pytorch·python
β添砖java10 天前
深度学习(22)网络中的网络NiN
人工智能·深度学习