我们目前正在使用Keras训练各种神经网络,这非常理想,因为它具有良好的接口和相对较易的使用,但我们希望能够在生产环境中应用它们。
不幸的是,生产环境是C++,所以我们的计划是:
- 使用TensorFlow后端将模型保存为protobuf格式
- 将我们的生产代码与TensorFlow链接,然后加载protobuf格式的模型
不幸的是,我不知道如何从Keras中访问TensorFlow保存工具,因为它通常保存为HDF5和JSON格式。如何保存为protobuf格式?
我们目前正在使用Keras训练各种神经网络,这非常理想,因为它具有良好的接口和相对较易的使用,但我们希望能够在生产环境中应用它们。
不幸的是,生产环境是C++,所以我们的计划是:
不幸的是,我不知道如何从Keras中访问TensorFlow保存工具,因为它通常保存为HDF5和JSON格式。如何保存为protobuf格式?
您可以通过以下方式访问TensorFlow后端:
import keras.backend.tensorflow_backend as K
K.tf.ConfigProto
将你的Keras模型保存为HDF5文件。
接下来,您可以使用以下代码进行转换:
from keras import backend as K
from tensorflow.python.framework import graph_util
from tensorflow.python.framework import graph_io
weight_file_path = 'path to your keras model'
net_model = load_model(weight_file_path)
sess = K.get_session()
constant_graph = graph_util.convert_variables_to_constants(sess, sess.graph.as_graph_def(), 'name of the output tensor')
graph_io.write_graph(constant_graph, 'output_folder_path', 'output.pb', as_text=False)
print('saved the constant graph (ready for inference) at: ', osp.join('output_folder_path', 'output.pb'))
以下是我处理多输入和多输出情况的示例代码: https://github.com/amir-abdi/keras_to_tensorflow
tf.get_default_graph().as_graph_def()
获取protobuf。 - Yaroslav Bulatov