28、完整的模型验证步骤

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

 1 '''完整模型的验证'''
 2 import torch
 3 import torchvision
 4 from PIL import Image
 5 from torch import nn
 6 
 7 '''1、就是真实的应用场景:待预测的一张陌生图'''
 8 #先获取图像的路径,----用Image.open()打开图像,此时读取成PIL类型----保留通道颜色----转换成tensor数据类型
 9 img_path='../../dataset/Images/dog.png'
10 img=Image.open(img_path)
11 print(img)
12 
13 #####! png格式的图像是4通道的,RGB+alpha(透明度),所以要调用img=img.convert('RGB')保留其颜色通道,如果本身就是3通道,加了这句不变化
14 img=img.convert('RGB')
15 '''2、转换成tensor数据类型'''
16 transform=torchvision.transforms.Compose([torchvision.transforms.Resize((32,32)),       #compose是将几个变化合在一起,先改变尺寸大小,然后改变数据类型
17                                           torchvision.transforms.ToTensor()])         #注意数据类型前后输出保持一致
18 img=transform(img)
19 print(img.shape)
20 
21 '''3、网络模型'''
22 class class_net(nn.Module):
23     def __init__(self):
24         super().__init__()
25         self.modle=nn.Sequential(
26             nn.Conv2d(in_channels=3, out_channels=32, kernel_size=5,stride=1, padding=2),
27             nn.MaxPool2d(kernel_size=2),
28             nn.Conv2d(32,32,5,1,2),
29             nn.MaxPool2d(kernel_size=2),
30             nn.Conv2d(32,64,5,1,2),
31             nn.MaxPool2d(kernel_size=2),
32             nn.Flatten(),
33             nn.Linear(in_features=64*4*4,out_features=64),
34             nn.Linear(64,10)
35         )
36 
37     def forward(self,x):
38         x=self.modle(x)
39         return x
40 
41 '''4、加载训练好的模型'''
42 model=torch.load('tuidui_0.pth')
43 #model=torch.load('tuidui_29_gpu.pth',map_location=torch.device('cpu'))
44 # 不同环境下训练的模型在应用到不同的环境中不同,在GPU下的模型导入时要映射到CPU设备上来
45 print(model)
46 img=torch.reshape(img,(1,3,32,32))
47 #测试模式,测试的时候是不需要梯度的
48 
49 '''5、进行测试'''
50 model.eval()
51 with torch.no_grad():
52     output=model(img)
53 print(output)
54 
55 print(output.argmax(1))

 

posted @ 2023-02-27 21:14  bokeAR  阅读(153)  评论(0)    收藏  举报