- 🍨 本文为🔗365天深度学习训练营 中的学习记录博客
- 🍖 原作者:K同学啊
前言
- 前几天一直很忙,一直在数学建模中,没有来得及更新,接下来将恢复正常
- 这一次的案例很有意思:在学习动态调整学习率的时候,本来想着记录训练过程中的训练集中损失率最低的学习率,记录下来了发现是:0.001(是初始值),然后用0.001去训练,发现出现了过拟合,哈哈哈哈哈。
目标
- 学习动态调整学习率
- 使测试集的准确率达到84%
结果
- 达到了84%
1、数据预处理
数据文件夹说明(data): 分为训练集和测试集,每个文件夹里面都含有不同品牌的运动鞋分类,分类单独一个文件
1、导入库
import torch
import torch.nn as nn
import torchvision
import numpy as np
import os, PIL, pathlib
device = ('cuda' if torch.cuda.is_available() else 'cup')
device
输出:
'cuda'
2、数据导入与展示
# 查看数据数据文件夹内容
data_dir = './data/train/'
data_dir = pathlib.Path(data_dir)
# 获取该文件夹内内容
data_path = data_dir.glob('*') # 获取绝对路径
classNames = [str(path).split('\\')[2] for path in data_path]
classNames
输出:
['adidas', 'nike']
# 数据展示
import matplotlib.pyplot as plt
from PIL import Image
# 获取文件名称
data_path_name = './data/train/nike/'
data_path_list = [f for f in os.listdir(data_path_name) if f.endswith(('jpg', 'png'))]
# 创建画板
fig, axes = plt.subplots(2, 8, figsize=(16, 6)) # fig:画板,ases子图
# 展示
for ax, img_file in zip(axes.flat, data_path_list):
path_name = os.path.join(data_path_name, img_file)
img = Image.open(path_name)
ax.imshow(img)
ax.axis('off')
plt.show()
3、数据处理
# 将所有的数据图片统一格式
from torchvision import transforms, datasets
train_path = './data/train/'
test_path = './data/test/'
# 定义训练集、测试集图片标准
train_transforms = transforms.Compose([
transforms.Resize([224, 224]), # 统一图片大小
transforms.ToTensor(), # 统一规格
transforms.Normalize( # 数据标准化
mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225]
)
])
test_transforms = transforms.Compose([
transforms.Resize([224, 224]),
transforms.ToTensor(),
transforms.Normalize(
mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225]
)
])
# 数据处理
train_data = datasets.ImageFolder(root=train_path, transform=train_transforms)
test_data = datasets.ImageFolder(root=test_path, transform=test_transforms)
4、加载与划分动态数据
batch_size = 32
train_dl = torch.utils.data.DataLoader(train_data,
batch_size=batch_size,
shuffle=True,
num_workers=1)
test_dl = torch.utils.data.DataLoader(test_data,
batch_size=batch_size,
shuffle=True,
num_workers=1)
# 展示图像参数
for param, data in train_dl:
print("image(N, C, H, W): ", param.shape)
print("data: ", data)
break
image(N, C, H, W): torch.Size([32, 3, 224, 224])
data: tensor([0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0,
0, 1, 1, 0, 1, 0, 0, 0])
2、构建CNN神经网络
卷积:--> 12*220*220 --> 12*216*216
池化:--> 12*108*108
卷积: --> 24*104*104 --> 24*100*100
池化:--> 24*50*50 --> 25*50*2
import torch.nn.functional as F
class Net_work(nn.Module):
def __init__(self):
super(Net_work, self).__init__() # 父类信息构建
self.conv1 = nn.Sequential(
nn.Conv2d(in_channels=3, out_channels=12, kernel_size=5, padding=0),
nn.BatchNorm2d(12), # 第一个参数:特征数量
nn.ReLU()
)
self.conv2 = nn.Sequential(
nn.Conv2d(in_channels=12, out_channels=12, kernel_size=5, padding=0),
nn.BatchNorm2d(12),
nn.ReLU()
)
self.pool1 = nn.Sequential(
nn.MaxPool2d(2, 2)
)
self.conv3 = nn.Sequential(
nn.Conv2d(in_channels=12, out_channels=24, kernel_size=5, padding=0),
nn.BatchNorm2d(24),
nn.ReLU()
)
self.conv4 = nn.Sequential(
nn.Conv2d(in_channels=24, out_channels=24, kernel_size=5, padding=0),
nn.BatchNorm2d(24),
nn.ReLU()
)
self.pool2 = nn.Sequential(
nn.MaxPool2d(2, 2)
)
self.dropout = nn.Sequential(
nn.Dropout(0.2)
)
self.fc = nn.Sequential(
nn.Linear(24*50*50, len(classNames))
)
def forward(self, x):
batch_size = x.size(0) # 每一次训练的批次大小,N,C,H,W
x = self.conv1(x) # 卷积-->NB-->激活
x = self.conv2(x) # 卷积-->NB-->激活
x = self.pool1(x) # 池化
x = self.conv3(x) # 卷积-->NB-->激活
x = self.conv4(x) # 卷积-->NB-->激活
x = self.pool2(x) # 池化
x = x.view(batch_size, -1) # -1,代表自动展示,将24*50*50展开
x = self.fc(x)
return x
# 将网络结构导入GPU
model = Net_work().to(device)
model
输出:
Net_work(
(conv1): Sequential(
(0): Conv2d(3, 12, kernel_size=(5, 5), stride=(1, 1))
(1): BatchNorm2d(12, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(2): ReLU()
)
(conv2): Sequential(
(0): Conv2d(12, 12, kernel_size=(5, 5), stride=(1, 1))
(1): BatchNorm2d(12, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(2): ReLU()
)
(pool1): Sequential(
(0): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
)
(conv3): Sequential(
(0): Conv2d(12, 24, kernel_size=(5, 5), stride=(1, 1))
(1): BatchNorm2d(24, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(2): ReLU()
)
(conv4): Sequential(
(0): Conv2d(24, 24, kernel_size=(5, 5), stride=(1, 1))
(1): BatchNorm2d(24, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(2): ReLU()
)
(pool2): Sequential(
(0): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
)
(dropout): Sequential(
(0): Dropout(p=0.2, inplace=False)
)
(fc): Sequential(
(0): Linear(in_features=60000, out_features=2, bias=True)
)
)
3、模型的训练准备
1、设置超参数
# 创建损失函数
loss_fn = nn.CrossEntropyLoss()
# 初始化学习率
lr = 1e-4
# 创建梯度下降法
optimizer = torch.optim.SGD(model.parameters(), lr=lr)
2、创建训练函数
def train(dataloader, model, loss_fn, optimizer):
# 总大小
size = len(dataloader.dataset)
# 批次大小
batch_size = len(dataloader)
# 准确率和损失
trian_acc, train_loss = 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() # 梯度上更新
# 方向传播
loss.backward()
# 梯度更新
optimizer.step()
# 记录损失和准确率
train_loss += loss.item()
trian_acc += (pred.argmax(1) == y).type(torch.float64).sum().item()
# 计算损失和准确率
trian_acc /= size
train_loss /= batch_size
return trian_acc, train_loss
3、创建测试函数
def test(dataloader, model, loss_fn):
size = len(dataloader.dataset)
batch_size = len(dataloader)
test_acc, test_loss = 0, 0
with torch.no_grad():
for X, y in dataloader:
X, y = X.to(device), y.to(device)
pred = model(X)
loss = loss_fn(pred, y)
test_loss += loss.item()
test_acc += (pred.argmax(1) == y).type(torch.float64).sum().item()
test_acc /= size
test_loss /= batch_size
return test_acc, test_loss
4、动态调整学习率
def adjust_learning_rate(optimizer, epoch, start_lr):
# 调整规则:每 2 次都衰减到原来的 0.92
lr = start_lr * (0.95 ** (epoch // 2))
for param_group in optimizer.param_groups:
param_group['lr'] = lr
4、正式训练
train_acc = []
train_loss = []
test_acc = []
test_loss = []
# 定义训练次数
epoches = 40
for epoch in range(epoches):
# 动态调整学习率
adjust_learning_rate(optimizer, epoches, lr)
# 训练
model.train()
epoch_trian_acc, epoch_train_loss = train(train_dl, model, loss_fn, optimizer)
# 测试
model.eval()
epoch_test_acc, epoch_test_loss = test(test_dl, model, loss_fn)
# 记录
train_acc.append(epoch_trian_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_trian_acc*100, epoch_train_loss, epoch_test_acc*100, epoch_test_loss))
Epoch: 1, Train_acc:52.0%, Train_loss:0.736, Test_acc:52.6%, Test_loss:0.695
Epoch: 2, Train_acc:59.2%, Train_loss:0.685, Test_acc:61.8%, Test_loss:0.672
Epoch: 3, Train_acc:65.1%, Train_loss:0.644, Test_acc:72.4%, Test_loss:0.593
Epoch: 4, Train_acc:66.7%, Train_loss:0.616, Test_acc:65.8%, Test_loss:0.571
Epoch: 5, Train_acc:69.3%, Train_loss:0.602, Test_acc:68.4%, Test_loss:0.555
Epoch: 6, Train_acc:69.7%, Train_loss:0.580, Test_acc:69.7%, Test_loss:0.525
Epoch: 7, Train_acc:73.3%, Train_loss:0.559, Test_acc:77.6%, Test_loss:0.530
Epoch: 8, Train_acc:75.9%, Train_loss:0.544, Test_acc:71.1%, Test_loss:0.513
Epoch: 9, Train_acc:75.7%, Train_loss:0.531, Test_acc:75.0%, Test_loss:0.495
Epoch:10, Train_acc:78.7%, Train_loss:0.517, Test_acc:81.6%, Test_loss:0.508
Epoch:11, Train_acc:78.9%, Train_loss:0.499, Test_acc:78.9%, Test_loss:0.503
Epoch:12, Train_acc:81.3%, Train_loss:0.486, Test_acc:77.6%, Test_loss:0.482
Epoch:13, Train_acc:80.5%, Train_loss:0.480, Test_acc:76.3%, Test_loss:0.476
Epoch:14, Train_acc:83.3%, Train_loss:0.468, Test_acc:81.6%, Test_loss:0.497
Epoch:15, Train_acc:81.7%, Train_loss:0.459, Test_acc:81.6%, Test_loss:0.518
Epoch:16, Train_acc:83.9%, Train_loss:0.461, Test_acc:77.6%, Test_loss:0.465
Epoch:17, Train_acc:85.9%, Train_loss:0.443, Test_acc:78.9%, Test_loss:0.497
Epoch:18, Train_acc:84.9%, Train_loss:0.430, Test_acc:78.9%, Test_loss:0.485
Epoch:19, Train_acc:85.9%, Train_loss:0.428, Test_acc:78.9%, Test_loss:0.504
Epoch:20, Train_acc:86.5%, Train_loss:0.418, Test_acc:82.9%, Test_loss:0.446
Epoch:21, Train_acc:87.5%, Train_loss:0.406, Test_acc:82.9%, Test_loss:0.464
Epoch:22, Train_acc:87.5%, Train_loss:0.403, Test_acc:78.9%, Test_loss:0.486
Epoch:23, Train_acc:87.6%, Train_loss:0.393, Test_acc:81.6%, Test_loss:0.443
Epoch:24, Train_acc:88.6%, Train_loss:0.391, Test_acc:84.2%, Test_loss:0.435
Epoch:25, Train_acc:89.8%, Train_loss:0.374, Test_acc:78.9%, Test_loss:0.421
Epoch:26, Train_acc:89.8%, Train_loss:0.371, Test_acc:81.6%, Test_loss:0.444
Epoch:27, Train_acc:90.2%, Train_loss:0.372, Test_acc:82.9%, Test_loss:0.435
Epoch:28, Train_acc:90.8%, Train_loss:0.360, Test_acc:80.3%, Test_loss:0.431
Epoch:29, Train_acc:89.8%, Train_loss:0.356, Test_acc:80.3%, Test_loss:0.423
Epoch:30, Train_acc:91.8%, Train_loss:0.346, Test_acc:78.9%, Test_loss:0.447
Epoch:31, Train_acc:91.2%, Train_loss:0.343, Test_acc:84.2%, Test_loss:0.420
Epoch:32, Train_acc:92.4%, Train_loss:0.338, Test_acc:82.9%, Test_loss:0.455
Epoch:33, Train_acc:92.8%, Train_loss:0.333, Test_acc:80.3%, Test_loss:0.469
Epoch:34, Train_acc:92.4%, Train_loss:0.326, Test_acc:80.3%, Test_loss:0.432
Epoch:35, Train_acc:93.0%, Train_loss:0.321, Test_acc:82.9%, Test_loss:0.429
Epoch:36, Train_acc:92.4%, Train_loss:0.323, Test_acc:77.6%, Test_loss:0.459
Epoch:37, Train_acc:93.8%, Train_loss:0.312, Test_acc:84.2%, Test_loss:0.458
Epoch:38, Train_acc:94.0%, Train_loss:0.312, Test_acc:84.2%, Test_loss:0.437
Epoch:39, Train_acc:94.8%, Train_loss:0.306, Test_acc:81.6%, Test_loss:0.434
Epoch:40, Train_acc:93.6%, Train_loss:0.304, Test_acc:84.2%, Test_loss:0.421
5、结果可视化
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 #分辨率
epoch_length = range(epoches)
plt.figure(figsize=(12, 3))
plt.subplot(1, 2, 1)
plt.plot(epoch_length, train_acc, label='Train Accuaray')
plt.plot(epoch_length, test_acc, label='Test Accuaray')
plt.legend(loc='lower right')
plt.title('Accurary')
plt.subplot(1, 2, 2)
plt.plot(epoch_length, train_loss, label='Train Loss')
plt.plot(epoch_length, test_loss, label='Test Loss')
plt.legend(loc='upper right')
plt.title('Loss')
plt.show()
模型评价
-
准确率:
- 训练集稳定逐步上升
- 测试集不太稳定,但是总体趋向上升
-
损失率:
- 训练集和测试集总体趋于下降
- 训练和测试的差距后面,大于0.1,继续训练可能会出现过拟合的现象
6、预测
from PIL import Image
# 获取类型
classes = list(train_data.class_to_idx)
# 需要参数:路径、模型、类别
def predict_one_image(image_path, model, transform, classes):
test_img = Image.open(image_path).convert('RGB') # 以GRB颜色打开
# 展示
plt.imshow(test_img)
test_img = transform(test_img) # 统一规格
# 压缩
img = test_img.to(device).unsqueeze(0) # 去掉第一个 1
# 预测
model.eval()
output = model(img)
_, pred = torch.max(output, 1)
pred_class = classes[pred]
print(f'预测结果是: {pred_class}')
# 预测
predict_one_image("./data/test/adidas/10.jpg", model, train_transforms, classes)
预测结果是: adidas
7、模型保存
path = './model.pth'
torch.save(model.state_dict(), path) # 保存模型状态
model.load_state_dict(torch.load(path, map_location=device)) # 报错模型参数
输出:
<All keys matched successfully>
8、总结
准确率和损失率:
-
理想:测试集损失率底,且测试集准确率高
-
过拟合:训练集准确率高,而测试集准确率比较低,比如在这个案例中,如果学习率直接设置固定值,会发现到后面的时候,准确率上升,甚至达到了98%,但是测试集准确率却一直在78%徘徊,故如训练次数多的时候,训练集准确度一般会一直上升(有梯度下降法优化),但是测试集可能会在后一个地方一直徘徊,甚至出现下降的现象,从而出现过拟合的现象