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

【手写数字识别】GPU训练版本

SVM

Adaboost

Bagging

完整代码 I

import torch
import torch.nn.functional as F
from torch.utils.data import DataLoader, TensorDataset
from torchvision import transforms, datasets
import matplotlib.pyplot as plt# 超参数
batch_size = 64
num_epochs = 10# 数据集准备
transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))])
train_dataset = datasets.MNIST(root='./data/demo2', train=True, transform=transform, download=True)
test_dataset = datasets.MNIST(root='./data/demo2', train=False, transform=transform, download=True)
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
test_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False)# SVM 模型 (在GPU上训练)
class SVMModel(torch.nn.Module):def __init__(self):super(SVMModel, self).__init__()self.flatten = torch.nn.Flatten()  self.linear = torch.nn.Linear(28 * 28, 10)  def forward(self, x):x = self.flatten(x)  return self.linear(x)svm_model = SVMModel().cuda()
criterion = torch.nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(svm_model.parameters(), lr=0.01)# 训练和评估
svm_train_losses = []
svm_test_accuracies = []for epoch in range(num_epochs):for batch_idx, (data, labels) in enumerate(train_loader):data, labels = data.cuda(), labels.cuda()outputs = svm_model(data)loss = criterion(outputs, labels)optimizer.zero_grad()loss.backward()optimizer.step()svm_train_losses.append(loss.item())with torch.no_grad():test_accuracy = 0total = 0for batch_idx, (data, labels) in enumerate(test_loader):data, labels = data.cuda(), labels.cuda()outputs = svm_model(data)_, predicted = torch.max(outputs, 1)test_accuracy += torch.sum(predicted == labels).item()total += labels.size(0)accuracy = (test_accuracy / total) * 100svm_test_accuracies.append(accuracy)print('SVM - Epoch [{}/{}], Test Accuracy: {:.2f}%'.format(epoch + 1, num_epochs, accuracy))# Adaboost 模型 (在GPU上训练)
class AdaboostModel(torch.nn.Module):def __init__(self, num_estimators):super(AdaboostModel, self).__init__()self.num_estimators = num_estimatorsself.models = torch.nn.ModuleList([SVMModel() for _ in range(num_estimators)])def forward(self, x):outputs = torch.zeros(x.size(0), 10).cuda()for i in range(self.num_estimators):outputs += self.models[i](x)return outputsadaboost_model = AdaboostModel(num_estimators=50).cuda()
criterion = torch.nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(adaboost_model.parameters(), lr=0.01)# 训练和评估
adaboost_train_losses = []
adaboost_test_accuracies = []for epoch in range(num_epochs):for batch_idx, (data, labels) in enumerate(train_loader):data, labels = data.cuda(), labels.cuda()outputs = adaboost_model(data)loss = criterion(outputs, labels)optimizer.zero_grad()loss.backward()optimizer.step()adaboost_train_losses.append(loss.item())with torch.no_grad():test_accuracy = 0total = 0for batch_idx, (data, labels) in enumerate(test_loader):data, labels = data.cuda(), labels.cuda()outputs = adaboost_model(data)_, predicted = torch.max(outputs, 1)test_accuracy += torch.sum(predicted == labels).item()total += labels.size(0)accuracy = (test_accuracy / total) * 100adaboost_test_accuracies.append(accuracy)print('Adaboost - Epoch [{}/{}], Test Accuracy: {:.2f}%'.format(epoch + 1, num_epochs, accuracy))# Bagging 模型 (在GPU上训练)
class BaggingModel(torch.nn.Module):def __init__(self, num_estimators):super(BaggingModel, self).__init__()self.num_estimators = num_estimatorsself.models = torch.nn.ModuleList([SVMModel() for _ in range(num_estimators)])def forward(self, x):outputs = torch.zeros(x.size(0), 10).cuda()for i in range(self.num_estimators):outputs += self.models[i](x)return outputsbagging_model = BaggingModel(num_estimators=50).cuda()
criterion = torch.nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(bagging_model.parameters(), lr=0.01)# 训练和评估
bagging_train_losses = []
bagging_test_accuracies = []for epoch in range(num_epochs):for batch_idx, (data, labels) in enumerate(train_loader):data, labels = data.cuda(), labels.cuda()outputs = bagging_model(data)loss = criterion(outputs, labels)optimizer.zero_grad()loss.backward()optimizer.step()bagging_train_losses.append(loss.item())with torch.no_grad():test_accuracy = 0total = 0for batch_idx, (data, labels) in enumerate(test_loader):data, labels = data.cuda(), labels.cuda()outputs = bagging_model(data)_, predicted = torch.max(outputs, 1)test_accuracy += torch.sum(predicted == labels).item()total += labels.size(0)accuracy = (test_accuracy / total) * 100bagging_test_accuracies.append(accuracy)print('Bagging - Epoch [{}/{}], Test Accuracy: {:.2f}%'.format(epoch + 1, num_epochs, accuracy))# 可视化
plt.figure(figsize=(12, 4))plt.subplot(1, 2, 1)
plt.plot(svm_train_losses, label='SVM Train Loss')
plt.xlabel('Iterations')
plt.ylabel('Loss')
plt.legend()plt.subplot(1, 2, 2)
plt.plot(svm_test_accuracies, label='SVM Test Accuracy', color='orange')
plt.plot(adaboost_test_accuracies, label='Adaboost Test Accuracy', color='green')
plt.plot(bagging_test_accuracies, label='Bagging Test Accuracy', color='blue')
plt.xlabel('Epochs')
plt.ylabel('Accuracy (%)')
plt.legend()plt.show()

