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

news2024/9/26 1:20:43

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 = 0
        total = 0
        for 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) * 100
        svm_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_estimators
        self.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

adaboost_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 = 0
        total = 0
        for 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) * 100
        adaboost_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_estimators
        self.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_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 = 0
        total = 0
        for 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) * 100
        bagging_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_estimators
        self.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_estimators
        self.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 = 0

    for 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 = 0
            total = 0
            for 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) * 100
            test_accuracies.append(accuracy)

            # 更新最佳准确率和最佳模型
            if accuracy > best_accuracy:
                best_accuracy = accuracy
                best_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.coloradmin.cn/o/1078937.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

计算机网络第三章——数据链路层(二)

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档 文章目录 3.4.2 停止等待协议为什么要有停止等待协议无差错情况有差错的情况 停等协议性能分析脑图时刻 3.4.3 后退n帧协议后退n帧协议中的滑动窗口GBN发送方必须响应的三件事…

智能晾衣架丨以科技解放双手

以往的晾衣架大多是平放式、手摇式居多,为衣物的晾晒提供了一个“栖身之所。”随着科技的日新月异,智能家居的产品越来越多。晾衣架也不例外,一款带有语音控制升降、同时具备照明和消毒的多功能衣架也已深入生活,正被人们所接受。…

算法题系列12·字符串判断子序列

