>- **🍨 本文为[🔗365天深度学习训练营](https://mp.weixin.qq.com/s/rbOOmire8OocQ90QM78DRA) 中的学习记录博客**
>- **🍖 原作者:[K同学啊 | 接辅导、项目定制](https://mtyjkh.blog.csdn.net/)**
代码复现学习
1、准备GPU和导入数据
import torch
import torch.nn as nn
import matplotlib.pyplot as plt
import torchvision
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
device
train_ds = torchvision.datasets.CIFAR10('data',
train=True,
transform=torchvision.transforms.ToTensor(), # 将数据类型转化为Tensor
download=True)
test_ds = torchvision.datasets.CIFAR10('data',
train=False,
transform=torchvision.transforms.ToTensor(), # 将数据类型转化为Tensor
download=True)
转化为Tensor是为了便于Pytorch处理数据,该数据类型是Pytorch的核心,Tensor不仅用于数据存储,还可以构建计算图,并提供自动微分机制,这对于深度学习中的梯度计算至关重要。将数据转换为Tensor,意味着可以直接在这些数据上应用模型,并自动计算梯度,这是训练神经网络的基础。
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)
值得注意的是这里只打乱了训练集的顺序没有打乱测试集的,这是通常的选择,因为我们需要保持测试集的数据顺序来评估模型性能。(目前没有在此处用到抽样功能,看后续项目会不会用到,如没有则自行尝试)
imgs, labels = next(iter(train_dl))
imgs.shape
torch.Size([32, 3, 32, 32])
next
函数是Python的内置函数,用于获取迭代器的下一个元素。当你使用iter
函数将一个可迭代对象(比如列表、元组、字典、文件等)转换成迭代器后,可以通过next
函数来逐个访问这个迭代器中的元素。
import numpy as np
# 指定图片大小,图像大小为20宽、5高的绘图(单位为英寸inch)
plt.figure(figsize=(20, 5))
for i, imgs in enumerate(imgs[:20]):
# 维度缩减
npimg = imgs.numpy().transpose((1, 2, 0))
# 将整个figure分成2行10列,绘制第i+1个子图。
plt.subplot(2, 10, i+1)
plt.imshow(npimg, cmap=plt.cm.binary)
plt.axis('off')
subplot索引从1开始,所以这里要用i+1
img是一个四维张量,[batch_size, channels, height, width]。imgs[:20]切片后张量为
[N, channels, height, width],N为小于或等于20的数。
for i, img in enumerate(imgs[:20]):
:当我们在这个切片后的张量上进行迭代时,每次迭代提取出来的img
是一个三维张量([channels, height, width]
),代表单张图片的数据。
此处通过迭代处理隐晦将4维张量处理成了3维的,原理还是有点懵懵懂懂的,后续继续探索一下。
2、模型构建
import torch.nn.functional as F
num_classes = 10 # 图片的类别数
class Model(nn.Module):
def __init__(self):
super().__init__()
# 特征提取网络
self.conv1 = nn.Conv2d(3, 64, kernel_size=3) # 第一层卷积,卷积核大小为3*3
self.pool1 = nn.MaxPool2d(kernel_size=2) # 设置池化层,池化核大小为2*2
self.conv2 = nn.Conv2d(64, 64, kernel_size=3) # 第二层卷积,卷积核大小为3*3
self.pool2 = nn.MaxPool2d(kernel_size=2)
self.conv3 = nn.Conv2d(64, 128, kernel_size=3) # 第二层卷积,卷积核大小为3*3
self.pool3 = nn.MaxPool2d(kernel_size=2)
# 分类网络
self.fc1 = nn.Linear(512, 256)
self.fc2 = nn.Linear(256, num_classes)
# 前向传播
def forward(self, x):
x = self.pool1(F.relu(self.conv1(x)))
x = self.pool2(F.relu(self.conv2(x)))
x = self.pool3(F.relu(self.conv3(x)))
x = torch.flatten(x, start_dim=1)
x = F.relu(self.fc1(x))
x = self.fc2(x)
return x
各层的计算shape如下:
卷积层公式:(W - F + 2P) / S + 1,其中W是输入尺寸,F是卷积核尺寸,P是填充,S是步长
conv1层计算如下:(32 - 3 + 2*0) / 1 + 1 = 30,输出为[64, 30, 30]
池化层较简单,pool1为:30 / 2 = 15,输出为[64, 15, 15]
后续都用此规则计算,到最后输出为[128, 2, 2]
最后展平为128*2*2=512,最后再经过全连接后输出为10
from torchinfo import summary
# 将模型转移到GPU中(我们模型运行均在GPU中进行)
model = Model().to(device)
summary(model)
=================================================================
Layer (type:depth-idx) Param #
=================================================================
Model --
├─Conv2d: 1-1 1,792
├─MaxPool2d: 1-2 --
├─Conv2d: 1-3 36,928
├─MaxPool2d: 1-4 --
├─Conv2d: 1-5 73,856
├─MaxPool2d: 1-6 --
├─Linear: 1-7 131,328
├─Linear: 1-8 2,570
=================================================================
Total params: 246,474
Trainable params: 246,474
Non-trainable params: 0
=================================================================
3、模型训练
loss_fn = nn.CrossEntropyLoss() # 创建损失函数
learn_rate = 1e-2 # 学习率
opt = torch.optim.SGD(model.parameters(),lr=learn_rate)
此处选择的损失函数为交叉熵损失函数,这在分类问题中是常用的损失函数
# 训练循环
def train(dataloader, model, loss_fn, optimizer):
size = len(dataloader.dataset) # 训练集的大小,一共60000张图片
num_batches = 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) # 计算网络输出和真实值之间的差距,targets为真实值,计算二者差值即为损失
# 反向传播
optimizer.zero_grad() # grad属性归零
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_batches
return train_acc, train_loss
训练完后进行测试
def test (dataloader, model, loss_fn):
size = len(dataloader.dataset) # 测试集的大小,一共10000张图片
num_batches = len(dataloader) # 批次数目,313(10000/32=312.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
此处测试是直接使用的测试集数据,不过个人认为更合理的应该是一开始就划分为训练集、测试集、验证集3个数据集,用验证集调整模型,最后才用测试集来评估最终模型的结果
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 = ('Epoch:{: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*100, epoch_test_loss))
print('Done')
Epoch: 1, Train_acc:12.5%, Train_loss:2.287, Test_acc:21.1%,Test_loss:2.213
Epoch: 2, Train_acc:24.1%, Train_loss:2.049, Test_acc:25.9%,Test_loss:2.030
Epoch: 3, Train_acc:32.4%, Train_loss:1.837, Test_acc:31.4%,Test_loss:1.963
Epoch: 4, Train_acc:40.0%, Train_loss:1.647, Test_acc:39.9%,Test_loss:1.630
Epoch: 5, Train_acc:44.1%, Train_loss:1.537, Test_acc:46.0%,Test_loss:1.490
Epoch: 6, Train_acc:47.6%, Train_loss:1.445, Test_acc:43.9%,Test_loss:1.598
Epoch: 7, Train_acc:50.9%, Train_loss:1.363, Test_acc:50.1%,Test_loss:1.383
Epoch: 8, Train_acc:54.0%, Train_loss:1.290, Test_acc:53.8%,Test_loss:1.290
Epoch: 9, Train_acc:56.6%, Train_loss:1.222, Test_acc:55.9%,Test_loss:1.242
Epoch:10, Train_acc:59.1%, Train_loss:1.163, Test_acc:58.9%,Test_loss:1.164
Done
迭代10次后结果如下
3、结果可视化
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='Training Loss')
plt.plot(epochs_range, test_loss, label='Test Loss')
plt.legend(loc='upper right')
plt.title('Training and Validation Loss')
plt.show()
模型训练的准确率持续提高,而损失率持续下降,中间存在波动但在后续迭代中回归理想状况。若需要进一步提高模型性能可能需要后续进行更复杂的模型修正和设计。