在这里插入图片描述

在这里插入图片描述

从gpu使用率看:
在这里插入图片描述


完整代码 II

import torch
import torch.nn.functional as F
from torch.utils.data import DataLoader, TensorDataset
from torchvision import transforms, datasets
import matplotlib.pyplot as plt# 超参数
batch_size = 64
num_epochs = 10# 数据集准备
transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))])
train_dataset = datasets.MNIST(root='./data/demo2', train=True, transform=transform, download=True)
test_dataset = datasets.MNIST(root='./data/demo2', train=False, transform=transform, download=True)
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
test_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False)# SVM 模型定义
class SVMModel(torch.nn.Module):def __init__(self):super(SVMModel, self).__init__()self.flatten = torch.nn.Flatten()self.linear = torch.nn.Linear(28 * 28, 10)def forward(self, x):x = self.flatten(x)return self.linear(x)# Adaboost 模型定义
class AdaboostModel(torch.nn.Module):def __init__(self, num_estimators):super(AdaboostModel, self).__init__()self.num_estimators = num_estimatorsself.models = torch.nn.ModuleList([SVMModel() for _ in range(num_estimators)])def forward(self, x):outputs = torch.zeros(x.size(0), 10).cuda()for i in range(self.num_estimators):outputs += self.models[i](x)return outputs# Bagging 模型定义
class BaggingModel(torch.nn.Module):def __init__(self, num_estimators):super(BaggingModel, self).__init__()self.num_estimators = num_estimatorsself.models = torch.nn.ModuleList([SVMModel() for _ in range(num_estimators)])def forward(self, x):outputs = torch.zeros(x.size(0), 10).cuda()for i in range(self.num_estimators):outputs += self.models[i](x)return outputs# 训练函数
def train_model(model, train_loader, test_loader, num_epochs, optimizer, criterion):train_losses = []test_accuracies = []best_accuracy = 0for epoch in range(num_epochs):model.train()for batch_idx, (data, labels) in enumerate(train_loader):data, labels = data.cuda(), labels.cuda()outputs = model(data)loss = criterion(outputs, labels)optimizer.zero_grad()loss.backward()optimizer.step()train_losses.append(loss.item())model.eval()with torch.no_grad():test_accuracy = 0total = 0for batch_idx, (data, labels) in enumerate(test_loader):data, labels = data.cuda(), labels.cuda()outputs = model(data)_, predicted = torch.max(outputs, 1)test_accuracy += torch.sum(predicted == labels).item()total += labels.size(0)accuracy = (test_accuracy / total) * 100test_accuracies.append(accuracy)# 更新最佳准确率和最佳模型if accuracy > best_accuracy:best_accuracy = accuracybest_model = model.state_dict()print('Epoch [{}/{}], Test Accuracy: {:.2f}%'.format(epoch + 1, num_epochs, accuracy))# 返回训练过程中的损失、准确率和最佳模型的状态字典return train_losses, test_accuracies, best_model# 创建SVM模型、Adaboost模型和Bagging模型
svm_model = SVMModel().cuda()
adaboost_model = AdaboostModel(num_estimators=50).cuda()
bagging_model = BaggingModel(num_estimators=50).cuda()# 损失函数和优化器
criterion = torch.nn.CrossEntropyLoss()
svm_optimizer = torch.optim.SGD(svm_model.parameters(), lr=0.01)
adaboost_optimizer = torch.optim.SGD(adaboost_model.parameters(), lr=0.01)
bagging_optimizer = torch.optim.SGD(bagging_model.parameters(), lr=0.01)# 训练SVM模型
print('训练SVM模型:')
svm_train_losses, svm_test_accuracies, svm_best_model = train_model(svm_model, train_loader, test_loader, num_epochs,svm_optimizer, criterion)# 训练Adaboost模型
print('训练Adaboost模型:')
adaboost_train_losses, adaboost_test_accuracies, adaboost_best_model = train_model(adaboost_model, train_loader,test_loader, num_epochs,adaboost_optimizer, criterion)# 训练Bagging模型
print('训练Bagging模型:')
bagging_train_losses, bagging_test_accuracies, bagging_best_model = train_model(bagging_model, train_loader,test_loader, num_epochs,bagging_optimizer, criterion)# SVM、Adaboost和Bagging三个模型在测试集上的最佳准确率
print('SVM Best Test Accuracy: {:.2f}%'.format(max(svm_test_accuracies)))
print('Adaboost Best Test Accuracy: {:.2f}%'.format(max(adaboost_test_accuracies)))
print('Bagging Best Test Accuracy: {:.2f}%'.format(max(bagging_test_accuracies)))# 三个模型的准确率最好的放在一起进行可视化对比
plt.figure(figsize=(8, 6))
plt.plot(svm_test_accuracies, label='SVM Test Accuracy', color='orange')
plt.plot(adaboost_test_accuracies, label='Adaboost Test Accuracy', color='green')
plt.plot(bagging_test_accuracies, label='Bagging Test Accuracy', color='blue')
plt.xlabel('Epochs')
plt.ylabel('Accuracy (%)')
plt.legend()
plt.show()

