python - 在 tensorflow 2.0 中保存和加载模型

我使用此代码在 tensorflow 2.x 中保存了预制估算器的模型

import os
serving_input_fn = tf.estimator.export.build_parsing_serving_input_receiver_fn(
tf.feature_column.make_parse_example_spec(my_feature_columns))
estimator_base_path = os.path.join( 'from_estimator')
estimator_path = classifier.export_saved_model(estimator_base_path, serving_input_fn)

此代码创建一个包含 .pb 文件的文件夹 我将来需要重用这个模型,我尝试加载这个功能

saved_model_obj = tf.compat.v2.saved_model.load(export_dir="/model_dir/")

但是当我尝试使用加载的模型进行预测时,它会引发此错误

predictions = saved_model_obj.predict(
input_fn=lambda: input_fn(predict_x))


---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-23-a9902ff8210c> in <module>
----> 1 predictions = saved_model_obj.predict(
      2     input_fn=lambda: input_fn(predict_x))

AttributeError: 'AutoTrackable' object has no attribute 'predict'

我如何加载 .pb 文件并进行预测,就像我从未保存和加载它一样?

最佳答案

当我保存模型供以后使用时,我通常这样做:

假设你的模型是model:

model.save('my_model.h5') 

这会将模型保存为 hdf5 格式。

然后当我不得不再次使用它进行预测时,我可以:

new_model = tf.keras.models.load_model('my_model.h5')

而且你可以 new_model.predict()

https://stackoverflow.com/questions/62176051/

相关文章:

python - psutil.AccessDenied : psutil. AccessDenie

reactjs - React Rich Text Editor 真的可以在移动设备上运行吗?

graphql-java - 读取通过 G​​raphQL Java 中的变量传递的字段参数

google-cloud-functions - GCP Console : console. lo

javascript - 创建 React 应用程序 + React lazy + Absolute

ethereum - 返回错误 : The method web3_clientVersion do

python - tqdm.notebook 在 jupyter notebook 中显示带有 "H

c# - 如何评估包含局部变量名称的字符串作为 C# 中的代码

r - 在创建列表 tibble 列时在 "mutation"中使用 dplyr::sym() 会导

docker - 无法加载动态库 'libcuda.so.1'; dlerror : libcuda