完整的模型测试套路

测试出我们训练的模型是否准确
这里,我们使用CIFAR10这个数据集来训练与测试
首先,先debug下,查看这个数据集中有哪些target
在这里插入图片描述
我们以一个小狗的图片为例,测试我们的模型是否能识别正确
在这里插入图片描述

这里用到一个函数Rezie(),因为我们的模型需要32x32的图片,然后我们的图片print一下一看,是size=631x440 的。将我们的图片由PIL类型转化成totensor类型后进行测试

import torch
import torchvision
from PIL import Image
from torch import nn
from torch.nn import Conv2d, MaxPool2d, Flatten, Linear

image_path = "img.png"

image = Image.open(image_path)
image = image.convert("RGB")
transform = torchvision.transforms.Compose([torchvision.transforms.Resize((32,32)),
                                           torchvision.transforms.ToTensor()])
image = transform(image)

class Star(nn.Module):
    def __init__(self):
        super(Star, self).__init__()
        self.conv1 = Conv2d(3,32,5,padding=2)
        self.maxpool1 = MaxPool2d(kernel_size=2)
        self.conv2 = Conv2d(32,32,5,padding=2)
        self.maxpool2 = MaxPool2d(2)
        self.conv3 = Conv2d(32,64,5,padding=2)
        self.maxpool3 = MaxPool2d(kernel_size=2)
        self.flatten = Flatten()
        self.linear1 = Linear(1024,64)
        self.linear2 = Linear(64,10)

    def forward(self,x):
        x = self.conv1(x)
        x = self.maxpool1(x)
        x = self.conv2(x)
        x = self.maxpool2(x)
        x = self.conv3(x)
        x = self.maxpool3(x)
        x = self.flatten(x)
        x = self.linear1(x)
        x = self.linear2(x)
        return x;
model = torch.load("star_9.pth")
image = torch.reshape(image,(1,3,32,32))
image = image.cuda()
model.eval()
with torch.no_grad():
    output = model(image)
print(output)

print(output.argmax(1))

输出:

tensor([[-0.4542, -7.7979,  2.0277,  4.0805,  1.7858,  4.6912,  1.4061,  4.3938,
         -6.4003, -4.6274]], device='cuda:0')
tensor([5], device='cuda:0')

结果为5,对应上方target,结果为dog,测试正确

注意:
1.image = image.convert("RGB")在导入图片后要加上,这是因为适应png,jpg各种格式的图片,png格式的图片为四通道,除了"RGB"三通道外,还有一个透明度通道,利用这个函数,可以都转化成RGB格式
2.为了养成一个良好的习惯,当然,这也是必须的,在测试模型前,要加上

model.eval()
with torch.no_grad():

3.有的时候可别忘了reshape

入门结束,撒花

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值