一、步骤
加载被应用的数据
将数据转换为模型输入的大小及类型
加载模型(注意模型若为cuda训练的则数据应该也转换为cuda)
进行预测
注:所采用的就是CIFAR10-分类模型完整套路所训练第10轮的模型(验证集预测正确百分比30%多一点)
二、代码实践-CIFAR10
import torch
import torchvision.transforms
from PIL import Image
import os
# 运用模型进行图片识别
ImagePath = "../imgs/airplane.png"
img = Image.open(ImagePath)
img = img.convert("RGB")
transform = torchvision.transforms.Compose([torchvision.transforms.Resize((32,32)),
torchvision.transforms.ToTensor()
])
img = transform(img)
img = torch.reshape(img,(1,3,32,32))
print(img.type())
img = img.to('cuda')
print(img.type())
module = torch.load("../Modules/CIFAR10_module10.pth", map_location='cuda')
module.eval()
with torch.no_grad():
output = module(img)
result = output.argmax(1)
print(result)
三、结果
CIFAR10类别
输入图片:结果: