当前位置:网站首页>完整的模型验证(测试,demo)套路
完整的模型验证(测试,demo)套路
2022-07-07 23:11:00 【booze-J】
文章
网络模型训练与保存参考利用GPU训练网络模型,并且加载的网络模型也是该篇文章中的代码训练出来的。
验证模型示例代码:
import torch
import torchvision
from PIL import Image
from torch import nn
from torch.nn import Sequential, Conv2d, MaxPool2d, Flatten, Linear
# 获取图片存放路径
image_path = "./images/img.png"
# 读取图片
image = Image.open(image_path)
# 读取的图片类型为 <PIL.PngImagePlugin.PngImageFile image mode=RGBA size=296x183 at 0x1FBD755E340>
print("image:\n",image)
image = image.convert("RGB")
'''接下来要对image进行通道转换,因为png格式是四通道的,除RGB三通道外,还有一个透明度通道。所以我们调用image = image.convert("RGB"),保留其颜色通道 当然,如果图片本来就是三个颜色通道,经过此操作,不变。加上这一步之后可以适应png,jpg各种格式的图片、 '''
# [Resize](https://pytorch.org/vision/stable/generated/torchvision.transforms.Resize.html?highlight=resize#torchvision.transforms.Resize)
# 为什么要进行Resize这一步呢?是因为我们这个网络模型的要求输入是32*32大小的图片
transform = torchvision.transforms.Compose([torchvision.transforms.Resize((32,32)),torchvision.transforms.ToTensor()])
# 将image转化为合适的类型
image = transform(image)
print("image:\n",image.shape) # torch.Size([3, 32, 32])
# 搭建神经网络(单独开一个文件存放网络模型)
class Booze(nn.Module):
def __init__(self):
super(Booze, self).__init__()
self.model = Sequential(
Conv2d(3, 32, 5, padding=2),
MaxPool2d(2),
Conv2d(32, 32, 5, padding=2),
MaxPool2d(2),
Conv2d(32, 64, 5, padding=2),
MaxPool2d(2),
Flatten(),
Linear(1024, 64),
Linear(64, 10)
)
def forward(self,x):
x = self.model(x)
return x
# 加载网络模型
model = torch.load("./model/obj_0.pth")
# 将图片转化为四维的(3,32,32) -> (1,3,32,32)
image = torch.reshape(image,(1,3,32,32))
# 定义测试所用的设备 模型的训练方式的不同(GPU训练、CPU训练) 测试时的数据类型也不一样
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# 查看模型
print(model)
model.eval() # 测试的时候,这一步大家也许经常遗忘
with torch.no_grad(): # # 这一步大家也许经常遗忘
# 模型如果是使用cuda训练的,则测试的时候也需要使用cuda类型的数据进行测试
output = model(image.to(device))
''' tensor([[-1.1961, 0.1016, 0.6076, 0.5585, 0.4856, 0.4466, 0.4176, 0.3158, -1.4603, -0.5929]], device='cuda:0') 可以看到output含10个数据,每个数据代表着测试图片属于该类的一个概率 '''
print(output)
# 打印出测试图片使用网络模型预测的类别 发现和实际类别不同哈 原因是因为该网络模型的训练次数较少 增加训练批次和调整学习率可以得到更精准的网络模型
print(output.argmax(1).item())
一些需要注意的点在代码中的注释有详细的描述。
注意
- png格式是四通道的,除RGB三通道外,还有一个透明度通道。所以我们调用
image = image.convert("RGB"),保留其颜色通道当然,如果图片本来就是三个颜色通道,经过此操作,不变。 - 在将待预测图片传入网络模型中预测之前,需要先进行预处理,图片大小是否符合输入要求,图片格式和维度是否符合要求等等。
- 模型如果是使用cuda训练的,则测试的时候也需要使用cuda类型的数据进行测试
- 打印出测试图片使用网络模型预测的类别,发现和实际类别不同,原因是因为该网络模型的训练次数较少或者学习率不合适,增加训练批次和调整学习率可以得到更精准的网络模型。
边栏推荐
- Which securities company has a low, safe and reliable account opening commission
- Password recovery vulnerability of foreign public testing
- [reprint] solve the problem that CONDA installs pytorch too slowly
- ReentrantLock 公平锁源码 第0篇
- How to insert highlighted code blocks in WPS and word
- Reptile practice (VIII): reptile expression pack
- 【obs】Impossible to find entrance point CreateDirect3D11DeviceFromDXGIDevice
- What is load balancing? How does DNS achieve load balancing?
- 13. Model saving and loading
- 【愚公系列】2022年7月 Go教学课程 006-自动推导类型和输入输出
猜你喜欢

第一讲:链表中环的入口结点

Invalid V-for traversal element style

【愚公系列】2022年7月 Go教学课程 006-自动推导类型和输入输出

My best game based on wechat applet development

Password recovery vulnerability of foreign public testing

Fofa attack and defense challenge record

Malware detection method based on convolutional neural network

51 communicates with the Bluetooth module, and 51 drives the Bluetooth app to light up

Class head up rate detection based on face recognition

"An excellent programmer is worth five ordinary programmers", and the gap lies in these seven key points
随机推荐
Course of causality, taught by Jonas Peters, University of Copenhagen
ABAP ALV LVC模板
What is load balancing? How does DNS achieve load balancing?
fabulous! How does idea open multiple projects in a single window?
Kubernetes Static Pod (静态Pod)
The standby database has been delayed. Check that the MRP is wait_ for_ Log, apply after restarting MRP_ Log but wait again later_ for_ log
基于人脸识别实现课堂抬头率检测
How is it most convenient to open an account for stock speculation? Is it safe to open an account on your mobile phone
手机上炒股安全么?
【obs】官方是配置USE_GPU_PRIORITY 效果为TRUE的
NVIDIA Jetson测试安装yolox过程记录
Deep dive kotlin collaboration (the end of 23): sharedflow and stateflow
8.优化器
13.模型的保存和载入
Lecture 1: the entry node of the link in the linked list
letcode43:字符串相乘
After going to ByteDance, I learned that there are so many test engineers with an annual salary of 40W?
Analysis of 8 classic C language pointer written test questions
SDNU_ ACM_ ICPC_ 2022_ Summer_ Practice(1~2)
A brief history of information by James Gleick