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'))
5 回答
这似乎是在_2852055中回答的,由Francois Chollet在The Keras Blog上发布 .
特别是section II, "Using Keras models with TensorFlow" .
您可以通过以下方式访问TensorFlow后端:
然后你可以调用任何TensorFlow实用程序或函数,如:
如果你不需要在你正在部署的环境中使用GPU,你也可以使用我的库,名为frugally-deep . 它可以在GitHub上获得并在MIT许可下发布:https://github.com/Dobiasd/frugally-deep
节俭深度允许直接在C中直接传输已经训练过的Keras模型,而无需链接TensorFlow或任何其他后端 .
将您的keras模型保存为HDF5文件 .
然后,您可以使用以下代码进行转换:
这是我的示例代码,它处理多个输入和多个输出案例:https://github.com/amir-abdi/keras_to_tensorflow
确保更改 learning phase of keras backend 以存储图层的正确值(如丢失或批量标准化) . 关于它,这是discussion .