神经网络 torch----使用GPU(cuda)

在训练过程中,要想利用我们的GPU,有两个基本要求。这些要求如下:
1、数据必须移到GPU上
2、网络必须移到GPU上。

默认情况下,在创建 PyTorch 张量或 PyTorch 神经网络模块时,会在 CPU 上初始化相应的数据。具体来说,这些数据存在于 CPU 的内存中。

如何用GPU训练神经网络模型

具体修改的位置包括下面3个地方:

  • 网络模型
  • 数据(输入、标注)
  • 损失函数
python 复制代码
import torch
import torchvision
from torch import nn
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
import time
 
 
train_data = torchvision.datasets.CIFAR10(root='./dataset', train=True, transform=torchvision.transforms.ToTensor(),
                                       download=True)
test_data = torchvision.datasets.CIFAR10(root='./dataset', train=False, transform=torchvision.transforms.ToTensor(),
                                       download=True)
 
train_data_size = len(train_data)
test_data_size = len(test_data)
# print("Train data size: ", train_data_size)
print('Train data size: {}'.format(train_data_size))
print('Test data size: {}'.format(test_data_size))
 
# 利用DataLoader 来加载数据集
train_dataloader = DataLoader(train_data, batch_size=64, shuffle=True)
test_dataloader = DataLoader(test_data, batch_size=64, shuffle=True)
 
# 搭建nn
class Tuduix(nn.Module):
    def __init__(self):
        super(Tuduix, self).__init__()
        self.module = nn.Sequential(
            nn.Conv2d(3, 32, 5, stride=1, padding=2),
            nn.MaxPool2d(2),
            nn.Conv2d(32, 32, 5, stride=1, padding=2),
            nn.MaxPool2d(2),
            nn.Conv2d(32, 64, 5, stride=1, padding=2),
            nn.MaxPool2d(2),
            nn.Flatten(),
            nn.Linear(64 * 4 * 4, 64),
            nn.Linear(64, 10)
        )
 
    def forward(self, x):
        y = self.module(x)
        return y
    
#创建网络模型
tudui = Tuduix()
if torch.cuda.is_available():
    tudui = tudui.cuda()
 
# 损失函数
loss_fn = nn.CrossEntropyLoss()
if torch.cuda.is_available():
    loss_fn = loss_fn.cuda()
 
# 优化器
learning_rate = 1e-2
optimizer = torch.optim.SGD(tudui.parameters(), lr=learning_rate)
 
# 设置训练网络的一些参数
# 记录训练的次数
total_train_step = 0
# 记录测试的次数
total_test_step = 0
# 训练的轮数
epoch = 10
 
# 添加tensorboard
writer = SummaryWriter('./logs')
 
# 计时
start_time = time.time()
 
for i in range(epoch):
    print('------------第{}轮训练-----------------'.format(i+1))
 
    # 训练步骤开始
    tudui.train()
    for data in train_dataloader:
        imgs, labels = data
        if torch.cuda.is_available():
            imgs, labels = imgs.cuda(), labels.cuda()
        outputs = tudui(imgs)
        loss = loss_fn(outputs, labels)
 
        # 优化器优化模型
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
 
        total_train_step += 1
        if total_train_step % 100 == 0:
            end_time = time.time()
            print(end_time - start_time)
            print('训练次数:{},Loss={}'.format(total_train_step, loss.item()))
            writer.add_scalar('train_loss', loss.item(), total_train_step)
 
    # 测试步骤开始
    tudui.eval()
    total_test_loss = 0
    total_accuracy = 0
    with torch.no_grad():
        for data in test_dataloader:
            imgs, labels = data
            if torch.cuda.is_available():
                imgs, labels = imgs.cuda(), labels.cuda()
            outputs = tudui(imgs)
            loss = loss_fn(outputs, labels)
            total_test_loss = total_test_loss + loss.item()
            accuracy = (outputs.argmax(1) == labels).sum()
            total_accuracy = total_accuracy + accuracy.item()
    print('整体测试集上的Loss:{}'.format(total_test_loss))
    print('整体测试集上的正确率:{}'.format(total_accuracy/test_data_size))
    writer.add_scalar('test_loss', total_test_loss, total_test_step)
    writer.add_scalar('test_accuracy', total_accuracy/test_data_size, total_test_step)
    total_test_step = total_test_step + 1
 
    torch.save(tudui, 'tuduix_gpu1{}.pth'.format(i))
    print('model has been saved.')
 
writer.close()
相关推荐
Elastic 中国社区官方博客7 分钟前
Elastic AI agent builder 介绍(三)
大数据·人工智能·elasticsearch·搜索引擎·ai·全文检索
小喵要摸鱼20 分钟前
【深度学习】超参数调整(Hyperparameter Tuning)
深度学习·超参数调整
这张生成的图像能检测吗37 分钟前
(论文速读)YOLA:学习照明不变特征的低光目标检测
图像处理·人工智能·目标检测·计算机视觉·低照度
ZPC82101 小时前
opencv 获取图像中物体的坐标值
人工智能·python·算法·机器人
亚里随笔1 小时前
AsyPPO_ 轻量级mini-critics如何提升大语言模型推理能力
人工智能·语言模型·自然语言处理·llm·agentic
coding_ksy1 小时前
基于启发式的多模态风险分布越狱攻击,针对多模态大型语言模型(ICCV 2025) - 论文阅读和解析
人工智能·语言模型
Louisejrkf1 小时前
U-net系列算法
深度学习
算家计算1 小时前
5年后手机和APP将成历史?马斯克最新预言背后:端云协同与AI操作系统的未来架构
人工智能·云计算·资讯
多恩Stone2 小时前
【3DV 进阶-5】3D生成中 Inductive Bias (归纳偏置)的技术路线图
人工智能·python·算法·3d·aigc