22.1 验证过程
利用已训练好的模型,提供输入,查看输出。
22.1.1 代码实现
选择验证笔记 21.1.2 中训练出的第一个模型"avlon_0.pth";
首先选择一张图片,这里选择了一张小狗的图片"dog.png"
具体代码
import numpy as np
import torch
import torchvision.transforms
from PIL import Image
from torch import nn
image_path = "../imgs/dog.png"
image = Image.open(image_path)
print(image)
# 查看通道数,否则调用.convert('RGB')
# image = np.array(image)
# print(image.shape)
transform = torchvision.transforms.Compose([torchvision.transforms.Resize((32, 32)),
torchvision.transforms.ToTensor()])
image = transform(image)
print(image.shape)
class Avlon(nn.Module):
def __init__(self):
super().__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)
)
def forward(self, x):
x = self.model(x)
return x
# 1.若在 CPU 上运行 GPU 模型,需要将 GPU 模型映射到 CPU 上
# model = torch.load("avlon_0_gpu.pth", map_location=torch.device('cpu'))
model = torch.load("avlon_0.pth")
print(model)
image = torch.reshape(image, (1, 3, 32, 32))
model.eval() # 测试模式
with torch.no_grad(): # 减少运行内存
image = image.cuda() # 2."avlon_0.pth"是GPU上训练出来的,故权值在GPU上,输入也需要在GPU上,否则报错
output = model(image)
print(output)
print(output.argmax(1)) # 返回最大的预测值的列索引值
运行后,预测结果:图片类型为5
22.1.2 结果验证
查看原始数据集"CIFAR10"中图片类型5的名称。
对笔记 21.1.2 代码第12行进行断点操作
可见图片类型5为"dog",该模型得到的预测结果正确。
# 大概率预测错误,因为选择的是只训练了1轮的模型