首页 文章

将Keras模型转换为TensorFlow protobuf

提问于
浏览
20

我们目前正在使用Keras训练各种神经网络,这是理想的,因为它具有良好的界面并且相对易于使用,但我们希望能够在我们的 生产环境 环境中应用它们 .

不幸的是 生产环境 环境是C,所以我们的计划是:

  • 使用TensorFlow后端将模型保存到protobuf

  • 将我们的 生产环境 代码链接到TensorFlow,然后加载到protobuf中

不幸的是,我不知道如何从Keras访问TensorFlow保存实用程序,它通常保存为HDF5和JSON . 如何保存到protobuf?

5 回答

  • 4

    这似乎是在_2852055中回答的,由Francois Chollet在The Keras Blog上发布 .

    特别是section II, "Using Keras models with TensorFlow" .

  • 0

    您可以通过以下方式访问TensorFlow后端:

    import keras.backend.tensorflow_backend as K
    

    然后你可以调用任何TensorFlow实用程序或函数,如:

    K.tf.ConfigProto
    
  • 6

    如果你不需要在你正在部署的环境中使用GPU,你也可以使用我的库,名为frugally-deep . 它可以在GitHub上获得并在MIT许可下发布:https://github.com/Dobiasd/frugally-deep

    节俭深度允许直接在C中直接传输已经训练过的Keras模型,而无需链接TensorFlow或任何其他后端 .

  • 2

    将您的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

  • 3

    确保更改 learning phase of keras backend 以存储图层的正确值(如丢失或批量标准化) . 关于它,这是discussion .

相关问题