当前位置: 首页 > article >正文

Day 37

继续之前的学习

过拟合的判断

import torch
import torch.nn as nn
import torch.optim as optim
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
import time
import matplotlib.pyplot as plt
from tqdm import tqdm 
import warnings
warnings.filterwarnings("ignore") device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
print(f"使用设备: {device}")iris = load_iris()
X = iris.data  
y = iris.target X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)scaler = MinMaxScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)X_train = torch.FloatTensor(X_train).to(device)
y_train = torch.LongTensor(y_train).to(device)
X_test = torch.FloatTensor(X_test).to(device)
y_test = torch.LongTensor(y_test).to(device)class MLP(nn.Module):def __init__(self):super(MLP, self).__init__()self.fc1 = nn.Linear(4, 10)  self.relu = nn.ReLU()self.fc2 = nn.Linear(10, 3) def forward(self, x):out = self.fc1(x)out = self.relu(out)out = self.fc2(out)return outmodel = MLP().to(device)criterion = nn.CrossEntropyLoss()optimizer = optim.SGD(model.parameters(), lr=0.01)num_epochs = 20000 # 用于存储每200个epoch的损失值和对应的epoch数
train_losses = [] 
test_losses = [] 
epochs = []start_time = time.time() with tqdm(total=num_epochs, desc="训练进度", unit="epoch") as pbar:for epoch in range(num_epochs):outputs = model(X_train)  train_loss = criterion(outputs, y_train)optimizer.zero_grad()train_loss.backward()optimizer.step()if (epoch + 1) % 200 == 0:model.eval()with torch.no_grad():test_outputs = model(X_test)test_loss = criterion(test_outputs, y_test)model.train()train_losses.append(train_loss.item())test_losses.append(test_loss.item())epochs.append(epoch + 1)pbar.set_postfix({'Train Loss': f'{train_loss.item():.4f}', 'Test Loss': f'{test_loss.item():.4f}'})if (epoch + 1) % 1000 == 0:pbar.update(1000) if pbar.n < num_epochs:pbar.update(num_epochs - pbar.n)  time_all = time.time() - start_time  
print(f'Training time: {time_all:.2f} seconds')plt.figure(figsize=(10, 6))
plt.plot(epochs, train_losses, label='Train Loss') 
plt.plot(epochs, test_losses, label='Test Loss')  
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.title('Training and Test Loss over Epochs')
plt.legend() 
plt.grid(True)
plt.show()model.eval() 
with torch.no_grad(): outputs = model(X_test) _, predicted = torch.max(outputs, 1) # torch.max(outputs, 1)返回每行的最大值和对应的索引correct = (predicted == y_test).sum().item() accuracy = correct / y_test.size(0)print(f'测试集准确率: {accuracy * 100:.2f}%')    

模型的保存和加载

深度学习中模型的保存与加载主要涉及参数(权重)和整个模型结构的存储,同时需兼顾训练状态(如优化器参数、轮次等)以支持断点续训。

仅保存模型参数

-原理:保存模型的权重参数,不保存模型结构代码。加载时需提前定义与训练时一致的模型类。
-优点:文件体积小(仅含参数),跨框架兼容性强(需自行定义模型结构)

早停法(early stop)

我们梳理下过拟合的情况

正常情况:训练集和测试集损失同步下降,最终趋于稳定

过拟合:训练集损失持续下降,但测试集损失在某一时刻开始上升(或不再下降)

如果可以监控验证集的指标不再变好,此时提前终止训练,避免模型对训练集过度拟合。----监控的对象是验证集的指标。这种策略叫早停法。

