将机器学习模型转换为onnx,以便在windows ml中使用
keras2onnx的Python项目详细描述
简介
keras2onnx模型转换器允许用户将keras模型转换为ONNX模型格式。 最初,keras转换器是在项目onnxmltools中开发的。KALAS2ONNX转换器的开发被移动到一个^ {A3}以支持更多种类的CARAS模型,并降低了混合多个转换器的复杂性。
自从onnx操作集7以来,所有keras层都支持使用keras2onnx进行转换。有关路缘石层的详细信息,请参阅Keras documentation。KLAS2ONNX转换器还支持通过嵌入到源树中的^ {A5}转换器来避免版本冲突和安装复杂性。
windows机器学习(winml)用户可以使用WinMLTools将keras模型转换为onnx格式。如果要使用keras2onnx转换器,请参考WinML Release Notes来标识winml版本对应的onnx操作集。
keras2onnx已经在python 3.5、3.6和3.7上进行了测试(ci build)。它不支持python 2.x。
注释
tf.keras v.s.keras.io
Keras2onnx转换器现在支持这两种Keras型号。如果用户的keras包是从Keras.io安装的,那么转换器将在keras.io包创建模型时转换模型。否则,它将通过tf.keras转换它。
如果要重写此行为,请在调用转换器python api之前指定环境变量tf_keras=1。
用法
在运行转换器之前,请注意tensorflow必须安装在python环境中, 您可以选择tensorflow包(CPU版本)或tensorflow GPU(GPU版本)
验证预先培训的Keras应用程序模型
从python脚本将模型从keras转换为onnx将非常有用。 您可以使用以下API:
import keras2onnx
keras2onnx.convert_keras(model, name=None, doc_string='', target_opset=None, channel_first_inputs=None):
# type: (keras.Model, str, str, int, []) -> onnx.ModelProto
"""
:param model: keras model
:param name: the converted onnx model internal name
:param doc_string:
:param target_opset:
:param channel_first_inputs: A list of channel first input.
:return:
"""
使用以下脚本将keras应用程序模型转换为onnx,然后执行推断:
import numpy as np
from keras.preprocessing import image
from keras.applications.resnet50 import preprocess_input
import keras2onnx
import onnxruntime
# image preprocessing
img_path = 'street.jpg' # make sure the image is in img_path
img_size = 224
img = image.load_img(img_path, target_size=(img_size, img_size))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)
# load keras model
from keras.applications.resnet50 import ResNet50
model = ResNet50(include_top=True, weights='imagenet')
# convert to onnx model
onnx_model = keras2onnx.convert_keras(model, model.name)
# runtime prediction
content = onnx_model.SerializeToString()
sess = onnxruntime.InferenceSession(content)
x = x if isinstance(x, list) else [x]
feed = dict([(input.name, x[n]) for n, input in enumerate(sess.get_inputs())])
pred_onnx = sess.run(None, feed)
将onnx模型加载到运行时会话的另一种方法是首先保存模型:
import onnx
temp_model_file = 'model.onnx'
onnx.save_model(onnx_model, temp_model_file)
sess = onnxruntime.InferenceSession(temp_model_file)
我们成功地转换了所有的keras应用模型,以及其他一些预训练模型。见下文:
Model Name | Category |
---|---|
Xception | Computer Vision |
VGG16, VGG19 | Computer Vision |
ResNet50 | Computer Vision |
InceptionV3, InceptionResNetV2 | Computer Vision |
MobileNet, MobileNetV2 | Computer Vision |
DenseNet121, DenseNet169, DenseNet201 | Computer Vision |
NASNetMobile, NASNetLarge | Computer Vision |
LPCNet | Speech |
ACGAN (Auxiliary Classifier GAN) | GAN |
Adversarial Autoencoder | GAN |
BGAN (Boundary-Seeking GAN) | GAN |
BIGAN (Bidirectional GAN) | GAN |
以下模型需要自定义转换,请参见“指令”列。
Model Name | Category | Instruction |
---|---|---|
YOLOv3 | Computer Vision | Readme |
Mask RCNN | Computer Vision | Readme |
贡献
我们欢迎以反馈、想法或代码的形式作出贡献。