pytorch使用cuda,调用GPU进行训练

文章介绍了如何在PyTorch中利用CUDA进行GPU训练,包括检查CUDA可用性,将模型、数据和损失函数移到GPU上,以及提供了一个使用CNN训练CIFAR10数据集的示例。通过.to(device)或.cuda()方法可以在GPU和CPU间迁移模型。
部署运行你感兴趣的模型镜像

pytorch使用cuda,调用GPU进行训练

Pytorch允许把在GPU上训练的模型加载到CPU上,也允许把在CPU上训练的模型加载到GPU上。

首先需要判断自己的pytorch是否能够使用GPU计算:

print(torch.cuda.is_available())

如果输出False的话,要重新配置cuda环境,这里就不仔细说明了。

然后,明确什么东西可以使用GPU训练,一般来说包括网络模型、数据(输入、标注)、损失函数,主要有以下两种方法:

方法1:使用.to(device)方法

device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
net.to(device)
inputs, labels = inputs.to(device), labels.to(device)
loss_fn = loss_fn.to(device)

方法2:使用.cuda()方法

if torch.cuda.is_available():
	net.cuda()
if torch.cuda.is_available():
	inputs, labels = inputs.cuda(), labels.cuda()
if torch.cuda.is_available():
	loss_fn = loss_fn.cuda()

使用方法2调用cuda进行训练的一个案例,方法1同理。

import time

import torch
import torchvision.datasets
from torch import nn
from torch.nn import Sequential, Conv2d, MaxPool2d, Flatten, Linear
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter

# from model import *

# 准备数据集
train_data = torchvision.datasets.CIFAR10("./dataset_cifar10/train", train=True,
                                          transform=torchvision.transforms.ToTensor(),
                                          download=True)
test_data = torchvision.datasets.CIFAR10("./dataset_cifar10/test", train=False,
                                         transform=torchvision.transforms.ToTensor(),
                                         download=True)

# 利用DataLoader加载数据集
train_dataloader = DataLoader(train_data, batch_size=64)
test_dataloader = DataLoader(test_data, batch_size=64)


# 创建网络模型
class Lyon(nn.Module):

    def __init__(self):
        super(Lyon, self).__init__()
        self.model1 = Sequential(
            Conv2d(3, 32, 5, padding=2),
            MaxPool2d(2),
            Conv2d(32, 32, 5, padding=2),
            MaxPool2d(2),
            Conv2d(32, 64, 5, padding=2),
            MaxPool2d(2),
            Flatten(),
            Linear(1024, 64),
            Linear(64, 10)
        )

    def forward(self, x):
        x = self.model1(x)
        return x


lyon = Lyon()
if torch.cuda.is_available():
    lyon = lyon.cuda()

# 损失函数
loss_fn = nn.CrossEntropyLoss()
if torch.cuda.is_available():
    loss_fn = loss_fn.cuda()

# 优化器
learning_rate = 0.01
optimizer = torch.optim.SGD(lyon.parameters(), lr=learning_rate)

# 设置训练网络的一些参数
# 记录训练次数
total_train_step = 0
# 记录训练次数
total_test_step = 0
# 训练轮数
epoch = 10

# 添加tensorboard
writer = SummaryWriter("./logs/train")

start_time = time.time()
for i in range(epoch):
    print("----- 第 {} 轮训练开始 -----".format(i + 1))
    # 训练步骤开始
    lyon.train()  # 可以不写
    for data in train_dataloader:
        imgs, targets = data
        if torch.cuda.is_available():
            imgs = imgs.cuda()
            targets = targets.cuda()
        output = lyon(imgs)
        loss = loss_fn(output, targets)

        # 优化器优化模型
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

        total_train_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))
            writer.add_scalar("train_loss", loss.item(), total_train_step)

    # 测试步骤开始
    lyon.eval()  # 评估步骤开始,可以不写
    total_test_loss = 0
    total_accuracy = 0
    with torch.no_grad():
        for data in test_dataloader:
            imgs, targets = data
            if torch.cuda.is_available():
                imgs = imgs.cuda()
                targets = targets.cuda()
            outputs = lyon(imgs)
            loss = loss_fn(outputs, targets)
            accuracy = (outputs.argmax(1) == targets).sum()  # outputs.argmax(1)将输出结果转换为targets的模式
            total_test_loss = total_test_loss + loss.item()
            total_accuracy = total_accuracy + accuracy

    print("整体测试集上的Loss:{}".format(total_test_loss))
    print("整体测试集上的正确率:{}".format(total_accuracy))
    writer.add_scalar("test_loss", total_test_loss, total_test_step)
    total_test_step = total_test_step + 1

    torch.save(lyon, "./train_model/lyon_{}.pth".format(i))
    # 官方推荐模型保存方式
    # torch.save(lyon.state_dict(), "./lyon_{}.pth".format(i))
    print("模型已保存!")

writer.close()

您可能感兴趣的与本文相关的镜像

PyTorch 2.5

PyTorch 2.5

PyTorch
Cuda

PyTorch 是一个开源的 Python 机器学习库,基于 Torch 库,底层由 C++ 实现,应用于人工智能领域,如计算机视觉和自然语言处理

设置使用CUDA进行训练,需要在以下三个地方进行修改,以告诉计算机使用的是CUDA,并且有两种方式实现: ### 方式一:使用`.cuda()`方法 ```python import torch import torch.nn as nn # 定义一个简单的网络结构 class SimpleNet(nn.Module): def __init__(self): super(SimpleNet, self).__init__() self.fc = nn.Linear(10, 1) def forward(self, x): return self.fc(x) # 1. 网络结构 model = SimpleNet() model.cuda() # 2. 损失函数 criterion = nn.MSELoss() criterion.cuda() # 模拟数据 data = torch.randn(5, 10) target = torch.randn(5, 1) # 3. 数据马上使用之前 data = data.cuda() target = target.cuda() # 前向传播 output = model(data) loss = criterion(output, target) ``` ### 方式二:使用`.to(device)`方法 ```python import torch import torch.nn as nn # 检查CUDA是否可用 device = torch.device("cuda" if torch.cuda.is_available() else "cpu") # 定义一个简单的网络结构 class SimpleNet(nn.Module): def __init__(self): super(SimpleNet, self).__init__() self.fc = nn.Linear(10, 1) def forward(self, x): return self.fc(x) # 1. 网络结构 model = SimpleNet() model.to(device) # 2. 损失函数 criterion = nn.MSELoss() criterion.to(device) # 模拟数据 data = torch.randn(5, 10) target = torch.randn(5, 1) # 3. 数据马上使用之前 data = data.to(device) target = target.to(device) # 前向传播 output = model(data) loss = criterion(output, target) ``` 使用GPU训练模型时,需要同时对模型、数据、损失函数同时指定使用GPU模型,否则就会存在运行问题[^1][^2]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值