pytorch完整模型训练套路

文章目录

  • CIFAR10数据集简介
  • 训练模型套路
    • 1、准备数据集
    • 2、加载数据集
    • 3、搭建神经网络
    • 4、创建网络模型、定义损失函数、优化器
    • 5、训练网络
    • 6、测试数据集
    • 7、添加tensorboard
    • 8、转化为正确率
    • 9、保存模型
  • 完整代码

本文以 CIFAR10数据集为例,介绍一个完整的模型训练套路。

CIFAR10数据集简介

CIFAR-10数据集包含60000张32x32彩色图像,分为10个类,每类6000张。有50000张训练图片和10000张测试图片。

数据集分为五个训练batches和一个测试batch,每个batch有10000张图像。测试batch包含从每个类中随机选择的1000个图像。训练batches以随机顺序包含剩余的图像,但有些训练batches可能包含一个类的图像多于另一个类的图像。在它们之间,训练batches包含来自每个类的5000张图像。

下面是数据集中的类,以及每个类的10张随机图片:
pytorch完整模型训练套路_第1张图片

一共包含10 个类别的RGB 彩色图片:飞机( airplane )、汽车( automobile )、鸟类( bird )、猫( cat )、鹿( deer )、狗( dog )、蛙类( frog )、马( horse )、船( ship )和卡车( truck )。

训练模型套路

1、准备数据集

# 准备数据集
train_data = torchvision.datasets.CIFAR10(root="./source", train=True, transform=torchvision.transforms.ToTensor(), download=True)

test_data = torchvision.datasets.CIFAR10(root="./source", train=False, transform=torchvision.transforms.ToTensor(), download=True)
# length 长度
train_data_size = len(train_data)
test_data_size = len(test_data)
print(f"训练数据集的长度为:{train_data_size}")
print(f"测试数据集的长度为:{test_data_size}")

pytorch完整模型训练套路_第2张图片

2、加载数据集

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

3、搭建神经网络

我们准备搭建一个这样的网络模型结构:

pytorch完整模型训练套路_第3张图片

# 搭建神经网络
class Aniu(nn.Module):
    def __init__(self):
        super(Aniu, self).__init__()
        self.model = nn.Sequential(
            nn.Conv2d(3, 32, 5, 1, 2),
            nn.MaxPool2d(2),
            nn.Conv2d(32, 32, 5, 1, 2),
            nn.MaxPool2d(2),
            nn.Conv2d(32, 64, 5, 1, 2),
            nn.MaxPool2d(2),
            nn.Flatten(),
            nn.Linear(64 * 4 * 4, 64),
            nn.Linear(64, 10)
        )

    def forward(self, x):
        x = self.model(x)
        return x
if __name__ == '__main__':
    aniu = Aniu()
    input = torch.ones((64, 3, 32, 32))
    output = aniu(input)
    print(output.shape)

我们在一个新的文件下搭建并简单测试神经网络。

4、创建网络模型、定义损失函数、优化器

# 创建网络模型
aniu = Aniu()
# 损失函数
loss_fn = nn.CrossEntropyLoss()
# 优化器
learning_rate = 1e-2
optimizer = torch.optim.SGD(aniu.parameters(), lr=learning_rate)

5、训练网络

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

for i in range(epoch):
    print(f"----------第{i+1}轮训练开始-----------")

    # 训练开始
    for data in train_dataloader:
        imgs, targets = data
        output = aniu(imgs)
        loss = loss_fn(output, targets)

        # 优化器优化模型
        optimizer.zero_grad() # 优化器梯度清零
        loss.backward()
        optimizer.step()

        total_train_step = total_train_step + 1
        print(f"训练次数:{total_train_step},loss:{loss.item()}") # .item()可以将tensor数据类型转化

6、测试数据集

我们可以通过with torch.mo_grad():来测试

