完整的模型验证套路:利用已经训练好的模型,然后给他提供输入,应用到实际环境过程中
验证集有2个主要的作用:
(1)评估模型效果,为了调整超参数而服务
(2)调整超参数,使得模型在验证集上的效果最好
ps:超参数是在开始学习过程之前设置值的参数,而不是通过训练得到的参数数据。
说明:
(1)验证集不像训练集和测试集,它是非必需的。如果不需要调整超参数,就可以不使用验证集,直接用测试集来评估效果。
(2)验证集评估出来的效果并非模型的最终效果,主要是用来调整超参数的,模型最终效果以测试集的评估结果为准。
步骤如下:
1.指定验证集路径,并让输入符合我们的模型
image_path="imgs/airplane.jpg"#图片路径
image=Image.open(image_path)
print(image)
#不同格式的图片通道数不同,png是4通道,除了RGB通道外还有一个透明通道
image=image.convert('RGB')#仅保留颜色通道
#让输入符合我们的模型
transform=torchvision.transforms.Compose([torchvision.transforms.Resize((32,32)),#将图片大小转为32*32
torchvision.transforms.ToTensor() ])#将图片转为tensor类型
image=transform(image)
print(image.shape)
2.搭建模型
#搭建网络模型 class Tudui(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,x): x=self.model(x) return x
3.加载模型
#采用GPU训练的东西,如果只是想要单纯的在CPU上运行的话,要把它从GPU上映射到cpu上map_location=torch.device('cpu') model=torch.load("tudui_29_gpu.pth",map_location=torch.device('cpu')) print(model) #网络模型输入需要batch_size image=torch.reshape(image,[1,3,32,32])
4.进行验证
model.eval() with torch.no_grad():#消除梯度 output=model(image) print(output) print(output.argmax(1))
代码如下:
import torch
import torchvision.transforms
from PIL import Image
from torch import nn
image_path="imgs/airplane.jpg"#图片路径
image=Image.open(image_path)
print(image)
#不同格式的图片通道数不同,png是4通道,除了RGB通道外还有一个透明通道
image=image.convert('RGB')#仅保留颜色通道
#让输入符合我们的模型
transform=torchvision.transforms.Compose([torchvision.transforms.Resize((32,32)),#将图片大小转为32*32
torchvision.transforms.ToTensor() ])#将图片转为tensor类型
image=transform(image)
print(image.shape)
#搭建网络模型
class Tudui(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,x):
x=self.model(x)
return x
#加载网络模型
#RuntimeError: Attempting to deserialize object on a CUDA device but torch.cuda.is_available() is False.
# If you are running on a CPU-only machine,
# please use torch.load with map_location=torch.device('cpu') to map your storages to the CPU.
#采用GPU训练的东西,如果只是想要单纯的在CPU上运行的话,要把它从GPU上映射到cpu上map_location=torch.device('cpu')
model=torch.load("tudui_29_gpu.pth",map_location=torch.device('cpu'))#tudui_29_gpu.pth是之前训练好的模型
print(model)
#网络模型输入需要batch_size
image=torch.reshape(image,[1,3,32,32])
model.eval()
with torch.no_grad():#消除梯度
output=model(image)
print(output)
print(output.argmax(1))