前言
- 一直就听说学习深度学习无非就是看论文,然后复现,不断循环,这段时间也看了好几篇论文(虽然都是简单的),但是对于我一个人自学,复现成功,我感觉还是挺开心的
- 本人初学看论文的思路:聚焦网络结构与其实验的效果
- LeNet虽然简单,很老了,但是毕竟经典,对于初学的的我来说,我感觉还是很有必要学习的,可以积累CNN网络结构模型
- 注意:minist数据集可以直接下载,不用自己找,详情请看导入数据
- 本来今天打算更新C从C++的变化基础的,但是由于种种原因,就先更新这篇吧
论文(知网可查询):基于LeNet-5的手写数字识别的改进方法
网络结构(LeNet):
-
卷积层:两层
-
池化层:两层
-
卷积层参数:
- 第一层:维度变化(1->6),步伐:1,卷积核:5 * 5
- 第二层:维度变化(6->16),步伐:1,卷积核:5 * 5
-
池化层:
- 两层都是:卷积核:2 * 2,步伐:2
-
全连接层:3层
- 16 * 5 * 5 --> 120 --> 84 --> 10
-
网络结构图如下(论文截图):
结果
- 轮次10,有点大了,可以降低
- 相比第一课,发现在训练集的损失率、测试集的损失率、训练集的准确率都有提升,详情情况结果可视化
1、前期准备
1、设置GPU
import torch # 用于张量计算和自动求导
import torch.nn as nn # 构建神经网络和损失函数
import matplotlib.pyplot as plt # 绘图
import torchvision # 专门处理视觉的库
# 设置GPU
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(device)
print(torch.__version__)
print(torchvision.__version__)
cuda
2.4.0
0.19.0
2、导入数据
# 将所有的数据图片统一格式, 论文大小为:32 * 32
from torchvision import transforms, datasets
transforms = transforms.Compose([
transforms.Resize([32, 32]), # 统一图片大小
transforms.ToTensor(), # 统一规格
transforms.Normalize(mean=[0.1307], std=[0.3081]) # MNIST的均值和方差
])
# download设置为True,可以自动下载图片
train_ds = torchvision.datasets.MNIST('data', train=True, transform=transforms, download=False)
test_ds = torchvision.datasets.MNIST('data', train=True, transform=transforms, download=False)
batch_size = 32
train_dl = torch.utils.data.DataLoader(train_ds, batch_size=batch_size, shuffle=True)
test_dl = torch.utils.data.DataLoader(test_ds, batch_size=batch_size, shuffle=True)
# 取一个批次查看数据格式
# 数据的shape为:[batch_size, channel, heigh, weight]
# batch_size是自己设定的,channel,height,weight分别是图片的通道数,高度,宽度
imgs, labels = next(iter(train_dl))
imgs.shape
结果:
torch.Size([32, 1, 32, 32])
3、数据可视化
import numpy as np
# 指定图片的大小,图像的大小为20宽,5高
plt.figure(figsize=(20,5))
for i, imgs in enumerate(imgs[:20]):
# 维度缩减
npimg = np.squeeze(imgs.numpy())
# 将整个figure分层2行10列,绘制第i+1个子图
plt.subplot(2, 10, i + 1)
plt.imshow(npimg, cmap=plt.cm.binary)
plt.axis('off')
2、构建简单的CNN网络
import torch.nn.functional as F
num_classes = 10 # 图片的类别数
class Model(nn.Module):
def __init__(self):
super().__init__()
# 特征提取网络设置
self.conv1 = nn.Conv2d(1, 6, kernel_size=5)
self.pool1 = nn.MaxPool2d(2)
self.conv2 = nn.Conv2d(6, 16, kernel_size=5)
self.pool2 = nn.MaxPool2d(2)
# 分类网络设置
self.fc1 = nn.Linear(16 * 5 * 5, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, num_classes)
# 前向传播
def forward(self, x):
x = F.relu(self.conv1(x))
x = self.pool1(x)
x = F.relu(self.conv2(x))
x = self.pool2(x)
x = x.view(-1, 16 * 5 * 5)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
加载并且打印模型
from torchinfo import summary
# 将模型转移到GPU中
model = Model().to(device)
summary(model)
=================================================================
Layer (type:depth-idx) Param #
=================================================================
Model --
├─Conv2d: 1-1 156
├─MaxPool2d: 1-2 --
├─Conv2d: 1-3 2,416
├─MaxPool2d: 1-4 --
├─Linear: 1-5 48,120
├─Linear: 1-6 10,164
├─Linear: 1-7 850
=================================================================
Total params: 61,706
Trainable params: 61,706
Non-trainable params: 0
=================================================================
for X, y in train_dl:
print(X.shape) # 检查输入数据的形状
break # 只打印第一个批次的数据形状
torch.Size([32, 1, 32, 32])
3、模型训练
1、设置超参数
loss_fn = nn.CrossEntropyLoss() # 创建损失函数
learn_rate = 1e-2 # 学习率
opt = torch.optim.SGD(model.parameters(), lr = learn_rate)
2、编写训练函数
def train(dataloader, model, loss_fn, optimizer):
size = len(dataloader.dataset) # 训练集大小一共60000张图片
num_batchs = len(dataloader) # 批次数目,1875 (60000/32)
train_loss, train_acc = 0, 0 # 初始化训练损失和正确率
for X, y in dataloader: # 获取图片及其标签
X, y = X.to(device), y.to(device)
# 计算预测误差
pred = model(X) # 网络输出
loss = loss_fn(pred, y) # 计算网络输出和真实值的差距
# 反向传播
optimizer.zero_grad() # gred属性归零
loss.backward() # 反向传播
optimizer.step() # 每一步自动跟新
# 记录acc和loss
train_acc += (pred.argmax(1) == y).type(torch.float).sum().item()
train_loss += loss.item()
train_acc /= size
train_loss /= num_batchs
return train_acc, train_loss
3、编写测试函数
def test(dataloader, model, loss_fn):
size = len(dataloader.dataset) # 测试集的大小,一共10000张图片
num_batches = len(dataloader) # 批次数目,313(10000/32 = 321.5,向上取整)
test_loss, test_acc = 0, 0
# 当不进行训练时候,停止梯度更新,节省计算内存消耗
with torch.no_grad():
for imgs, target in dataloader:
imgs, target = imgs.to(device), target.to(device)
# 计算loss
target_pred = model(imgs)
loss = loss_fn(target_pred, target)
test_loss += loss.item()
test_acc += (target_pred.argmax(1) == target).type(torch.float).sum().item()
test_acc /= size
test_loss /= num_batches
return test_acc, test_loss
4、正式训练
epochs = 10
train_loss = []
train_acc = []
test_loss = []
test_acc = []
for epoch in range(epochs):
model.train()
epoch_train_acc, epoch_train_loss = train(train_dl, model, loss_fn, opt)
model.eval()
epoch_test_acc, epoch_test_loss = test(test_dl, model, loss_fn)
train_acc.append(epoch_train_acc)
train_loss.append(epoch_train_loss)
test_acc.append(epoch_test_acc)
test_loss.append(epoch_test_loss)
template = ('Eopch: {:2d}, Train_acc: {:.1f}%, Train_loss: {:.3f}, Test_acc: {:.1f}%, test_loss: {:.3f}')
print(template.format(epoch+1, epoch_train_acc * 100, epoch_train_loss, epoch_test_acc, epoch_test_loss))
print('Done')
Eopch: 1, Train_acc: 75.9%, Train_loss: 0.739, Test_acc: 1.0%, test_loss: 0.144
Eopch: 2, Train_acc: 96.4%, Train_loss: 0.117, Test_acc: 1.0%, test_loss: 0.079
Eopch: 3, Train_acc: 97.6%, Train_loss: 0.080, Test_acc: 1.0%, test_loss: 0.073
Eopch: 4, Train_acc: 98.0%, Train_loss: 0.063, Test_acc: 1.0%, test_loss: 0.056
Eopch: 5, Train_acc: 98.4%, Train_loss: 0.053, Test_acc: 1.0%, test_loss: 0.048
Eopch: 6, Train_acc: 98.5%, Train_loss: 0.047, Test_acc: 1.0%, test_loss: 0.041
Eopch: 7, Train_acc: 98.7%, Train_loss: 0.042, Test_acc: 1.0%, test_loss: 0.035
Eopch: 8, Train_acc: 98.8%, Train_loss: 0.037, Test_acc: 1.0%, test_loss: 0.029
Eopch: 9, Train_acc: 99.0%, Train_loss: 0.033, Test_acc: 1.0%, test_loss: 0.029
Eopch: 10, Train_acc: 99.0%, Train_loss: 0.030, Test_acc: 1.0%, test_loss: 0.023
Done
4、结果可视化
import matplotlib.pyplot as plt
import warnings
# 忽略警告
warnings.filterwarnings("ignore") #忽略警告信息
plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号
plt.rcParams['figure.dpi'] = 100 #分辨率
epochs_range = range(epochs)
plt.figure(figsize=(12, 3))
plt.subplot(1, 2, 1)
plt.plot(epochs_range, train_acc, label='Training Accuracy')
plt.plot(epochs_range, test_acc, label='Test Accuracy')
plt.legend(loc='lower right')
plt.title('Training and Validation Accuracy')
plt.subplot(1, 2, 2)
plt.plot(epochs_range, train_loss, label='Train Loss')
plt.plot(epochs_range, test_loss, label='Test Loss')
plt.legend(loc='upper right')
plt.title('Training and Validation Loss')
plt.show()
标签:acc,loss,plt,--,Train,train,LeNet,test,网络结构 From: https://blog.csdn.net/weixin_74085818/article/details/142236029