AI模型序列化总结
模型序列化是模型部署的第一步,如何把训练好的模型存储起来,以供后续的模型预测使用,是模型部署的首先要考虑的问题。本文主要罗列当前流行开源模型不同序列化方法,以供查阅参考,欢迎添加和指正(Github)。
跨平台跨语言通用序列化方法,主要使用三种格式:XML,JSON,和Protobuf,前两种是文本格式,人和机器都可以理解,后一种是二进制格式,只有机器能理解,但在存储传输解析上有很大的速度优势。
onnx-ml
也已经可以支持传统非深度神经网络模型。详细参考文章《使用ONNX部署深度学习和传统机器学习模型》。模型本身提供的自定义序列化方法
语言级通用序列化方法
用户自定义序列化方法
如何选择模型序列化方法,可以参考以下顺序,优先使用跨平台跨语言通用序列化方法,最后再考虑使用自定义序列化方法:
在同一类型格式选项中,可以参考以下筛选流程:
# Save the model
model.save('path_to_my_model.h5')
# Recreate the exact same model purely from the file
new_model = keras.models.load_model('path_to_my_model.h5')
SavedModel
格式,该格式是TensorFlow对象的独立序列化格式,由TensorFlow serving和TensorFlow(而不是Python)支持。# Export the model to a SavedModel
model.save('path_to_saved_model', save_format='tf')
# Recreate the exact same model
new_model = keras.models.load_model('path_to_saved_model')
json_string = model.to_json()
model = keras.models.model_from_json(json_string)
或者YAML:
yaml_string = model.to_yaml()
model = keras.models.model_from_yaml(yaml_string)
模型权重值可以存储为HDF5格式:
model.save_weights('path_to_my_weights.h5')
或者TF格式:
model.save_weights('path_to_my_weights', save_format='tf')
因为该方法没有存储模型训练配置参数和优化器(Optimizer),所以如果您需要再继续训练模型,必须重新调用compile()函数来设置。但是如果只是用于模型预测,这种序列化方式已经足够了,完整的例子:
# Save JSON config to disk
json_config = model.to_json()
with open('model_config.json', 'w') as json_file:
json_file.write(json_config)
# Save weights to disk
model.save_weights('path_to_my_weights.h5')
# Reload the model from the 2 files we saved
with open('model_config.json') as json_file:
json_config = json_file.read()
new_model = keras.models.model_from_json(json_config)
new_model.load_weights('path_to_my_weights.h5')
# Make prediction against the restored model.
new_model.predict(x_test)
PMML: Nyoka,导出的是扩展的PMML模型,不属于PMML标准。
ONNX:keras2onnx
Pytorch内部格式:只存储已训练模型的状态(包括weights and biases),因为仅仅为了模型预测。
# Saving & Loading Model for Inference
torch.save(model.state_dict(), PATH)
model = TheModelClass(*args, **kwargs)
model.load_state_dict(torch.load(PATH))
model.eval()
ONNX:内部支持torch.onnx.export
# Saving model parameters to file
net = build_net(gluon.nn.Sequential())
train_model(net)
net.save_parameters(file_name)
# Loading model parameters from file
new_net = build_net(gluon.nn.Sequential())
new_net.load_parameters(file_name, ctx=ctx)
# Saving model parameters AND architecture to file
net = build_net(gluon.nn.HybridSequential())
net.hybridize()
train_model(net)
# Two files path-symbol.json and path-xxxx.params will be created, where xxxx is the 4 digits epoch number.
net.export(path)
# Loading model parameters AND architecture from file
gluon.nn.SymbolBlock.imports(symbol_file, input_names, param_file=None, ctx=None)
ONNX:内部支持mxnet.contrib.onnx.export_model
这并不是一个完整的列表,欢迎大家贡献,标星^_^。
Github地址:https://github.com/aipredict/ai-models-serialization