在这里插入图片描述
在这里插入图片描述

相关文章:

【手写数字识别】GPU训练版本

SVM Adaboost Bagging 完整代码 I import torch import torch.nn.functional as F from torch.utils.data import DataLoader, TensorDataset from torchvision import transforms, datasets import matplotlib.pyplot as plt# 超参数 batch_size 64 num_epochs 10# 数据…...

c#-特殊的集合

位数组 可观察的集合 private ObservableCollection<string> strList new ObservableCollection<string>();// Start is called before the first frame updatevoid Start(){strList.CollectionChanged Change;strList.Add("ssss");strList.Add("…...

Android 使用 eChart 设置标线

echart使用标线 Android部分&#xff1a; import android.webkit.WebView; import com.jianqu.plasmasterilizer.R; import com.jianqu.plasmasterilizer.utils.DisplayUtils; import com.jianqu.plasmasterilizer.utils.TimerUtil; import java.util.ArrayList; import java.…...

红队专题-Cobalt strike 4.x - Beacon重构

红队专题 招募六边形战士队员重构后 Beacon 适配的功能windows平台linux和mac平台C2profile 重构思路跨平台功能免杀代码部分sysinfo包packet包config.go命令的执行shell、run、executepowershell powerpick命令powershell-importexecute-assembly 堆内存加密字符集 招募六边形…...

一文掌握 Go 文件的写入操作

前言 通过案例展示如何读取文件里的内容。本文接着上篇文章的内容&#xff0c;介绍文件的写入操作。 File.Write、File.WriteString、File.WriteAt File.Write(b []byte) (n int, err error) 直接操作磁盘往文件里写入数据&#xff0c;写入单位为字节。 b 参数&#xff1a;…...

小程序入门及案例展示

目录 一、小程序简介 1.1 为什么要使用小程序 1.2 小程序可以干什么 二、前期准备 2.1 申请账号 2.2 开发工具下载与安装 三、电商案例演示 四、入门案例 4.1 项目结构解析 4.2 基础操作及语法 4.3 模拟器 4.4 案例演示 4.4.1 新建页面 4.4.2 头部样式设置 4.4.…...

linux 安装python django pip 遇到的问题

Python解决SSL不可用问题 解决方案&#xff1a; 首先要明白python版本需要和openssl的版本需要相对匹配的&#xff0c;在Python3.7之后的版本&#xff0c;依赖的openssl&#xff0c;必须要是1.1或者1.0.2之后的版本&#xff0c;或者安装了2.6.4之后的libressl&#xff0c;linux…...

【问题解决】【爬虫】抓包工具charles与pycharm发送https请求冲突问题

问题&#xff1a; 开启charles抓包&#xff0c;运行pycharm发送https请求报以下错误 解决&#xff1a; 修改python代码&#xff0c;发送请求时添加verify false&#xff0c;此时charles也能抓取到pycharm发送的请求 2. 关闭charles抓包&#xff0c;取消勾选window proxy...

