Keras h5 到 2019 年服务于 Tensorflow?

Posted

技术标签:

【中文标题】Keras h5 到 2019 年服务于 Tensorflow?【英文标题】:Keras h5 to Tensorflow serving in 2019? 【发布时间】:2019-08-13 15:35:03 【问题描述】:

我尝试按照本教程了解如何转换 Keras H5 Model zu ProtoBuff 并使用 Tensorflow Serve 提供服务: https://towardsdatascience.com/deploying-keras-models-using-tensorflow-serving-and-flask-508ba00f1037

该教程在网络上的许多其他资源中使用“tf.saved_model.simple_save”,现在(2019 年 3 月)已弃用和删除。 使用 freeze_session 将 h5 转换为 pb,如下所示: How to export Keras .h5 to tensorflow .pb?

好像错过了一个“服务”标签,因为 tensorflow_model_server 输出:

Loading servable: name: ImageClassifier version: 1 failed: Not found: Could not find meta graph def matching supplied tags: serve . To inspect available tag-sets in the SavedModel, please use the SavedModel CLI: saved_model_cli

用saved_model_cli检查过,没有标签。

现在有什么方法可以让 h5 模型在 tensorflow_server 中可用?

【问题讨论】:

【参考方案1】:

注意:这适用于 TF 2.0+

我假设您的 Keras 模型位于 model.h5。 首先,只需使用 TensorFlow 的 Keras 实现加载模型:

from tensorflow import keras
model = keras.models.load_model('model.h5')

然后,只需导出 SavedModel

keras.experimental.export_saved_model(model, 'path_to_saved_model')

最后,应用您通常需要的任何转换,从 SavedModel.pb 推理文件(例如:冻结、优化推理等)

您可以在 TF 的official guide for saving and serializing models in TF 2.0 中获得更多详细信息和完整示例

【讨论】:

感谢您的回复。我必须有特定版本的 keras 吗?我使用“pip3 install keras”安装了 keras。使用您的代码时,它存在错误“AttributeError: module 'tensorflow.python.keras' has no attribute 'experimental'” 这就是我所说的“tensorflow 的 Keras 实现”的意思。不要import kerasfrom tensorflow import keras部分很重要 我没有导入其他任何东西,你写的很清楚。但现在我注意到:在我的本地机器上,他找不到“实验性”,而在谷歌协作虚拟机中,他确实找到了“实验性”,但没有找到“export_saved_model”。所以我想我在某个地方的版本有问题。感谢您到目前为止的意见,将尝试以某种方式首先解决该问题 你安装的是什么TF版本? API 现在更新为model.save('path_to_saved_model', save_format="tf")

以上是关于Keras h5 到 2019 年服务于 Tensorflow?的主要内容,如果未能解决你的问题,请参考以下文章