如何将使用Keras模型训练的Tensorflow 2. *转换为.onnx格式? [英] How to convert Tensorflow 2.* trained with Keras model to .onnx format?
问题描述
我将Python 3.7.4与TensorFlow 2.0和Keras 2.2.4-tf结合使用来训练自己的CNN模型.一切顺利.我可以使用例如model.save(my_model),然后在其他Python脚本中使用它.当我想在OpenCV中使用经过训练的模型及其C ++中的DNN模块时出现问题.cv :: dnn:readNetFromTensorflow(model.pb,model.pbtxt),就像您看到的两个参数一样,我无法获取第二个.pbtxt文件.因此,由于其灵活性,我决定使用.onnx格式.问题是现有库keras2onnx仅采用TensorFlow 1. *中的模型,我想避免使用它.转换它的代码示例如下:
I use the Python 3.7.4 with TensorFlow 2.0 and Keras 2.2.4-tf to train my own CNN model. Everything goes fine. I can use e.g. model.save(my_model), and then use it in other Python scripts. Problem appears when I want to use trained model in OpenCV with its DNN module in C++. cv::dnn:readNetFromTensorflow(model.pb, model.pbtxt), takes as you can see two arguments, and I can't get the second .pbtxt file. So I decide to use .onnx format, because of its flexibility. The problem is that existing libraries keras2onnx takes only model from TensorFlow 1.*, and I want to avoid working with it. Example of code to convert it is presented below:
import tensorflow as tf
import onnx
import keras2onnx
model = tf.keras.models.load_model(my_model_folder_path)
onnx_model = keras2onnx.convert_keras(model, model.name)
onnx.save_model(onnx_model, model_name_onnx)
还有其他方法可以将这种模型转换为onnx格式吗?
Is there some other ways to convert such model to onnx format?
推荐答案
最新版本的keras2onnx(在github主版本中)支持TensorFlow2.
The latest version of keras2onnx (in github master) supports TensorFlow 2.
您可以这样安装它:
pip install git+https://github.com/microsoft/onnxconverter-common
pip install git+https://github.com/onnx/keras-onnx
这篇关于如何将使用Keras模型训练的Tensorflow 2. *转换为.onnx格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!