当前位置: 首页 > 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…...

JavaSec-RCE

简介 RCE(Remote Code Execution)&#xff0c;可以分为:命令注入(Command Injection)、代码注入(Code Injection) 代码注入 1.漏洞场景&#xff1a;Groovy代码注入 Groovy是一种基于JVM的动态语言&#xff0c;语法简洁&#xff0c;支持闭包、动态类型和Java互操作性&#xff0c…...

idea大量爆红问题解决

问题描述 在学习和工作中&#xff0c;idea是程序员不可缺少的一个工具&#xff0c;但是突然在有些时候就会出现大量爆红的问题&#xff0c;发现无法跳转&#xff0c;无论是关机重启或者是替换root都无法解决 就是如上所展示的问题&#xff0c;但是程序依然可以启动。 问题解决…...

C++初阶-list的底层

目录 1.std::list实现的所有代码 2.list的简单介绍 2.1实现list的类 2.2_list_iterator的实现 2.2.1_list_iterator实现的原因和好处 2.2.2_list_iterator实现 2.3_list_node的实现 2.3.1. 避免递归的模板依赖 2.3.2. 内存布局一致性 2.3.3. 类型安全的替代方案 2.3.…...

安宝特方案丨XRSOP人员作业标准化管理平台:AR智慧点检验收套件

在选煤厂、化工厂、钢铁厂等过程生产型企业&#xff0c;其生产设备的运行效率和非计划停机对工业制造效益有较大影响。 随着企业自动化和智能化建设的推进&#xff0c;需提前预防假检、错检、漏检&#xff0c;推动智慧生产运维系统数据的流动和现场赋能应用。同时&#xff0c;…...

2024年赣州旅游投资集团社会招聘笔试真

2024年赣州旅游投资集团社会招聘笔试真 题 ( 满 分 1 0 0 分 时 间 1 2 0 分 钟 ) 一、单选题(每题只有一个正确答案,答错、不答或多答均不得分) 1.纪要的特点不包括()。 A.概括重点 B.指导传达 C. 客观纪实 D.有言必录 【答案】: D 2.1864年,()预言了电磁波的存在,并指出…...

抖音增长新引擎:品融电商,一站式全案代运营领跑者

抖音增长新引擎&#xff1a;品融电商&#xff0c;一站式全案代运营领跑者 在抖音这个日活超7亿的流量汪洋中&#xff0c;品牌如何破浪前行&#xff1f;自建团队成本高、效果难控&#xff1b;碎片化运营又难成合力——这正是许多企业面临的增长困局。品融电商以「抖音全案代运营…...

多模态商品数据接口:融合图像、语音与文字的下一代商品详情体验

一、多模态商品数据接口的技术架构 &#xff08;一&#xff09;多模态数据融合引擎 跨模态语义对齐 通过Transformer架构实现图像、语音、文字的语义关联。例如&#xff0c;当用户上传一张“蓝色连衣裙”的图片时&#xff0c;接口可自动提取图像中的颜色&#xff08;RGB值&…...

Java面试专项一-准备篇

一、企业简历筛选规则 一般企业的简历筛选流程&#xff1a;首先由HR先筛选一部分简历后&#xff0c;在将简历给到对应的项目负责人后再进行下一步的操作。 HR如何筛选简历 例如&#xff1a;Boss直聘&#xff08;招聘方平台&#xff09; 直接按照条件进行筛选 例如&#xff1a…...

蓝桥杯3498 01串的熵

问题描述 对于一个长度为 23333333的 01 串, 如果其信息熵为 11625907.5798&#xff0c; 且 0 出现次数比 1 少, 那么这个 01 串中 0 出现了多少次? #include<iostream> #include<cmath> using namespace std;int n 23333333;int main() {//枚举 0 出现的次数//因…...

初探Service服务发现机制

1.Service简介 Service是将运行在一组Pod上的应用程序发布为网络服务的抽象方法。 主要功能&#xff1a;服务发现和负载均衡。 Service类型的包括ClusterIP类型、NodePort类型、LoadBalancer类型、ExternalName类型 2.Endpoints简介 Endpoints是一种Kubernetes资源&#xf…...