PyTorch模型转换为ONNX格式实现过程详解
作者:实力 时间:2022-03-18 00:54:18
1. 安装依赖
将PyTorch模型转换为ONNX格式可以使它在其他框架中使用,如TensorFlow、Caffe2和MXNet
首先安装以下必要组件:
Pytorch
ONNX
ONNX Runtime(可选)
建议使用conda
环境,运行以下命令来创建一个新的环境并激活它:
conda create -n onnx python=3.8
conda activate onnx
接下来使用以下命令安装PyTorch和ONNX:
conda install pytorch torchvision torchaudio -c pytorch
pip install onnx
可选地,可以安装ONNX Runtime以验证转换工作的正确性:
pip install onnxruntime
2. 准备模型
将需要转换的模型导出为PyTorch模型的.pth
文件。使用PyTorch内置的函数加载它,然后调用eval()方法以保证close状态:
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torch.onnx
import torchvision.transforms as transforms
import torchvision.datasets as datasets
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(3, 6, 5)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(6, 16, 5)
self.fc1 = nn.Linear(16 * 5 * 5, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)
def forward(self, x):
x = self.pool(F.relu(self.conv1(x)))
x = self.pool(F.relu(self.conv2(x)))
x = x.view(-1, 16 * 5 * 5)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
net = Net()
PATH = './model.pth'
torch.save(net.state_dict(), PATH)
model = Net()
model.load_state_dict(torch.load(PATH))
model.eval()
3. 调整输入和输出节点
现在需要定义输入和输出节点,这些节点由导出的模型中的张量名称表示。将使用PyTorch内置的函数torch.onnx.export()
来将模型转换为ONNX格式。下面的代码片段说明如何找到输入和输出节点,然后传递给该函数:
input_names = ["input"]
output_names = ["output"]
dummy_input = torch.randn(batch_size, input_channel_size, input_height, input_width)
# Export the model
torch.onnx.export(model, dummy_input, "model.onnx", verbose=True,
input_names=input_names, output_names=output_names)
4. 运行转换程序
运行上述程序时可能遇到错误信息,其中包括一些与节点的名称和形状相关的警告,甚至还有Python版本、库、路径等信息。在处理完这些错误后,就可以转换PyTorch模型并立即获得ONNX模型了。输出ONNX模型的文件名是model.onnx
。
5. 使用后端框架测试ONNX模型
现在,使用ONNX模型检查一下是否成功地将其从PyTorch导出到ONNX,可以使用TensorFlow或Caffe2进行验证。以下是一个简单的示例,演示如何使用TensorFlow来加载和运行该模型:
import onnxruntime as rt
import numpy as np
sess = rt.InferenceSession('model.onnx')
input_name = sess.get_inputs()[0].name
output_name = sess.get_outputs()[0].name
np.random.seed(123)
X = np.random.randn(batch_size, input_channel_size, input_height, input_width).astype(np.float32)
res = sess.run([output_name], {input_name: X})
这应该可以顺利地运行,并且输出与原始PyTorch模型具有相同的形状(和数值)。
6. 核对结果
最好的方法是比较PyTorch模型与ONNX模型在不同框架中推理的结果。如果结果完全匹配,则几乎可以肯定地说PyTorch到ONNX转换已经成功。以下是通过PyTorch和ONNX检查模型推理结果的一个小程序:
# Test the model with PyTorch
model.eval()
with torch.no_grad():
Y = model(torch.from_numpy(X)).numpy()
# Test the ONNX model with ONNX Runtime
sess = rt.InferenceSession('model.onnx')
res = sess.run(None, {input_name: X})[0]
# Compare the results
np.testing.assert_allclose(Y, res, rtol=1e-6, atol=1e-6)
来源:https://juejin.cn/post/7221777883160985661
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
新建文件时Pycharm中自动设置头部模板信息的方法
![](https://img.aspxhome.com/file/2023/2/81622_0s.jpg)
YUI Compressor 组件压缩 JavaScript 的一些原理
SQLServer中数据库文件的存放方式,文件和文件组
分类、属性、关键词与Tag
Python使用plotly绘制数据图表的方法
![](https://img.aspxhome.com/file/2023/1/82721_0s.png)
解决hive中导入text文件遇到的坑
浅谈如何使用Python控制手机(一)
![](https://img.aspxhome.com/file/2023/9/68979_0s.jpg)
一组常用的弹出窗口用法总结
PS笔刷,样式,形状、渐变、滤镜载入方式及使用
![](https://img.aspxhome.com/file/UploadPic/200710/17/2007101711564849s.gif)
中国移动G3笔记本全Flash 网站
![](https://img.aspxhome.com/file/UploadPic/20094/27/g3_1-35s.jpg)
python基础教程之分支、循环简单用法
简单方法实现网页自动适应任何分辨率任何窗口大小
微信小程序与php 实现微信支付的简单实例
ie和火狐兼容问题
python Django 创建应用过程图示详解
![](https://img.aspxhome.com/file/2023/4/67304_0s.png)