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

DAY 37 早停策略和模型权重的保存

  1. 早停策略

import torch.nn as nn
import torch.optim as optim
import time
import matplotlib.pyplot as plt
from tqdm import tqdm# Define the MLP model
class MLP(nn.Module):def __init__(self):super(MLP, self).__init__()self.fc1 = nn.Linear(X_train.shape[1], 10)self.relu = nn.ReLU()self.fc2 = nn.Linear(10, 2)  # Binary classificationdef forward(self, x):out = self.fc1(x)out = self.relu(out)out = self.fc2(out)return out# Instantiate the model
model = MLP().to(device)# Loss and optimizer
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=0.01)# Training settings
num_epochs = 20000
early_stop_patience = 50  # Epochs to wait for improvement
best_loss = float('inf')
patience_counter = 0
best_epoch = 0
early_stopped = False# Track losses
train_losses = []
test_losses = []
epochs = []# Start training
start_time = time.time()
with tqdm(total=num_epochs, desc="Training Progress", unit="epoch") as pbar:for epoch in range(num_epochs):model.train()optimizer.zero_grad()outputs = model(X_train)train_loss = criterion(outputs, y_train)train_loss.backward()optimizer.step()# Evaluate on the test setmodel.eval()with torch.no_grad():outputs_test = model(X_test)test_loss = criterion(outputs_test, y_test)if (epoch + 1) % 200 == 0:train_losses.append(train_loss.item())test_losses.append(test_loss.item())epochs.append(epoch + 1)# Early stopping checkif test_loss.item() < best_loss:  # If current test loss is better than the bestbest_loss = test_loss.item()  # Update best lossbest_epoch = epoch + 1  # Update best epochpatience_counter = 0  # Reset counter# Save the best modeltorch.save(model.state_dict(), 'best_model.pth')else:patience_counter += 1if patience_counter >= early_stop_patience:print(f"Early stopping triggered! No improvement for {early_stop_patience} epochs.")print(f"Best test loss was at epoch {best_epoch} with a loss of {best_loss:.4f}")early_stopped = Truebreak  # Stop the training loop# Update the progress barpbar.set_postfix({'Train Loss': f'{train_loss.item():.4f}', 'Test Loss': f'{test_loss.item():.4f}'})# Update progress bar every 1000 epochsif (epoch + 1) % 1000 == 0:pbar.update(1000)# Ensure progress bar reaches 100%
if pbar.n < num_epochs:pbar.update(num_epochs - pbar.n)time_all = time.time() - start_time  # Calculate total training time
print(f'Training time: {time_all:.2f} seconds')# If early stopping occurred, load the best model
if early_stopped:print(f"Loading best model from epoch {best_epoch} for final evaluation...")model.load_state_dict(torch.load('best_model.pth'))# Continue training for 50 more epochs after loading the best model
num_extra_epochs = 50
for epoch in range(num_extra_epochs):model.train()optimizer.zero_grad()outputs = model(X_train)train_loss = criterion(outputs, y_train)train_loss.backward()optimizer.step()# Evaluate on the test setmodel.eval()with torch.no_grad():outputs_test = model(X_test)test_loss = criterion(outputs_test, y_test)train_losses.append(train_loss.item())test_losses.append(test_loss.item())epochs.append(num_epochs + epoch + 1)# Print progress for the extra epochsprint(f"Epoch {num_epochs + epoch + 1}: Train Loss = {train_loss.item():.4f}, Test Loss = {test_loss.item():.4f}")# Plot the loss curves
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()# Evaluate final accuracy on the test set
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'Test Accuracy: {accuracy * 100:.2f}%')

@浙大疏锦行

http://www.xdnf.cn/news/14535.html

相关文章:

  • @annotation:Spring AOP 的“精准定位器“
  • uniapp开发小程序,导出文件打开并保存,实现过程downloadFile下载,openDocument打开
  • 4.文件管理(文本、日志、Excel表)
  • 基于PyQt5和PaddleSpeech的中文语音识别系统设计与实现(Python)
  • Spring Boot + MyBatis + Vue:全栈开发中的最佳实践
  • C++11 右值引用(Rvalue Reference)
  • MySQL 数据库索引详解
  • 【AI时代速通QT】第二节:Qt SDK 的目录介绍和第一个Qt Creator项目
  • Linux tail 命令
  • Android图形系统框架解析
  • 实时输出subprocess.Popen运行程序的日志
  • 面试第三期
  • 【Bug:docker】--Docker同时部署Dify和RAGFlow出现错误
  • Spring-创建第一个SpringBoot项目
  • StableDiffusion实战-手机壁纸制作 第一篇:从零基础到生成艺术品的第一步!
  • 解密提示词工程师:AI 时代的新兴职业
  • 视频续播功能实现 - 断点续看从前端到 Spring Boot 后端
  • C#最佳实践:为何优先使用查询语法而非循环
  • HALCON相机标定
  • Laravel框架的发展前景与Composer的核心作用-优雅草卓伊凡
  • 微信小程序:实现左侧菜单、右侧内容、表单、新增按钮等组件封装
  • 蜻蜓Q系统的技术演进:从Laravel 6到Laravel 8的升级之路-优雅草卓伊凡
  • web3 浏览器注入 (如 MetaMask)
  • 如何获取 vscode 的 vsix 离线插件安装包
  • jmeter学习
  • JETBRAINS IDE 开发环境自定义设置快捷键
  • MySQL存储引擎深度解析:InnoDB、MyISAM、MEMORY 与 ARCHIVE 的全面对比与选型建议
  • FPGA基础 -- Verilog行为级建模之alawys语句
  • 【深度学习】卷积神经网络(CNN):计算机视觉的革命性引擎
  • 最新期刊影响因子,基本包含全部期刊