Hadoop3教程(二):HDFS的定义及概述

文章目录 &#xff08;40&#xff09;HDFS产生的背景和定义&#xff08;41&#xff09;HDFS的优缺点&#xff08;42&#xff09;HDFS组成架构&#xff08;43&#xff09;HDFS文件块大小&#xff08;面试重点&#xff09;参考文献 &#xff08;40&#xff09;HDFS产生的背景和定…...

【物联网+JAVA 】智慧工地源码

一、什么是智慧工地&#xff1f; 工地本身不拥有智慧&#xff0c;工地的运作是依赖于人的智慧。工地信息化技术&#xff0c;能够减少对人的依赖&#xff0c;使工地拥有智慧。 智慧工地&#xff0c;就是立足于“智慧城市”和“互联网”&#xff0c;采用云计算、大数据和物联网…...

001数据安全传输-多端协议传输平台:Openssl安装和配置 - EVP代码测试

001数据安全传输-多端协议传输平台&#xff1a;Openssl安装和配置 - EVP代码测试 文章目录 001数据安全传输-多端协议传输平台&#xff1a;Openssl安装和配置 - EVP代码测试1. 安装1.1 windows下安装openssl1.2 Linux下安装OpenSSL 2. VS中使用openssl3. 测试 1. 安装 1.1 win…...

关于小编入坑第512天

​机缘 最初成为创作者的初心&#xff1a;总结记录整个学习前端的历程 日常学习过程中的记录&#xff1a; 先思考&#xff0c;整个程序逻辑流程是否出现问题 再文档&#xff0c;根据相关文档了解源头&#xff0c;学会看懂文档&#xff0c;是一个锻炼自学前端能力的关键一步 …...

VS2015编译Qt工程发生MSB4018错误完整解决过程

一、错误产生环境 操作系统&#xff1a;Windows10 开发工具&#xff1a;VS2015企业版 Qt版本&#xff1a;Qt5.7.1 64位 二、错误内容 MSB4018 “VCMessage”任务意外失败。 System.FormatException: 索引(从零开始)必须大于或等于零&#xff0c;且小于参数列表的大小。 …...

如何使用JMeter测试导入接口/导出接口

今天一上班&#xff0c;被开发问了一个问题&#xff1a;JMeter调试接口&#xff0c;文件导入接口怎么老是不通&#xff1f;还有导出文件接口&#xff0c;不知道文件导到哪里去了&#xff1f; 我一听&#xff0c;这不是JMeter做接口测试经常遇到的嘛&#xff0c;但是一时半会又…...

[入门一]C# webApi创建、与发布、部署、api调用

一.创建web api项目 1.1、项目创建 MVC架构的话&#xff0c;它会有view-model-control三层&#xff0c;在web api中它的前端和后端是分离的&#xff0c;所以只在项目中存在model-control两层 1.2、修改路由 打开App_Start文件夹下&#xff0c;WebApiConfig.cs ,修改路由&…...

关于Vue+webpack使用unocss编写CSS,打包后CSS没加前缀

关于Vuewebpack使用unocss编写CSS&#xff0c;打包后CSS没加前缀&#xff0c;封装了一个插件去解决了这个问题 unocss-postcss-webpack-plugin unocss在vite中使用配置&#xff0c;关于unocss在vite中使用&#xff0c;自行查阅官网 https://unocss.dev/integrations/vite ,vi…...

软件工程与计算总结(十一)人机交互设计

目录 ​编辑 一.引例 二.目标 三.人类因素 1.精神模型 2.差异性 四.计算机因素 1.可视化设计 2.常见界面类型 五.人机交互设计的交互性 1.导航 2.反馈 3.设计原则 六.设计过程 1.基本过程 2.界面原型化 一.引例 无论软件功能多么出色&#xff0c;亦或内部的构造…...

Jmeter组件执行顺序与作用域

一、Jmeter重要组件&#xff1a; 1&#xff09;配置元件---Config Element&#xff1a; 用于初始化默认值和变量&#xff0c;以便后续采样器使用。配置元件大其作用域的初始阶段处理&#xff0c;配置元件仅对其所在的测试树分支有效&#xff0c;如&#xff0c;在同一个作用域的…...

第一天商城项目

