Day 34

 GPU训练
要让模型在 GPU 上训练,主要是将模型和数据迁移到 GPU 设备上。

在 PyTorch 里,.to(device) 方法的作用是把张量或者模型转移到指定的计算设备(像 CPU 或者 GPU)上。

对于张量(Tensor):调用 .to(device) 之后,会返回一个在新设备上的新张量。
对于模型(nn.Module):调用 .to(device) 会直接对模型进行修改,让其所有参数和缓冲区都移到新设备上。在进行计算时,所有输入张量和模型必须处于同一个设备。要是它们不在同一设备上,就会引发运行时错误。并非所有 PyTorch 对象都有 .to(device) 方法,只有继承自 torch.nn.Module 的模型以及 torch.Tensor 对象才有此方法。
RuntimeError: Tensor for argument #1 'input' is on CPU, but expected it to be on GPU 这个常见错误就是输入张量和模型处于不同的设备。

import torchif torch.cuda.is_available():print("CUDA可用!")device_count = torch.cuda.device_count()print(f"可用的CUDA设备数量: {device_count}")current_device = torch.cuda.current_device()print(f"当前使用的CUDA设备索引: {current_device}")device_name = torch.cuda.get_device_name(current_device)print(f"当前CUDA设备的名称: {device_name}")cuda_version = torch.version.cudaprint(f"CUDA版本: {cuda_version}")print("cuDNN版本:", torch.backends.cudnn.version())else:print("CUDA不可用。")iris = load_iris()
X = iris.data 
y = iris.target  
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)X_train = torch.FloatTensor(X_train).to(device)
y_train = torch.LongTensor(y_train).to(device)
X_test = torch.FloatTensor(X_test).to(device)
y_test = torch.LongTensor(y_test).to(device)class MLP(nn.Module):def __init__(self):super(MLP, self).__init__()self.fc1 = nn.Linear(4, 10)self.relu = nn.ReLU()self.fc2 = nn.Linear(10, 3)def forward(self, x):out = self.fc1(x)out = self.relu(out)out = self.fc2(out)return outmodel = MLP().to(device)criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=0.01)num_epochs = 20000
losses = []
start_time = time.time()for epoch in range(num_epochs):outputs = model(X_train)loss = criterion(outputs, y_train)optimizer.zero_grad()loss.backward()optimizer.step()losses.append(loss.item())if (epoch + 1) % 100 == 0:print(f'Epoch [{epoch+1}/{num_epochs}], Loss: {loss.item():.4f}')time_all = time.time() - start_time
print(f'Training time: {time_all:.2f} seconds')plt.plot(range(num_epochs), losses)
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.title('Training Loss over Epochs')
plt.show()

能够优化的只有数据传输时间,针对性解决即可,很容易想到2个思路:
1. 直接不打印训练过程的loss了,但是这样会没办法记录最后的可视化图片,只能肉眼观察loss数值变化。
2. 每隔200个epoch保存一下loss,不需要20000个epoch每次都打印,

下面先尝试第一个思路:

import torch
import torch.nn as nn
import torch.optim as optim
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
import numpy as npiris = load_iris()
X = iris.data 
y = iris.target  
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)X_train = torch.FloatTensor(X_train)
y_train = torch.LongTensor(y_train)
X_test = torch.FloatTensor(X_test)
y_test = torch.LongTensor(y_test)class MLP(nn.Module): def __init__(self): super(MLP, self).__init__() self.fc1 = nn.Linear(4, 10)  self.relu = nn.ReLU()self.fc2 = nn.Linear(10, 3)  def forward(self, x):out = self.fc1(x)out = self.relu(out)out = self.fc2(out)return outmodel = MLP()criterion = nn.CrossEntropyLoss()optimizer = optim.SGD(model.parameters(), lr=0.01)num_epochs = 20000 losses = []import time
start_time = time.time() for epoch in range(num_epochs): outputs = model.forward(X_train)  # outputs = model(X_train) loss = criterion(outputs, y_train) optimizer.zero_grad() loss.backward(optimizer.step() if (epoch + 1) % 100 == 0:print(f'Epoch [{epoch+1}/{num_epochs}], Loss: {loss.item():.4f}')time_all = time.time() - start_time
print(f'Training time: {time_all:.2f} seconds')

优化后发现确实效果好,近乎和用cpu训练的时长差不多。所以可以理解为数据从gpu到cpu的传输占用了大量时间。

