小土堆pytorch学习笔记(二十一、完整的模型测试套路)

一、

利用已经训练好的模型,然后给他提供输入。
打开google colab,创建笔记本,运行如下代码:

import time

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

# from model import *

# 定义训练的设备
device = torch.device("cuda")
# 准备数据集
train_data = torchvision.datasets.CIFAR10("./dataset", train=True, transform=torchvision.transforms.ToTensor(),
                                          download=True)
test_data = torchvision.datasets.CIFAR10("./dataset", train=False, transform=torchvision.transforms.ToTensor(),
                                         download=True)

# 查看训练集和验证集的长度
train_data_size = len(train_data)
test_data_size = len(test_data)
print("训练数据集的长度为:{}".format(train_data_size))
print("测试数据集的长度为:{}".format(test_data_size))

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


# 创建网络模型
class Cow(nn.Module):
    def __init__(self):
        super(Cow, 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


cow = Cow()
cow.to(device)

# 损失函数,使用交叉熵损失函数
loss_fn = nn.CrossEntropyLoss()
loss_fn.to(device)
# 优化器
# 1e-3 = 1 x 10^(-3) = 0.001
learning_rate = 1e-3
optimizer = torch.optim.SGD(cow.parameters(), lr=learning_rate)

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

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

start_time = time.time()
for i in range(epoch):
    print("------第{}轮训练开始".format(i + 1))

    # 训练步骤开始
    cow.train()
    for data in train_dataloader:
        imgs, targets = data
        imgs = imgs.to(device)
        targets = targets.to(device)
        outputs = cow(imgs)
        loss = loss_fn(outputs, targets)

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

        total_train_step = total_train_step + 1
        # 设置100次步骤才打印一次,方便查看测试集损失
        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)

    # 测试步骤开始
    # 测试步骤不需要调优,所以使用with torch.no_grad()函数
    cow.eval()
    total_test_loss = 0
    total_accuracy = 0
    with torch.no_grad():
        for data in test_dataloader:
            imgs, targets = data
            imgs = imgs.to(device)
            targets = targets.to(device)
            outputs = cow(imgs)
            loss = loss_fn(outputs, targets)
            total_test_loss = total_test_loss + loss.item()
            accuracy = (outputs.argmax(1) == targets).sum()
            total_accuracy = total_accuracy + accuracy
    print("整体测试集上的Loss:{}".format(total_test_loss))
    print("整体测试集上的Loss:{}".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(cow, "cow_{}_gpu.pth".format(i))
    # 保存方式2 torch.save(cow.state_dict(), "cow_{}.pth".format(i))
    print("模型已保存")
writer.close()

运行结果,保存了30个世代训练好的模型,将损失值最小的一个下载下来,然后在测试代码中加载,再进行输入,查看预测输出值,是否与targets一致。分别输入狗和飞机的图片后,只有飞机的图片识别成功了。
下面是测试代码:

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

image_path = "./imgs/airplane.png"
image = Image.open(image_path)
print(image)
# 图片是PNG格式,PNG格式是4通道,除了RGB三通道外,还有一个透明度通道,所以调用下面这个函数保留其颜色通道。如果图片本来就是三个颜色通道,经过此操作,不变。
# 加上这一步后,可以适应png,jpg各种格式的图片。
image = image.convert('RGB')

transform = torchvision.transforms.Compose([torchvision.transforms.Resize((32, 32)), torchvision.transforms.ToTensor()])
image = transform(image)
# 不这么做的话会报错,因为之前训练的模型是使用gpu训练的,则输入的数据也要是在gpu上训练过的数据,则需要调用.cuda()函数
image = image.cuda()
print(image.shape)


class Cow(nn.Module):
    def __init__(self):
        super(Cow, 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

# 博主是将训练的模型映射到cpu上,这样输入的数据是cpu类型的,模型也是,就能做出预测,而我使用的是将image转换为gpu类型的,调用cuda()
# 博主做法:model = torch.load("cow_29_gpu.pth", map_location=torch.device('cpu'))
model = torch.load("cow_29_gpu.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))

测试飞机的运行结果:

<PIL.PngImagePlugin.PngImageFile image mode=RGBA size=435x254 at 0x2903D13BE50>
torch.Size([3, 32, 32])
Cow(
  (model): Sequential(
    (0): Conv2d(3, 32, kernel_size=(5, 5), stride=(1, 1), padding=(2, 2))
    (1): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
    (2): Conv2d(32, 32, kernel_size=(5, 5), stride=(1, 1), padding=(2, 2))
    (3): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
    (4): Conv2d(32, 64, kernel_size=(5, 5), stride=(1, 1), padding=(2, 2))
    (5): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
    (6): Flatten(start_dim=1, end_dim=-1)
    (7): Linear(in_features=1024, out_features=64, bias=True)
    (8): Linear(in_features=64, out_features=10, bias=True)
  )
)
tensor([[ 5.3422,  2.1384, -0.6086, -2.3171, -0.8421, -2.1335, -3.5489, -1.7529,
          3.6529, -0.1847]], device='cuda:0')
tensor([0], device='cuda:0')
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值