【手写数字识别】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()

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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/133511.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

A星寻路优化方案

1.存储常用位置间的路径信息(此优化方案一般用于地图较大,且起始点离终点较远情况下) 对于地图信息已知且各障碍位置固定的情况下,可以将常用的位置及其之间的路径信息保存,然后寻路时分别找到离开始点,结…

Axios 封装

请注意以下文件夹: utils下的setToken.js 是token封装(封装 Token-CSDN博客),service.js 是axios封装。 Axios封装: 1.安装axios 在项目终端下 输入: npm install axios --save 2.在main.js全局引入axios import…

「五度情报站」网罗全量企业情报,找客户、查竞品、寻商机!

在当下严峻的市场经济环境下,准确、及时的情报信息,就如同指引企业前行的明灯,能够让企业在风起云涌的市场大潮中保持敏锐的洞察力,掌握最新的市场动态,洞悉竞争对手的一举一动,先知先动,保持竞…

数字化转型背景下,MES管理系统的新特征是什么

近年来,随着智能制造的快速发展,MES管理系统作为生产过程中的重要管理系统,也越来越受到企业的关注和应用。在实现MES系统的过程中,需要将JIT思想融入其中,实现业务流程管理的自动化;同时,也需要…

苍穹外卖(三) 员工分页及技术实现细节

2. 员工分页查询 2.1 需求分析和设计 2.1.1 产品原型 2.1.2 接口设计 2.2 代码开发 2.2.1 设计DTO类 根据请求参数进行封装 2.2.2 封装PageResult 后面所有的分页查询,统一都封装为PageResult对象。 员工信息分页查询后端返回的对象类型为: Result 2.…

如何在Ubuntu 20.04.6 LTS系统上运行Playwright自动化测试

写在前面 这里以 Ubuntu 20.04.6 LTS为例。示例代码:自动化测试代码。 如果过程中遇到其他非文本中提到的错误,可以使用搜索引擎搜索错误,找出解决方案,再逐步往下进行。 一、 环境准备 1.1 安装python3 1.1.1 使用APT安装Py…

一种用于肽图分析的烷化剂,Desthiobiotin-Iodoacetamide

中文名:脱硫生物素-碘乙酰胺 英文名:Desthiobiotin-Iodoacetamide 化学式:C14H25IN4O3 分子量:424.28 外观:固体/粉末 规格:10mg、25mg、50mg等(接受各种规格的定制服务,具体可…

源码部署lamt架构

源码部署lamt架构 lamt由apache,mysql,tomcat三者组成 文章目录 源码部署lamt架构1.准备工作1.1.配置yum源,关闭防火墙和selinux1.2.拉取相应源码包 2.安装apache3.安装mariadb4.安装tomcat 1.准备工作 1.1.配置yum源,关闭防火墙…

Linux上安装Redis教程

本篇文章是基于CentOS7,安装Redis版本为redis-6.2.6。 一、下载并解压Redis 1、执行下面的命令下载redis: wget https://download.redis.io/releases/redis-6.2.6.tar.gz 2、解压redis: tar xzf redis-6.2.6.tar.gz 3、移动redis目录&a…

android之TextView自由选择复制

文章目录 前言一、效果图二、实现步骤1.OnSelectListener2.SelectionInfo类3.TextLayoutUtil类4.复制弹框的xml布局5.弹框背景Drawable6.倒三角Drawable7.复制工具类8.调用 总结 前言 根据时代进步,那些干产品的也叼砖起来了,今天就遇到一个需求&#x…

第一次汇报相关问题

深度学习现在已经学习到了Mini-Batch,early-stop等针对特定场景优化的算法了。 代码已经实现了一个L层的神经网络的构建了 论文看了一些综述 主要思考的两个方向:云计算和嵌入式 云计算:分布式机器学习、联邦学习、服务器负载均衡等 嵌入式&…

前端axios下载导出文件工具封装

使用示例: import { fileDownload } from /utils/fileDownloadfileDownload({ url: process.env.VUE_APP_BASE_URL /statistic/pageList/export, method: post, data: data })工具类: import store from ../store/index import {getAccessToken } fro…