福州云建站模版,wordpress设置登录和跳转到主页,网站静态页面做网站,男人直接做的视频网站#x1f368; 本文为#x1f517;365天深度学习训练营 中的学习记录博客#x1f356; 原作者#xff1a;K同学啊 前言 前几天一直很忙#xff0c;一直在数学建模中#xff0c;没有来得及更新#xff0c;接下来将恢复正常这一次的案例很有意思#xff1a;在学习动态调整… 本文为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输出
cuda2、数据导入与展示
# 查看数据数据文件夹内容
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(roottrain_path, transformtrain_transforms)
test_data datasets.ImageFolder(roottest_path, transformtest_transforms)4、加载与划分动态数据
batch_size 32train_dl torch.utils.data.DataLoader(train_data,batch_sizebatch_size,shuffleTrue,num_workers1)test_dl torch.utils.data.DataLoader(test_data,batch_sizebatch_size,shuffleTrue,num_workers1)# 展示图像参数
for param, data in train_dl:print(image(N, C, H, W): , param.shape)print(data: , data)breakimage(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_channels3, out_channels12, kernel_size5, padding0),nn.BatchNorm2d(12), # 第一个参数特征数量nn.ReLU())self.conv2 nn.Sequential(nn.Conv2d(in_channels12, out_channels12, kernel_size5, padding0),nn.BatchNorm2d(12),nn.ReLU())self.pool1 nn.Sequential(nn.MaxPool2d(2, 2))self.conv3 nn.Sequential(nn.Conv2d(in_channels12, out_channels24, kernel_size5, padding0),nn.BatchNorm2d(24),nn.ReLU())self.conv4 nn.Sequential(nn.Conv2d(in_channels24, out_channels24, kernel_size5, padding0),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,Wx 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, eps1e-05, momentum0.1, affineTrue, track_running_statsTrue)(2): ReLU())(conv2): Sequential((0): Conv2d(12, 12, kernel_size(5, 5), stride(1, 1))(1): BatchNorm2d(12, eps1e-05, momentum0.1, affineTrue, track_running_statsTrue)(2): ReLU())(pool1): Sequential((0): MaxPool2d(kernel_size2, stride2, padding0, dilation1, ceil_modeFalse))(conv3): Sequential((0): Conv2d(12, 24, kernel_size(5, 5), stride(1, 1))(1): BatchNorm2d(24, eps1e-05, momentum0.1, affineTrue, track_running_statsTrue)(2): ReLU())(conv4): Sequential((0): Conv2d(24, 24, kernel_size(5, 5), stride(1, 1))(1): BatchNorm2d(24, eps1e-05, momentum0.1, affineTrue, track_running_statsTrue)(2): ReLU())(pool2): Sequential((0): MaxPool2d(kernel_size2, stride2, padding0, dilation1, ceil_modeFalse))(dropout): Sequential((0): Dropout(p0.2, inplaceFalse))(fc): Sequential((0): Linear(in_features60000, out_features2, biasTrue))
)3、模型的训练准备
1、设置超参数
# 创建损失函数
loss_fn nn.CrossEntropyLoss()
# 初始化学习率
lr 1e-4
# 创建梯度下降法
optimizer torch.optim.SGD(model.parameters(), lrlr)
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 / sizetrain_loss / batch_sizereturn trian_acc, train_loss3、创建测试函数
def test(dataloader, model, loss_fn):size len(dataloader.dataset)batch_size len(dataloader)test_acc, test_loss 0, 0with 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_sizereturn test_acc, test_loss4、动态调整学习率
def adjust_learning_rate(optimizer, epoch, start_lr):# 调整规则每 2 次都衰减到原来的 0.92lr start_lr * (0.95 ** (epoch // 2))for param_group in optimizer.param_groups:param_group[lr] lr4、正式训练
train_acc []
train_loss []
test_acc []
test_loss []# 定义训练次数
epoches 40for 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(epoch1, 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.4215、结果可视化
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, labelTrain Accuaray)
plt.plot(epoch_length, test_acc, labelTest Accuaray)
plt.legend(loclower right)
plt.title(Accurary)plt.subplot(1, 2, 2)
plt.plot(epoch_length, train_loss, labelTrain Loss)
plt.plot(epoch_length, test_loss, labelTest Loss)
plt.legend(locupper 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)预测结果是: adidas7、模型保存
path ./model.pth
torch.save(model.state_dict(), path) # 保存模型状态model.load_state_dict(torch.load(path, map_locationdevice)) # 报错模型参数输出
All keys matched successfully8、总结
准确率和损失率 理想测试集损失率底且测试集准确率高 过拟合训练集准确率高而测试集准确率比较低比如在这个案例中如果学习率直接设置固定值会发现到后面的时候准确率上升甚至达到了98%但是测试集准确率却一直在78%徘徊故如训练次数多的时候训练集准确度一般会一直上升(有梯度下降法优化)但是测试集可能会在后一个地方一直徘徊甚至出现下降的现象从而出现过拟合的现象