复盘 1.maven高级部分聚合和继承 maven聚合工程(深度剖析)_一宿君的博客-CSDN博客 2.yml配置文件 mybatis mybatis: mapper-locations: classpath:mappers/*mapper.xml mapper-locations&#xff1a;这是一个子键&#xff0c;用于指定MyBatis映射文件&#xff08;Mapper XML…...

C++笔记之通用多态函数包装器std::function

C笔记之通用多态函数包装器std::function code review! 文章目录 C笔记之通用多态函数包装器std::function1.存储自由函数&#xff0c;lambda&#xff0c;std::bind 调用的结果2.存储到成员的调用3.存储到函数对象四.基本语法五.使用std::function定义函数对象六.使用std::fu…...

前端倒计时误差!

提示:记录工作中遇到的需求及解决办法 文章目录 前言一、误差从何而来?二、五大解决方案1. 动态校准法(基础版)2. Web Worker 计时3. 服务器时间同步4. Performance API 高精度计时5. 页面可见性API优化三、生产环境最佳实践四、终极解决方案架构前言 前几天听说公司某个项…...

Linux相关概念和易错知识点(42)(TCP的连接管理、可靠性、面临复杂网络的处理)

目录 1.TCP的连接管理机制&#xff08;1&#xff09;三次握手①握手过程②对握手过程的理解 &#xff08;2&#xff09;四次挥手&#xff08;3&#xff09;握手和挥手的触发&#xff08;4&#xff09;状态切换①挥手过程中状态的切换②握手过程中状态的切换 2.TCP的可靠性&…...

unix/linux,sudo,其发展历程详细时间线、由来、历史背景

sudo 的诞生和演化,本身就是一部 Unix/Linux 系统管理哲学变迁的微缩史。来,让我们拨开时间的迷雾,一同探寻 sudo 那波澜壮阔(也颇为实用主义)的发展历程。 历史背景:su的时代与困境 ( 20 世纪 70 年代 - 80 年代初) 在 sudo 出现之前,Unix 系统管理员和需要特权操作的…...

leetcodeSQL解题:3564. 季节性销售分析

leetcodeSQL解题&#xff1a;3564. 季节性销售分析 题目&#xff1a; 表&#xff1a;sales ---------------------- | Column Name | Type | ---------------------- | sale_id | int | | product_id | int | | sale_date | date | | quantity | int | | price | decimal | -…...

3-11单元格区域边界定位(End属性)学习笔记

返回一个Range 对象&#xff0c;只读。该对象代表包含源区域的区域上端下端左端右端的最后一个单元格。等同于按键 End 向上键(End(xlUp))、End向下键(End(xlDown))、End向左键(End(xlToLeft)End向右键(End(xlToRight)) 注意&#xff1a;它移动的位置必须是相连的有内容的单元格…...

ABAP设计模式之---“简单设计原则(Simple Design)”

“Simple Design”&#xff08;简单设计&#xff09;是软件开发中的一个重要理念&#xff0c;倡导以最简单的方式实现软件功能&#xff0c;以确保代码清晰易懂、易维护&#xff0c;并在项目需求变化时能够快速适应。 其核心目标是避免复杂和过度设计&#xff0c;遵循“让事情保…...

SiFli 52把Imagie图片,Font字体资源放在指定位置,编译成指定img.bin和font.bin的问题

分区配置 (ptab.json) img 属性介绍&#xff1a; img 属性指定分区存放的 image 名称&#xff0c;指定的 image 名称必须是当前工程生成的 binary 。 如果 binary 有多个文件&#xff0c;则以 proj_name:binary_name 格式指定文件名&#xff0c; proj_name 为工程 名&…...

Linux 内存管理实战精讲:核心原理与面试常考点全解析

Linux 内存管理实战精讲&#xff1a;核心原理与面试常考点全解析 Linux 内核内存管理是系统设计中最复杂但也最核心的模块之一。它不仅支撑着虚拟内存机制、物理内存分配、进程隔离与资源复用&#xff0c;还直接决定系统运行的性能与稳定性。无论你是嵌入式开发者、内核调试工…...

手机平板能效生态设计指令EU 2023/1670标准解读

手机平板能效生态设计指令EU 2023/1670标准解读 以下是针对欧盟《手机和平板电脑生态设计法规》(EU) 2023/1670 的核心解读&#xff0c;综合法规核心要求、最新修正及企业合规要点&#xff1a; 一、法规背景与目标 生效与强制时间 发布于2023年8月31日&#xff08;OJ公报&…...

MySQL 主从同步异常处理

阅读原文&#xff1a;https://www.xiaozaoshu.top/articles/mysql-m-s-update-pk MySQL 做双主&#xff0c;遇到的这个错误&#xff1a; Could not execute Update_rows event on table ... Error_code: 1032是 MySQL 主从复制时的经典错误之一&#xff0c;通常表示&#xff…...