下面尝试下第二个思路:

import torch
import torch.nn as nn
import torch.optim as optim
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
import time
import matplotlib.pyplot as pltdevice = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
print(f"使用设备: {device}")iris = load_iris()
X = iris.data 、
y = iris.target 、X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)scaler = MinMaxScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)X_train = torch.FloatTensor(X_train).to(device)
y_train = torch.LongTensor(y_train).to(device)
X_test = torch.FloatTensor(X_test).to(device)
y_test = torch.LongTensor(y_test).to(device)class MLP(nn.Module):def __init__(self):super(MLP, self).__init__()self.fc1 = nn.Linear(4, 10)  self.relu = nn.ReLU()self.fc2 = nn.Linear(10, 3) def forward(self, x):out = self.fc1(x)out = self.relu(out)out = self.fc2(out)return outmodel = MLP().to(device)criterion = nn.CrossEntropyLoss()、
optimizer = optim.SGD(model.parameters(), lr=0.01)num_epochs = 20000 、losses = []start_time = time.time() 、for epoch in range(num_epochs):outputs = model(X_train)  、loss = criterion(outputs, y_train)optimizer.zero_grad()loss.backward()optimizer.step()if (epoch + 1) % 200 == 0:losses.append(loss.item()) # item()方法返回一个Python数值,loss是一个标量张量print(f'Epoch [{epoch+1}/{num_epochs}], Loss: {loss.item():.4f}')if (epoch + 1) % 100 == 0:print(f'Epoch [{epoch+1}/{num_epochs}], Loss: {loss.item():.4f}')time_all = time.time() - start_time  、
print(f'Training time: {time_all:.2f} seconds')plt.plot(range(len(losses)), losses)
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.title('Training Loss over Epochs')
plt.show()

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

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

相关文章

C++笔试题(金山科技新未来训练营):

题目分布: 17道单选(每题3分)3道多选题(全对3分,部分对1分)2道编程题(每一道20分)。 不过题目太多,就记得一部分了: 单选题: static变量的初始…

Spark(29)基础自定义分区器

(一)什么是分区 【复习提问:RDD的定义是什么?】 在 Spark 里,弹性分布式数据集(RDD)是核心的数据抽象,它是不可变的、可分区的、里面的元素并行计算的集合。 在 Spark 中&#xf…

python打卡训练营打卡记录day35

知识点回顾: 三种不同的模型可视化方法:推荐torchinfo打印summary权重分布可视化进度条功能:手动和自动写法,让打印结果更加美观推理的写法:评估模式 作业:调整模型定义时的超参数,对比下效果 1…

【MySQL】07.表内容的操作

1. insert 我们先创建一个表结构,这部分操作我们使用这张表完成我们的操作: mysql> create table student(-> id int primary key auto_increment,-> name varchar(20) not null,-> qq varchar(20) unique-> ); Query OK, 0 rows affec…

使用SQLite Expert个人版VACUUM功能修复数据库

使用SQLite Expert个人版VACUUM功能修复数据库 一、SQLite Expert工具简介 SQLite Expert 是一款功能强大的SQLite数据库管理工具,分为免费的个人版(Personal Edition)和收费的专业版(Professional Edition)。其核心功…

LM-BFF——语言模型微调新范式

gpt3(GPT3——少样本示例推动下的通用语言模型雏形)结合提示词和少样本示例后,展示出了强大性能。但大语言模型的训练门槛太高,普通研究人员无力,LM-BFF(Making Pre-trained Language Models Better Few-shot Learners)的作者受gp…

遥感解译项目Land-Cover-Semantic-Segmentation-PyTorch之二训练模型

遥感解译项目Land-Cover-Semantic-Segmentation-PyTorch之一推理模型 背景 上一篇文章了解了这个项目的环境安装和模型推理,这篇文章介绍下如何训练这个模型,添加类别 下载数据集 在之前的一篇文章中,也有用到这个数据集 QGIS之三十六Deepness插件实现AI遥感训练模型 数…

【NLP 71、常见大模型的模型结构对比】

