完整的模型测试(deom)步骤

本文主要讲解了完整的模型验证,测试(deom)的具体步骤。简单来讲就是利用已经训练好的模型,给它提供输入,查看这输入经过模型后输出的结果。


目录

一、具体的步骤

 1 读取文件(相对路径)

2 转换数据类型

3 加载网络模型

4 进行测试

二、完整代码及注意事项

1.完整代码

2 输出结果

3 注意事项


一、具体的步骤

 1 读取文件(相对路径)

首先要读取我们需要输入进模型的数据,代码如下:

imgs_path = "./imgs/dog.png "
image = Image.open(imgs_path)
print(image)

输出结果:

<PIL.PngImagePlugin.PngImageFile image mode=RGBA size=273x188 at 0x1AA25DE87F0>

2 转换数据类型

因为每个模型的输入数据都是有要求的,比如在这里的模型,输入就要求(N , C,H, W)

所以我们就要将输入数据转换成我们需要的数据类型

# png格图片是4通道,我们的数据是3通道,需要转换
image = image.convert("RGB")
print(image)

# 将PIL 转换成tensor 类型
transform = torchvision.transforms.Compose([transforms.Resize((32, 32)),
                                                                        transforms.ToTensor()])
image = transform(image)
print(image.shape)

输出结果:

<PIL.Image.Image image mode=RGB size=273x188 at 0x1AA2C2131D0>
torch.Size([3, 32, 32])

注意:

image = image.convert('RGB')

因为在png格式图片是四个通道,除了RGB三通道外,还有一个透明度通道

所以我们调用imge = image.convert('RGB'), 保留其颜色通道,也就是三通道,

先对于png,jpg等图片格式,都可以这样写。

3 加载网络模型

加载经过训练的网络模型,因为我们使用的方法一进行模型保存的,所以使用相应的方法来加载,代码如下:

class Test(nn.Module):
    def __init__(self):
        super(Test, self).__init__()
        self.model = nn.Sequential(
            nn.Conv2d(in_channels=3, out_channels=32, kernel_size=5, padding=2),
            nn.MaxPool2d(kernel_size=2),
            nn.Conv2d(in_channels=32, out_channels=32, kernel_size=5, padding=2),
            nn.MaxPool2d(kernel_size=2),
            nn.Conv2d(in_channels=32, out_channels=64, kernel_size=5, padding=2),
            nn.MaxPool2d(kernel_size=2),
            nn.Flatten(),
            nn.Linear(in_features=1024, out_features=64),
            nn.Linear(in_features=64, out_features=10)
        )

    def forward(self, x):
        x = self.model(x)
        return x


model = torch.load("test_0.pth")
print(model)

输出结果:

Test(
  (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)
  )
)

4 进行测试

image = torch.reshape(image, (1, 3, 32, 32))
model.eval()  
              #   网络设置成验证状态
with torch.no_grad():        #   表示在 with 里的代码,它的梯度就没有了,可以减少运算量
    output = model(image)
print(output)
print(output.argmax(1))

输出结果:

tensor([[-2.9796, -0.0722,  0.5522,  0.6336,  1.4741,  0.9235,  2.3937,  1.1616,
         -3.4060, -0.5349]], grad_fn=<AddmmBackward0>)
tensor([6])

注意:

image = torch.reshape(image, (1, 3, 32, 32))

是因为添加一个N值,满足输入数据类型

model.eval()                是将网络设置成验证状态,规范化,写代码都可以加上
with torch.no_grad():       表示在 with 里的代码,它的梯度就没有了,可以减少运算量

print(output.argmax(1))   是将结果输入的更加简单,argmax(1)就是横向计算,argmax(0)就是纵向计算

二、完整代码及注意事项

1.完整代码

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

# 读取文件
imgs_path = "./imgs/dog.png "
image = Image.open(imgs_path)
print(image)

# png格图片是4通道,我们的数据是3通道,需要转换
image = image.convert("RGB")
print(image)

# 将PIL 转换成tensor 类型
transform = torchvision.transforms.Compose([transforms.Resize((32, 32)),
                                           transforms.ToTensor()])
image = transform(image)
print(image.shape)

# 搭建神经网络
class Test(nn.Module):
    def __init__(self):
        super(Test, self).__init__()
        self.model = nn.Sequential(
            nn.Conv2d(in_channels=3, out_channels=32, kernel_size=5, padding=2),
            nn.MaxPool2d(kernel_size=2),
            nn.Conv2d(in_channels=32, out_channels=32, kernel_size=5, padding=2),
            nn.MaxPool2d(kernel_size=2),
            nn.Conv2d(in_channels=32, out_channels=64, kernel_size=5, padding=2),
            nn.MaxPool2d(kernel_size=2),
            nn.Flatten(),
            nn.Linear(in_features=1024, out_features=64),
            nn.Linear(in_features=64, out_features=10)
        )

    def forward(self, x):
        x = self.model(x)
        return x

# 加载经过训练的网络模型
model = torch.load("test_0.pth")
print(model)
image = torch.reshape(image, (1, 3, 32, 32))
model.eval()                  #   网络设置成验证状态
with torch.no_grad():        #   表示在 with 里的代码,它的梯度就没有了,可以减少运算量
    output = model(image)
print(output)
print(output.argmax(1))

2 输出结果

<PIL.PngImagePlugin.PngImageFile image mode=RGBA size=273x188 at 0x1AA25DE87F0>
<PIL.Image.Image image mode=RGB size=273x188 at 0x1AA2C2131D0>
torch.Size([3, 32, 32])
Test(
  (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([[-2.9796, -0.0722,  0.5522,  0.6336,  1.4741,  0.9235,  2.3937,  1.1616,
         -3.4060, -0.5349]], grad_fn=<AddmmBackward0>)
tensor([6])

3 注意事项

如果电脑没有gpu,使用gpu训练的网络模型在cpu上进行测试的话,
需要将 model = torch.load("test_0.pth")
改为,model = torch.load("test_0.pth", map_location = torch.device('cpu'))  

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

晓亮.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值