本次小记,提供了一份基于pytorch的GoogleNet卷积神经网络模型的代码。除此之外,对代码中不容易理解的部分进行了讲解。
本代码的平台是PyCharm 2024.1.3,python版本3.11 numpy版本是1.26.4,pytorch版本2.0.0+cu118,d2l的版本是1.0.3
import numpy as np
import torch
from torch import nn
from torchvision.datasets import CIFAR10
import time
from torch.utils.data import DataLoader
from d2l import torch as d2l
import matplotlib.pyplot as plt
# 定义 inception块
class inception(nn.Module):
def __init__(self, channel_in, channel_out1, channel_out2, channel_out3, channel_out4):
super(inception, self).__init__()
channel_out2_1 = channel_out2[0]
channel_out2_2 = channel_out2[1]
channel_out3_1 = channel_out3[0]
channel_out3_2 = channel_out3[1]
# 第一条线路 1*1卷积
self.path1 = nn.Sequential(
nn.Conv2d(channel_in, channel_out1, kernel_size=1, stride=1),
nn.BatchNorm2d(channel_out1, eps=1e-3),
nn.ReLU(True)
)
# 第二条线路 1*1卷积-> 3*3卷积+填充1
self.path2 = nn.Sequential(
nn.Conv2d(channel_in, channel_out2_1, kernel_size=1, stride=1),
nn.BatchNorm2d(channel_out2_1, eps=1e-3),
nn.ReLU(True),
nn.Conv2d(channel_out2_1, channel_out2_2, kernel_size=3, stride=1, padding=1),
nn.BatchNorm2d(channel_out2_2, eps=1e-3),
nn.ReLU(True)
)
# 第三条线路 1*1卷积-> 5*5卷积+填充2
self.path3 = nn.Sequential(
nn.Conv2d(channel_in, channel_out3_1, kernel_size=1, stride=1),
nn.BatchNorm2d(channel_out3_1, eps=1e-3),
nn.ReLU(True),
nn.Conv2d(channel_out3_1, channel_out3_2, kernel_size=5, stride=1, padding=2),
nn.BatchNorm2d(channel_out3_2, eps=1e-3),
nn.ReLU(True)
)
# 第四条线路 3*3池化+填充1-> 3*3卷积
self.path4 = nn.Sequential(
nn.MaxPool2d(3, stride=1, padding=1),
nn.Conv2d(channel_in, channel_out4, kernel_size=1, stride=1),
nn.BatchNorm2d(channel_out4, eps=1e-3),
nn.ReLU(True)
)
def forward(self, x):
y1 = self.path1(x)
y2 = self.path2(x)
y3 = self.path3(x)
y4 = self.path4(x)
output = torch.cat((y1, y2, y3,