for i in range(epoch):
    print(f"----------第{i+1}轮训练开始-----------")

    # 训练开始
    for data in train_dataloader:
        imgs, targets = data
        output = aniu(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:
            print(f"训练次数:{total_train_step},loss:{loss.item()}") # .item()可以将tensor数据类型转化

    # 测试步骤开始
    total_test_loss = 0
    with torch.no_grad():
        for data in test_dataloader:
            imgs, targets = data
            output = aniu(imgs)
            loss = loss_fn(output, targets)
            total_test_loss = total_test_loss + loss.item()
    print(f"整体测试集上的Loss:{total_test_loss}")

pytorch完整模型训练套路_第4张图片

7、添加tensorboard

我们在以上的代码基础上添加tensorboard,并通过tensorboard画图进行观察:

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

for i in range(epoch):
    print(f"----------第{i+1}轮训练开始-----------")

    # 训练开始
    for data in train_dataloader:
        imgs, targets = data
        output = aniu(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:
            print(f"训练次数:{total_train_step},loss:{loss.item()}") # .item()可以将tensor数据类型转化
            writer.add_scalar("train_loss", loss.item(), total_train_step)

    # 测试步骤开始
    total_test_loss = 0
    with torch.no_grad():
        for data in test_dataloader:
            imgs, targets = data
            output = aniu(imgs)
            loss = loss_fn(output, targets)
            total_test_loss = total_test_loss + loss.item()
    print(f"整体测试集上的Loss:{total_test_loss}")
    writer.add_scalar("test_loss", total_test_loss, total_test_step)
    total_test_step = total_test_step + 1

writer.close()

运行并在终端输入:

tensorboard --logdir="log_train"

可以观察到图像:

pytorch完整模型训练套路_第5张图片

8、转化为正确率

添加一段代码,算出测试集上的正确率:

# 整体正确的个数
total_accuracy = 0

with torch.no_grad():
    for data in test_dataloader:
        imgs, targets = data
        output = aniu(imgs)
        loss = loss_fn(output, targets)
        total_test_loss = total_test_loss + loss.item()
        accuracy = (output.argmax(1) == targets).sum()
        total_accuracy = total_accuracy + accuracy
print(f"整体测试集上的Loss:{total_test_loss}")
print(f"整体测试集上的正确率:{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

9、保存模型

每轮保存一下模型:

torch.save(aniu, f"aniu_{i}.pth")
print("模型已保存")

完整代码

train.py文件:

import torch.cuda
import torchvision
from torch import nn
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter

from model import *
# 准备数据集
train_data = torchvision.datasets.CIFAR10(root="./source", train=True,
                                          transform=torchvision.transforms.ToTensor(), download=True)

test_data = torchvision.datasets.CIFAR10(root="./source", train=False,
                                          transform=torchvision.transforms.ToTensor(), download=True)

# length 长度
train_data_size = len(train_data)
test_data_size = len(test_data)
print(f"训练数据集的长度为:{train_data_size}")
print(f"测试数据集的长度为:{test_data_size}")

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

# 创建网络模型 搭建神经网络
class Aniu(nn.Module):
    def __init__(self):
        super(Aniu, self).__init__()
        self.model = nn.Sequential(
            nn.Conv2d(3, 32, 5, 1, 2),
            nn.MaxPool2d(2),
            nn.Conv2d(32, 32, 5, 1, 2),
            nn.MaxPool2d(2),
            nn.Conv2d(32, 64, 5, 1, 2),
            nn.MaxPool2d(2),
            nn.Flatten(),
            nn.Linear(64 * 4 * 4, 64),
            nn.Linear(64, 10)
        )

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

aniu = Aniu()
# if torch.cuda.is_available():
#     aniu = aniu.cuda()


# 损失函数
loss_fn = nn.CrossEntropyLoss()
# if torch.cuda.is_available():
#     loss_fn = loss_fn.cuda()
# 优化器
learning_rate = 1e-2
optimizer = torch.optim.SGD(aniu.parameters(), lr=learning_rate)

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


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

for i in range(epoch):
    print(f"----------第{i+1}轮训练开始-----------")

    # 训练开始
    aniu.train()
    for data in train_dataloader:
        imgs, targets = data
        # if torch.cuda.is_available():
        #     imgs = imgs.cuda()
        #     targets = targets.cuda()
        output = aniu(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:
            print(f"训练次数:{total_train_step},loss:{loss.item()}") # .item()可以将tensor数据类型转化
            writer.add_scalar("train_loss", loss.item(), total_train_step)


    # 测试步骤开始
    aniu.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()
            output = aniu(imgs)
            loss = loss_fn(output, targets)
            total_test_loss = total_test_loss + loss.item()
            accuracy = (output.argmax(1) == targets).sum()
            total_accuracy = total_accuracy + accuracy
    print(f"整体测试集上的Loss:{total_test_loss}")
    print(f"整体测试集上的正确率:{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(aniu.state_dict(), f"aniu_{}.pth") 官方推荐保存方式
    torch.save(aniu, f"aniu_{i}.pth")
    print("模型已保存")

writer.close()

model.py:

import torch
from torch import nn
# 搭建神经网络
class Aniu(nn.Module):
    def __init__(self):
        super(Aniu, self).__init__()
        self.model = nn.Sequential(
            nn.Conv2d(3, 32, 5, 1, 2),
            nn.MaxPool2d(2),
            nn.Conv2d(32, 32, 5, 1, 2),
            nn.MaxPool2d(2),
            nn.Conv2d(32, 64, 5, 1, 2),
            nn.MaxPool2d(2),
            nn.Flatten(),
            nn.Linear(64 * 4 * 4, 64),
            nn.Linear(64, 10)
        )

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

if __name__ == '__main__':
    aniu = Aniu()
    input = torch.ones((64, 3, 32, 32))
    output = aniu(input)
    print(output.shape)

你可能感兴趣的:(pytorch,深度学习,python)