(十六)完整的模型验证套路

【声明】来源b站视频小土堆PyTorch深度学习快速入门教程(绝对通俗易懂!)【小土堆】_哔哩哔哩_bilibili

测试/demo

套路:利用及已经训练好的模型,给它提供输入

模型是在谷歌的gpu上训练好的,精度为60多,这边直接加载

 test.py

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

img_path = "./data/cat.png" #图片路径
image = Image.open(img_path) #读取图片,把图片转换为PIL类型
#png格式是4通道,RGB+透明通道
image = image.convert('RGB') #保留颜色通道,如果图片本来就是三个通道,经过此操作,不变,加上这一步,可以适应png,jpg各种格式的图片
print(image)

transform = torchvision.transforms.Compose([
    torchvision.transforms.Resize((32,32)), #把图片进行resize
    torchvision.transforms.ToTensor() #转换为Tensor
])
image = transform(image)
print(image.shape)

# 搭建神经网络
class Model(nn.Module):
    def __init__(self) -> None:
        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),
            nn.Linear(64, 10)
        )
    def forward(self, input):
        input = self.model(input)
        return input

model = torch.load("./data/mymodel_train_goole29.pth",map_location=torch.device('cpu'))
print(model)
image = torch.reshape(image,(1,3,32,32))
model.eval() #把模型转换为测试类型
with torch.no_grad(): #没有梯度
    output =model(image)
print(output) # tensor([[-1.4594,  0.5749,  0.6508,  0.7668,  0.8262,  0.8882,  1.1195,  0.5799,
#           -1.7798, -0.3695]])
print(output.argmax(1)) #预测类别 tensor([6])

结果

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值