自学笔记
课程老师:刘二大人 河北工业大学教师 https://liuii.github.io
课程来源:https://www.bilibili.com/video/BV1Y7411d7Ys
十一、Implementation_of_Inception_Module
先看一下Inception_Module模块的图,课上老师按照下面的图进行的类的构建,然后封装,码代码时,是按照图中标注的分支1—4依次进行。其实构建四个分支的顺序可以随意调换,四个分支是平行的。
Inception_Module模块图
先构建Inception_Module类的代码,结合上图以及注释进行理解
#创建模型块,因为这个块在整个神经网络中经常使用,且不是基础的单层
#所以将其组合到一起,减少代码的重复性工作
class InceptionA(nn.Module):
def __init__(self,in_channels):
#使其能继承父类的属性,不明白的可以再看看python的类继承
super(InceptionA,self).__init__()
#结合老师课上给的模型图,这个网络分为了四个分支,下面逐一初始化
#分支1:1*1卷积层
self.branch1x1 = nn.Conv2d(in_channels, 16, kernel_size=1)
#分支2:1*1卷积层 --> 5*5的卷积层
self.branch5x5_1 = nn.Conv2d(in_channels,16, kernel_size=1)
#5*5的卷积层中,padding为2,保持了卷积后图片尺寸不变
self.branch5x5_2 = nn.Conv2d(16, 24, kernel_size=5, padding=2)
#分支3:1*1卷积层 --> 3*3卷积层 --> 3*3卷积层
self.branch3x3_1 = nn.Conv2d(in_channels, 16, kernel_size=1)
#两个3*3的卷积层,padding为1,同样保持了卷积后图片尺寸不变
self.branch3x3_2 = nn.Conv2d(16, 24, kernel_size=3, padding=1)
self.branch3x3_3 = nn.Conv2d(24, 24, kernel_size=3, padding=1)
#分支4:平均池化层 --> 1*1卷积,池化层在后面的forward中体现
self.branch_pool = nn.Conv2d(in_channels, 24, kernel_size=1)
def forward(self, x):
#分支1
branch1x1 = self.branch1x1(x)
#分支2
branch5x5 = self.branch5x5_1(x)
branch5x5 = self.branch5x5_2(branch5x5)
#分支3
branch3x3 = self.branch3x3_1(x)
branch3x3 = self.branch3x3_2(branch3x3)
branch3x3 = self.branch3x3_3(branch3x3)
#分支4,进行了池化层后,接了1*1卷积层
branch_pool = F.avg_pool2d(x, kernel_size=3, stride=1, padding=1)
branch_pool = self.branch_pool(branch_pool)
#将四层的输出结果按层进行合并。前面所有做的变换保证了每层的输出尺寸是一样大的,所以可以进行合并。
outputs = [branch1x1, branch5x5, branch3x3, branch_pool]
return torch.cat(outputs, dim=1)
接下来进行Net的构建
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
#初始化所需的卷积层
self.conv1 = nn.Conv2d(1, 10, kernel_size=5)
self.conv2 = nn.Conv2d(88, 20, kernel_size=5)
#初始化所需的InceptionA(nn.Module)
self.incep1 = InceptionA(in_channels=10)
self.incep2 = InceptionA(in_channels=20)
#初始化所需的最大池化层与线性层(fc即Fully_Connected,全连接)
self.mp = nn.MaxPool2d(2)
#这里老师教了一个偷懒的方法,线性层的输入大小(即下面的线性层输入1408)让系统自动计算
#方法:将下行代码注释掉,再在forward中输出对应位置的x.size(1)
self.fc = nn.Linear(1408, 10)
def forward(self, x):
#获取输入x的尺寸,这里即batch_size的大小
in_size = x.size(0)
#卷积-->池化-->relu
x = F.relu(self.mp(self.conv1(x)))
#经过第一个InceptionA模块
x = self.incep1(x)
#卷积-->池化-->relu
x = F.relu(self.mp(self.conv2(x)))
#经过第二个InceptionA模块
x = self.incep2(x)
#变形成 in_size 行,列自动变换
x = x.view(in_size, -1)
#如果想让程序自动计算出1408,将下方的代码(#print(x.size(1)))解除注释
#并注释它的下一行:x = self.fc(x),其它地方不变,整个代码跑一次,
#就能得到x.size(1),就是需要的全连接(线性层)的输入大小
#print(x.size(1))
x = self.fc(x)
return x
整个代码如下:
#仅模型部分做了改变,其它部分和前面的代码一致
#导入相应的包
import torch
from torchvision import transforms
from torchvision import datasets
from torch.utils.data import DataLoader
import torch.nn.functional as F
import torch.optim as optim
import torch.nn as nn
#小训练集大小
batch_size = 64
#数据集的处理
#图片变换:转换成Tensor,标准化
transform = transforms.Compose([transforms.ToTensor(),
transforms.Normalize((0.1307,),(0.3081,))])
#创建训练数据集
train_dataset = datasets.MNIST(root='../dataset/mnist/',
train=True, download=True,
transform=transform)
#导入训练数据集
train_loader = DataLoader(train_dataset,
shuffle=True,
batch_size=batch_size)
#创建测试数据集
test_dataset = datasets.MNIST(root='../dataset/mnist/',
train=False,
download=True,
transform=transform)
#导入测试数据集
test_loader = DataLoader(test_dataset,
shuffle=False,
batch_size=batch_size)
#创建模型块,因为这个块在整个神经网络中经常使用,且不是基础的单层
#所以将其组合到一起,减少代码的重复性工作
class InceptionA(nn.Module):
def __init__(self,in_channels):
#使其能继承父类的属性,不明白的可以再看看python的类继承
super(InceptionA,self).__init__()
#结合老师课上给的模型图,这个网络分为了四个分支,下面逐一初始化
#分支1:1*1卷积层
self.branch1x1 = nn.Conv2d(in_channels, 16, kernel_size=1)
#分支2:1*1卷积层 --> 5*5的卷积层
self.branch5x5_1 = nn.Conv2d(in_channels,16, kernel_size=1)
#5*5的卷积层中,padding为2,保持了卷积后图片尺寸不变
self.branch5x5_2 = nn.Conv2d(16, 24, kernel_size=5, padding=2)
#分支3:1*1卷积层 --> 3*3卷积层 --> 3*3卷积层
self.branch3x3_1 = nn.Conv2d(in_channels, 16, kernel_size=1)
#两个3*3的卷积层,padding为1,同样保持了卷积后图片尺寸不变
self.branch3x3_2 = nn.Conv2d(16, 24, kernel_size=3, padding=1)
self.branch3x3_3 = nn.Conv2d(24, 24, kernel_size=3, padding=1)
#分支4:平均池化层 --> 1*1卷积,池化层在后面的forward中体现
self.branch_pool = nn.Conv2d(in_channels, 24, kernel_size=1)
def forward(self, x):
#分支1
branch1x1 = self.branch1x1(x)
#分支2
branch5x5 = self.branch5x5_1(x)
branch5x5 = self.branch5x5_2(branch5x5)
#分支3
branch3x3 = self.branch3x3_1(x)
branch3x3 = self.branch3x3_2(branch3x3)
branch3x3 = self.branch3x3_3(branch3x3)
#分支4,进行了池化层后,接了1*1卷积层
branch_pool = F.avg_pool2d(x, kernel_size=3, stride=1, padding=1)
branch_pool = self.branch_pool(branch_pool)
#将四层的输出结果按层进行合并
outputs = [branch1x1, branch5x5, branch3x3, branch_pool]
return torch.cat(outputs, dim=1)
#设计总的模型,就可以直接调用上面的InceptionA(nn.Module)类
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
#初始化所需的卷积层
self.conv1 = nn.Conv2d(1, 10, kernel_size=5)
self.conv2 = nn.Conv2d(88, 20, kernel_size=5)
#初始化所需的InceptionA(nn.Module)
self.incep1 = InceptionA(in_channels=10)
self.incep2 = InceptionA(in_channels=20)
#初始化所需的最大池化层与线性层(fc即Fully_Connected,全连接)
self.mp = nn.MaxPool2d(2)
#这里老师教了一个偷懒的方法,线性层的输入大小(即下面的线性层输入1408)让系统自动计算
#方法:将下行代码注释掉,再在forward中输出对应位置的x.size(1)
self.fc = nn.Linear(1408, 10)
def forward(self, x):
#获取输入x的尺寸,这里即batch_size的大小
in_size = x.size(0)
#卷积-->池化-->relu
x = F.relu(self.mp(self.conv1(x)))
#经过第一个InceptionA模块
x = self.incep1(x)
#卷积-->池化-->relu
x = F.relu(self.mp(self.conv2(x)))
#经过第二个InceptionA模块
x = self.incep2(x)
#变形成 in_size 行,列自动变换
x = x.view(in_size, -1)
#如果想让程序自动计算出1408,将下方的代码(#print(x.size(1)))解除注释
#并注释它的下一行:x = self.fc(x),其它地方不变,整个代码跑一次,
#就能得到x.size(1),就是需要的全连接(线性层)的输入大小
#print(x.size(1))
x = self.fc(x)
return x
#实例化
model = Net()
#损失函数及反馈
criterion = torch.nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.5)
#训练
def train(epoch):
running_loss = 0.0
for batch_idx,data in enumerate(train_loader, 0):
inputs, target = data
optimizer.zero_grad()
# forward + backward + update
outputs = model(inputs)
loss = criterion(outputs, target)
loss.backward()
optimizer.step()
running_loss += loss.item()
if batch_idx % 300 == 299:
print('[%d, %5d] loss: %.3f' % (epoch + 1, batch_idx + 1, running_loss / 300))
running_loss = 0.0
def test():
correct = 0
total = 0
#不计算梯度,节省内存
with torch.no_grad():
for data in test_loader:
#导入测试数据
images, labels = data
#带入模型,得到输出
outputs = model(images)
#找到输出中概率最大的下标及值
_, predicted = torch.max(outputs.data, dim=1)
#计算所有的测试个数
total += labels.size(0)
#计算正确的个数
correct += (predicted == labels).sum().item()
#输出准确率
print('Accuracy on test set: %d %%' % (100 * correct / total))
if __name__ == '__main__':
#训练10次
for epoch in range(10):
#训练
train(epoch)
#测试
test()