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

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

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

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

  • 网络模型
  • 数据(输入、标注)
  • 损失函数
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()

Logo

欢迎来到由智源人工智能研究院发起的Triton中文社区,这里是一个汇聚了AI开发者、数据科学家、机器学习爱好者以及业界专家的活力平台。我们致力于成为业内领先的Triton技术交流与应用分享的殿堂,为推动人工智能技术的普及与深化应用贡献力量。

更多推荐