import torch
import torch.nn as nn
import torch.optim as optim
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
import time
import matplotlib.pyplot as plt
from tqdm import tqdm  # 导入tqdm库用于进度条显示
import warnings
warnings.filterwarnings("ignore")  # 忽略警告信息# 设置GPU设备
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
print(f"使用设备: {device}")# 加载鸢尾花数据集
iris = load_iris()
X = iris.data  # 特征数据
y = iris.target  # 标签数据# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)# 归一化数据
scaler = MinMaxScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)# 将数据转换为PyTorch张量并移至GPU
X_train = torch.FloatTensor(X_train).to(device)
y_train = torch.LongTensor(y_train).to(device)
X_test = torch.FloatTensor(X_test).to(device)
y_test = torch.LongTensor(y_test).to(device)class MLP(nn.Module):def __init__(self):super(MLP, self).__init__()self.fc1 = nn.Linear(4, 10)  # 输入层到隐藏层self.relu = nn.ReLU()self.fc2 = nn.Linear(10, 3)  # 隐藏层到输出层def forward(self, x):out = self.fc1(x)out = self.relu(out)out = self.fc2(out)return out# 实例化模型并移至GPU
model = MLP().to(device)# 分类问题使用交叉熵损失函数
criterion = nn.CrossEntropyLoss()# 使用随机梯度下降优化器
optimizer = optim.SGD(model.parameters(), lr=0.01)# 训练模型
num_epochs = 20000  # 训练的轮数# 用于存储每200个epoch的损失值和对应的epoch数
train_losses = []  # 存储训练集损失
test_losses = []   # 存储测试集损失
epochs = []# ===== 新增早停相关参数 =====
best_test_loss = float('inf')  # 记录最佳测试集损失
best_epoch = 0                 # 记录最佳epoch
patience = 50                # 早停耐心值(连续多少轮测试集损失未改善时停止训练)
counter = 0                    # 早停计数器
early_stopped = False          # 是否早停标志
# ==========================start_time = time.time()  # 记录开始时间# 创建tqdm进度条
with tqdm(total=num_epochs, desc="训练进度", unit="epoch") as pbar:# 训练模型for epoch in range(num_epochs):# 前向传播outputs = model(X_train)  # 隐式调用forward函数train_loss = criterion(outputs, y_train)# 反向传播和优化optimizer.zero_grad()train_loss.backward()optimizer.step()# 记录损失值并更新进度条if (epoch + 1) % 200 == 0:# 计算测试集损失model.eval()with torch.no_grad():test_outputs = model(X_test)test_loss = criterion(test_outputs, y_test)model.train()train_losses.append(train_loss.item())test_losses.append(test_loss.item())epochs.append(epoch + 1)# 更新进度条的描述信息pbar.set_postfix({'Train Loss': f'{train_loss.item():.4f}', 'Test Loss': f'{test_loss.item():.4f}'})# ===== 新增早停逻辑 =====if test_loss.item() < best_test_loss: # 如果当前测试集损失小于最佳损失best_test_loss = test_loss.item() # 更新最佳损失best_epoch = epoch + 1 # 更新最佳epochcounter = 0 # 重置计数器# 保存最佳模型torch.save(model.state_dict(), 'best_model.pth')else:counter += 1if counter >= patience:print(f"早停触发!在第{epoch+1}轮,测试集损失已有{patience}轮未改善。")print(f"最佳测试集损失出现在第{best_epoch}轮,损失值为{best_test_loss:.4f}")early_stopped = Truebreak  # 终止训练循环# ======================# 每1000个epoch更新一次进度条if (epoch + 1) % 1000 == 0:pbar.update(1000)  # 更新进度条# 确保进度条达到100%if pbar.n < num_epochs:pbar.update(num_epochs - pbar.n)  # 计算剩余的进度并更新time_all = time.time() - start_time  # 计算训练时间
print(f'Training time: {time_all:.2f} seconds')# ===== 新增:加载最佳模型用于最终评估 =====
if early_stopped:print(f"加载第{best_epoch}轮的最佳模型进行最终评估...")model.load_state_dict(torch.load('best_model.pth'))
# ================================# 可视化损失曲线
plt.figure(figsize=(10, 6))
plt.plot(epochs, train_losses, label='Train Loss')
plt.plot(epochs, test_losses, label='Test Loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.title('Training and Test Loss over Epochs')
plt.legend()
plt.grid(True)
plt.show()# 在测试集上评估模型
model.eval()
with torch.no_grad():outputs = model(X_test)_, predicted = torch.max(outputs, 1)correct = (predicted == y_test).sum().item()accuracy = correct / y_test.size(0)print(f'测试集准确率: {accuracy * 100:.2f}%')    

http://www.lryc.cn/news/2387274.html

相关文章:

  • libvirt设置虚拟机mtu实现原理
  • AstroNex空间任务智能控制研究与训练数据集
  • 汽车副水箱液位传感器介绍
  • Docker+MobaXterm+x11实现容器UI界面转发本地
  • IEEE出版|2025年智能制造、机器人与自动化国际学术会议 (IMRA2025)
  • EasyRTC嵌入式SDK音视频实时通话助力WebRTC技术与智能硬件协同发展
  • Higress MCP Server 安全再升级:API 认证为 AI 连接保驾护航
  • 多个vue2工程共享node_modules
  • 蓝桥杯178 全球变暖
  • 多模态理解大模型高性能优化丨前沿多模态模型开发与应用实战第七期
  • mysql 合集
  • Zustand V5教程:Vanilla Store 与 useStore 使用详解 + 实战 Demo
  • docker 搭建php 开发环境 添加扩展redis、swoole、xdebug(1)
  • 人脸识别技术合规备案最新政策详解
  • (16)高性能风控系统设计
  • AStar低代码平台-脚本调用C#方法
  • 企业级RAG技术实战指南:从理论到落地的全景解析
  • getline()跳过输入
  • 【八股战神篇】RabbitMQ高频面试题
  • 高阶数据结构——红黑树实现
  • 互联网大厂Java求职面试:AI与大模型应用集成中的架构难题与解决方案
  • 安卓学习笔记-声明式UI
  • AI天气预报进入“大模型时代“:如何用Transformer重构地球大气模拟?
  • 本地项目如何设置https(2)——2025-05-19
  • 数据结构第3章 线性表 (竟成)
  • JAVA面试复习知识点
  • 项目中的流程管理之Power相关流程管理
  • SLOT:测试时样本专属语言模型优化,让大模型推理更精准!
  • 《计算机组成原理》第 10 章 - 控制单元的设计
  • 【数据结构与算法】模拟