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

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,深度学习,python)