我做的是一个简单的二分类任务,用了个vgg11,因为要部署到应用,所以将 PyTorch 中定义的模型转换为 ONNX 格式,然后在 ONNX Runtime 中运行它,那就不用了在机子上配pytorch环境了。然后也试过转出来的onnx用opencv.dnn来调用,发现识别完全不对,据说是opencv的那个包只能做二维的pooling层,不能做三维的。
然后具体的模型转换以及使用如下代码所示,仅作为学习笔记咯~(亲测可用)
pip install onnx
pip install onnxruntime
首先,将Pytorch模型转成onnx格式,然后验证一波onnx模型有没有什么毛病
import torch
import torchvision
import torch.nn as nn
from vgg import vgg11_bn
from torchvision import models
import time
out_onnx = 'model.onnx'
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
dummy = torch.randn(1, 1, 128, 128)
model = vgg11_bn()
model = nn.DataParallel(model)
model.load_state_dict(torch.load('model.pth', map_location='cuda'))
if isinstance(model,torch.nn.DataParallel):
model = model.module
model = model.to(device)
dummy = dummy.to(device)
input_names = ["input"]
output_names = ["output"]
torch_out = torch.onnx.export(model, dummy, out_onnx, input_names=input_names, output_names=output_names)
print("finish!")
time.sleep(5)
import onnx
onnx_model = onnx.load(out_onnx)
print('The model is:\n{}'.format(onnx_model))
try:
onnx.checker.check_model(onnx_model)
except onnx.checker.ValidationError as e:
print('The model is invalid: %s' % e)
else:
print('The model is valid!')
output = onnx_model.graph.output
print(output)
然后就是用onnx在python不import torch的情况下做推理的测试:
import numpy as np
from PIL import Image
img_input = "test.jpg"
imagec = Image.open(img_input).convert("L")
imagec = imagec.resize((128, 128))
image = np.array(imagec,dtype=np.float32)/255.
image = np.expand_dims(image, axis=0)
image = np.expand_dims(image, axis=0)
print(image)
import onnxruntime
import onnx
onnx_model_path = "models.onnx"
session = onnxruntime.InferenceSession(onnx_model_path)
inputs = {session.get_inputs()[0].name: image}
logits = session.run(None, inputs)[0]
print("onnx weights", logits)
print("onnx prediction", logits.argmax(axis=1)[0])
参考了很多大佬的文章
https://blog.csdn.net/ouening/article/details/109245243 https://zhuanlan.zhihu.com/p/363177241 https://www.cnblogs.com/sddai/p/14537381.html 还有的大佬链接找不到了,感谢大佬们
|