CIFAR10模型加载、保存及验证

文章目录

  • 前言
  • 一、保存加载模型
  • 二、模型训练和验证
    • 1.使用cuda进行训练
    • 2.训练测试集
  • 三、CIFAR10模型训练和验证
    • 1.模型
    • 2.模型训练
    • 3.模型测试


前言

前端时间写了使用pytorch训练了mnist数据集,今天写cifar10模型的训练整个过程步骤,同时对训练后的模型进行验证

一、保存加载模型

保存和加载模型pytorch官网上给出以下两种方法,官网推荐第二种方法。
1.保存模型的结构和模型的参数。对于自定义的模型,需要在加载模型时进行导入该模型。

#保存
torch.save(model,"mymodel.pth")
#读取
from test1 import mymodel #自定义模型需要进行导入模型
model = torch.load("mymodel.pth")

2.保存模型的参数。(更推荐使用这种方法来进行保存和加载,可以节省内存空间使用)

torch.save(model.state_dict(),"mymodel.pth")
model = torch.load()
#如果要加载网络模型结构:
from test1 import mymodel
model = mymodel()
model.load_state_dict(torch.load("model.pth"))

二、模型训练和验证

1.使用cuda进行训练

pytorch训练模型默认是采用cpu进行,但是训练时间太慢,采用cuda所花费的时间要比cpu短的多。首先查看一下自己的电脑是否可以进行cuda训练

print(torch.cuda.is_available())
#返回True就是可以进行

pytorch在使用cuda方法时对以下三个参数可以采用:
1.网络模型、2.数据(输入、标注)、3.损失函数
这里采用传统方法和一个简单方法:

#传统方法:
if torch.cuda.is_available():
	model = model.cuda()
if torch.cuda.is_available():
	loss_fn = loss_fn.cuda()
#传统方法每次使用时必须要检查计算机是否能使用cuda
#简单方法:使用三目表达式
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = model.to(device)
loss_fn = loss_fn.to(device)

注:如果模型采用cuda进行训练保存,则在进行模型验证时,输入的数据也要使用cuda


2.训练测试集

在测试集下通常要统计该模型在测试集下的loss值和准确率。统计loss值,只需要将每一步测试得到的loss值相加即可。对于求准确率,是将统计到正确的个数 / 测试样本总数,在这里求的样本准确是使用argmax()函数。该函数是求参数(集合)的函数,也就是求自变量最大的函数。举个测试模型例子:

output = model(image)
print(output)
#tensor([[ -5.6223, -12.9199,  -3.8796,  13.4408,   4.3184,  11.5109,   2.4625,
           5.6173,  -6.3050,  -5.1592]], device='cuda:0')
#argmax(1)返回结果为:数组中每一列最大值所在“行”索引值
print(output.argmax(1))
#tensor([3], device='cuda:0')

在训练模型时使用如下代码来获取该bath_size下准确的个数

accuracy =(output.argmax(1) == targets).sum()

训练测试集的通用模板如下:

total_test_loss = 0
total_test_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()
        imgs = imgs.to(device)
        targets = targets.to(device)
        output = model(imgs)
        loss = loss_fn(output, targets)
        total_test_loss += loss

        accuracy = (output.argmax(1) == targets).sum()
        total_test_accuracy += accuracy

print("整体测试集的loss:{}".format(total_test_loss))
print("整体测试集的正确率:{}".format(total_test_accuracy / test_data_len))

该处使用的url网络请求的数据。


三、CIFAR10模型训练和验证

1.模型

model.py:

import torch
from torch import nn


class mymodel(nn.Module):
    def __init__(self):
        super(mymodel, self).__init__()
        self.model1 = nn.Sequential(
            nn.Conv2d(in_channels=3, out_channels=32, kernel_size=5, stride=1, padding=2),
            nn.MaxPool2d(kernel_size=2),
            nn.Conv2d(in_channels=32, out_channels=32, kernel_size=5, stride=1, padding=2),
            nn.MaxPool2d(kernel_size=2),
            nn.Conv2d(in_channels=32, out_channels=64, kernel_size=5, stride=1, padding=2),
            nn.MaxPool2d(kernel_size=2),
            nn.Flatten(),
            nn.Linear(in_features=1024, out_features=64),
            nn.Linear(in_features=64, out_features=10)
        )

    def forward(self, input):
        outpuet = self.model1(input)
        return outpuet

2.模型训练

import time

import torch.optim
import torchvision.datasets
from torch import nn
from torch.utils.data import DataLoader

from model import mymodel

start = time.perf_counter()

train_data = torchvision.datasets.CIFAR10(root="data", train=True, transform=torchvision.transforms.ToTensor(),
                                          download=False)

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

train_dataloader = DataLoader(train_data, batch_size=64)
test_dataloader = DataLoader(test_data, batch_size=64)

train_data_len = train_data.__len__()
test_data_len = test_data.__len__()
print("训练集的长度:{},测试的长度为:{}".format(train_data_len, test_data_len))

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

model = mymodel()
# .cuda():网络模型、数据(输入、标注)、损失函数
# if torch.cuda.is_available():
#     model = model.cuda()
model = model.to(device)

loss_fn = nn.CrossEntropyLoss()
# if torch.cuda.is_available():
#     loss_fn = loss_fn.cuda()
loss_fn = loss_fn.to(device)

learning_rate = 2e-2
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)

epochs = 30

total_train_step, total_test_step = 0, 0
for epoch in range(epochs):
    print("-----------------第{}伦训练开始----------------".format(epoch))

    model.train()
    for data in train_dataloader:
        imgs, targets = data;
        # if torch.cuda.is_available():
        #     imgs = imgs.cuda()
        #     targets = targets.cuda()
        imgs = imgs.to(device)
        targets = targets.to(device)
        output = model(imgs)
        loss = loss_fn(output, targets)

        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

        total_train_step += 1
        if total_train_step % 100 == 0:
            print("第{}次训练,loss{},l_rate:{}".format(total_train_step, loss.item(), optimizer.param_groups[0]['lr']))

    model.eval()
    # 测试步骤,停止对梯度值的改变
    total_test_loss = 0
    total_test_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()
            imgs = imgs.to(device)
            targets = targets.to(device)
            output = model(imgs)

            loss = loss_fn(output, targets)
            total_test_loss += loss

            accuracy = (output.argmax(1) == targets).sum()
            total_test_accuracy += accuracy

    print("整体测试集的loss:{}".format(total_test_loss))
    print("整体测试集的正确率:{}".format(total_test_accuracy / test_data_len))

    if (epoch + 1) % epochs == 0:
        torch.save(model, "lrmymodel{}.pth".format(epoch))

end = time.perf_counter()
runTime = end - start
print("运行时间:", runTime)

3.模型测试

import cv2
import torch
import torchvision
from PIL import Image
from torch import nn
from torchvision.transforms import InterpolationMode

img_pil = Image.open("test_img/img.png")

image = img_pil.convert('RGB')
print(image)
transform = torchvision.transforms.Compose([
    torchvision.transforms.Resize((32, 32), interpolation=InterpolationMode.BICUBIC),
    torchvision.transforms.ToTensor()
])

image = transform(image)
image = image.cuda()
#模型使用cuda训练后,提交的数据集也得使用cuda


model = torch.load("lrmymodel29.pth")
print(model)

image = torch.reshape(image, (1, 3, 32, 32))
model.eval()
with torch.no_grad():
    output = model(image)
    print(output)
    print(output.argmax(1))

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