目录 题目描述 实现 题目描述 给定字符串 s 和 t ,判断 s 是否为 t 的子序列。 字符串的一个子序列是原始字符串删除一些(也可以不删除)字符而不改变剩余字符相对位置形成的新字符串。(例如,"ace"是"…

RabbitMQ与springboot整合

1、基本概念 Server:接收客户端的连接,实现AMQP实体服务;Connection:连接,应用程序与Server的网络连接,TCP连接;Channel:信道,消息读写等操作在信道中进行。客户端可以建…

Python 图形化界面基础篇:发布应用程序到不同平台

Python 图形化界面基础篇:发布应用程序到不同平台 引言步骤1:准备应用程序1.1 处理依赖关系1.2 创建用户文档1.3 处理平台差异 步骤2:创建安装程序2.1 使用cx_Freeze创建独立包2.2 使用 PyInstaller 创建可执行文件2.3 使用其他工具 步骤3&am…

如何在 Spring Boot 中进行数据备份

在Spring Boot中进行数据备份 数据备份是确保数据安全性和可恢复性的关键任务之一。Spring Boot提供了多种方法来执行数据备份,无论是定期备份数据库,还是将数据导出到外部存储。本文将介绍在Spring Boot应用程序中进行数据备份的不同方法。 方法1: 使用…

CSS图文悬停翻转效果完整源码附注释

实现效果截图 HTML页面源码 <!DOCTYPE html> <html><head><meta http-equiv="content-type

正点原子嵌入式linux驱动开发——Linux内核移植

之前的两篇笔记&#xff0c;简单了解了一下Linux内核顶层 Makefile和Linux内核的启动流程&#xff0c;本篇内容来学习一下如何将ST官方提供的Linux内核移植到正点原子的STM32MP157开发板上。通过本章的学习&#xff0c;将掌握如何将半导体厂商提供的Linux BSP包移植到自己的平台…

【分享】小红书数据采集入excel表格

思路&#xff1a; 1. 打开小红书关键词页面 2. 循环指定次数&#xff0c;并鼠标往下滚 3. 获取元素列表&#xff0c;循环元素列表 4. 判断标题是否在list中&#xff0c;如果在就跳过&#xff0c;如果不在将标题存入list中 5. 点击元素&#xff0c;读取标题和内容&#xff…

LeetCode 1503. 所有蚂蚁掉下来前的最后一刻【脑筋急转弯】1618

本文属于「征服LeetCode」系列文章之一&#xff0c;这一系列正式开始于2021/08/12。由于LeetCode上部分题目有锁&#xff0c;本系列将至少持续到刷完所有无锁题之日为止&#xff1b;由于LeetCode还在不断地创建新题&#xff0c;本系列的终止日期可能是永远。在这一系列刷题文章…

2018架构真题案例(四十九)

某文件采用多级索引结构&#xff0c;磁盘大小4K字节&#xff0c;每个块号4字节&#xff0c;那么二级索引结果时&#xff0c;文件最大。 A、1024 B、1024*1024 C、2048*2048 D、4096*4096 答案&#xff1a;B 霍尔三维结构以时间堆、&#xff08;&#xff09;堆、知识堆组成…

vue踩坑

文章目录 1.error1 1.error1 在项目里面前端报这个错&#xff0c;有点蒙 确定了错误是在遍历数组中的图片部分 猜测可能是一开始的时候没有把photoList在form中写出来&#xff0c;form里面啥没有&#xff0c;导致渲染的时候有问题 所以以后在页面上渲染数据的都在data里…

网络-WebSocket

文章目录 前言一、WebSocket简介应用场景原理 二、使用心跳监测广播消息 三、群聊demo总结 前言 本文主要记录WebSocket的简单介绍和使用&#xff0c;完成群聊的demo 一、WebSocket简介 WebSocket是一种通信协议&#xff0c;它通过单个TCP连接提供全双工的通信通道。 它允许客…

【C#】标准WebService Soap1.1 兼容 ContentType: application/xml

一、问题描述 1.1 ESB平台要求 ContentType&#xff1a;application/xml Soap协议版本&#xff1a;1.1 1.2 提供的 WebService 接口 语言&#xff1a;C# 目标框架&#xff1a;.NetFramework 4.6.1 1.3 Postman 测试结果 HTTP Error 415.0 - Unsupported Media Type 服务器…

计算机竞赛YOLOv7 目标检测网络解读

文章目录 0 前言1 yolov7的整体结构2 关键点 - backbone关键点 - head3 训练4 使用效果5 最后 0 前言 世界变化太快&#xff0c;YOLOv6还没用熟YOLOv7就来了&#xff0c;如果有同学的毕设项目想用上最新的技术&#xff0c;不妨看看学长的这篇文章&#xff0c;学长带大家简单的…

如何为您的 Linux 服务器设置简单的 Grafana 云监控仪表板

Grafana 是一个开源可观察性平台,用于创建可视化数据集的仪表板。您可以使用它方便地监控服务器统计信息,例如 CPU 消耗、网络吞吐量和正常运行时间。 Grafana可以自托管,也可以通过官方Grafana Cloud实例作为 SaaS 解决方案进行访问。在本文中,您将了解如何设置 Grafana …

修炼k8s+flink+hdfs+dlink(四:k8s(一)概念)

一&#xff1a;概念 1. 概述 1.1 kubernetes对象. k8s对象包含俩个嵌套对象字段。 spec&#xff08;规约&#xff09;&#xff1a;期望状态 status&#xff08;状态&#xff09;&#xff1a;当前状态 当创建对象的时候&#xff0c;会按照spec的状态进行创建&#xff0c;如果…

scratch芝麻开门 2023年9月中国电子学会图形化编程 少儿编程 scratch编程等级考试一级真题和答案解析

目录 scratch芝麻开门 一、题目要求 1、准备工作 2、功能实现 二、案例分析

操作系统学习笔记3-同步互斥问题

文章目录 1 同步与互斥逻辑图2、并发性异步性独立性3、临界资源临界区4、同步与互斥 1 同步与互斥逻辑图 2、并发性异步性独立性 3、临界资源临界区 4、同步与互斥

汽车一键启动点火开关按键一键启动按钮型号规格

汽车点火开关/移动管家一键启动按键/汽车改装引擎启动按钮型号&#xff1a;YD828溥款开关 一键启动按钮&#xff08;适用于配套启动主机使用或原车一键启动开关更换&#xff09; 1.适合配套专用板板安装 2.开孔器开孔安装 3.原车钥匙位安装 外观&#xff1a;黑色 按钮上有3种不…