三到五年的深耕,足够让你成为一个你想成为的人 —— 25.5.8 模型名称位置编码Transformer结构多头机制Feed Forward层设计归一化层设计线性层偏置项激活函数训练数据规模及来源参数量应用场景侧重GPT-5 (OpenAI)RoPE动态相对编码混合专家架构(MoE&#…

[250521] DBeaver 25.0.5 发布:SQL 编辑器、导航器全面升级,新增 Kingbase 支持!

目录 DBeaver 25.0.5 发布:SQL 编辑器、导航器全面升级,新增 Kingbase 支持! DBeaver 25.0.5 发布:SQL 编辑器、导航器全面升级,新增 Kingbase 支持! 近日,DBeaver 发布了 25.0.5 版本&#xf…

服务器硬盘虚拟卷的处理

目前的情况是需要删除逻辑卷,然后再重新来弄一遍。 数据已经备份好了,所以不用担心数据会丢失。 查看服务器的具体情况 使用 vgdisplay 操作查看服务器的卷组情况: --- Volume group ---VG Name vg01System IDFormat …

Flutter 中 build 方法为何写在 StatefulWidget 的 State 类中

Flutter 中 build 方法为何写在 StatefulWidget 的 State 类中 在 Flutter 中,build 方法被设计在 StatefulWidget 的 State 类中而非 StatefulWidget 类本身,这种设计基于几个重要的架构原则和实际考量: 1. 核心设计原因 1.1 生命周期管理…

传统医疗系统文档集中标准化存储和AI智能化更新路径分析

引言 随着医疗数智化建设的深入推进,传统医疗系统如医院信息系统(HIS)、临床信息系统(CIS)、护理信息系统(NIS)、影像归档与通信系统(PACS)和实验室信息系统(LIS)已经成为了现代医疗机构不可或缺的技术基础设施。这些系统各自承担着不同的功能,共同支撑…

探索常识性概念图谱:构建智能生活的知识桥梁

目录 一、知识图谱背景介绍 (一)基本背景 (二)与NLP的关系 (三)常识性概念图谱的引入对比 二、常识性概念图谱介绍 (一)常识性概念图谱关系图示例 (二&#xff09…

Linux/aarch64架构下安装Python的Orekit开发环境

1.背景 国产化趋势越来越强,从软件到硬件,从操作系统到CPU,甚至显卡,就产生了在国产ARM CPU和Kylin系统下部署Orekit的需求,且之前的开发是基于Python的,需要做适配。 2.X86架构下安装Python/Orekit开发环…

Ctrl+鼠标滚动阻止页面放大/缩小

项目场景: 提示:这里简述项目相关背景: 一般在我们做大屏的时候,不希望Ctrl鼠标上下滚动的时候页面会放大/缩小,那么在有时候,又不希望影响到别的页面,比如说这个大屏是在另一个管理后台中&am…

MySQL——复合查询表的内外连

目录 复合查询 回顾基本查询 多表查询 自连接 子查询 where 字句中使用子查询 单行子查询 多行子查询 多列子查询 from 字句中使用子查询 合并查询 实战OJ 查找所有员工入职时候的薪水情况 获取所有非manager的员工emp_no 获取所有员工当前的manager 表的内外…

聊一下CSS中的标准流,浮动流,文本流,文档流

在网络上关于CSS的文章中,有时候能听到“标准流”,“浮动流”,“定位流”等等词语,还有像“文档流”,“文本流”等词,这些流是什么意思?它们是CSS中的一些布局方案和特性。今天我们就来聊一下CS…

python训练营第33天

MLP神经网络的训练 知识点回顾: PyTorch和cuda的安装查看显卡信息的命令行命令(cmd中使用)cuda的检查简单神经网络的流程 数据预处理(归一化、转换成张量)模型的定义 继承nn.Module类定义每一个层定义前向传播流程 定义…

JDK21深度解密 Day 1:JDK21全景图:关键特性与升级价值

【JDK21深度解密 Day 1】JDK21全景图:关键特性与升级价值 引言 欢迎来到《JDK21深度解密:从新特性到生产实践的全栈指南》系列的第一天。今天我们将探讨JDK21的关键特性和升级价值。作为近5年最重要的LTS版本,JDK21不仅带来了性能上的巨大突…

[docker]更新容器中镜像版本

从peccore-dev仓库拉取镜像 docker pull 10.12.135.238:8060/peccore-dev/configserver:v1.13.45如果报错,请参考docker拉取镜像失败,添加仓库地址 修改/etc/CET/Common/peccore-docker-compose.yml文件中容器的版本,为刚刚拉取的版本 # 配置中心confi…