如何将tensorflow 2.0估计器模型转换为tensorflow lite?

时间:2019-10-22 07:31:01

标签: python android tensorflow tensorflow-estimator tensorflow-lite

以下我下面的代码会生成常规的tensorflow模型,但是当我尝试将其转换为tensorflow lite却无法正常工作时,我遵循了以下文档。

https://www.tensorflow.org/tutorials/estimator/linear 1 https://www.tensorflow.org/lite/guide/get_started

export_dir = "tmp"
serving_input_fn = tf.estimator.export.build_parsing_serving_input_receiver_fn(
  tf.feature_column.make_parse_example_spec(feat_cols))

estimator.export_saved_model(export_dir, serving_input_fn)

# Convert the model.
converter = tf.lite.TFLiteConverter.from_saved_model("tmp/1571728920/saved_model.pb")
tflite_model = converter.convert()

错误消息

Traceback (most recent call last):
  File "C:/Users/Dacorie Smith/PycharmProjects/JamaicaClassOneNotifableModels/ClassOneModels.py", line 208, in <module>
    tflite_model = converter.convert()
  File "C:\Users\Dacorie Smith\PycharmProjects\JamaicaClassOneNotifableModels\venv\lib\site-packages\tensorflow_core\lite\python\lite.py", line 400, in convert
    raise ValueError("This converter can only convert a single "
ValueError: This converter can only convert a single ConcreteFunction. Converting multiple functions is under development.

从文档中提取

  

TensorFlow Lite转换器TensorFlow Lite转换器是一个工具   作为Python API提供,可将经过训练的TensorFlow模型转换为   TensorFlow Lite格式。它还可以引入优化,   在第4节“优化模型”中进行了介绍。

     

以下示例显示了正在转换的TensorFlow SavedModel   转换为TensorFlow Lite格式:

     

将tensorflow导入为tf

     

转换器= tf.lite.TFLiteConverter.from_saved_model(saved_model_dir)   tflite_model = converter.convert()open(“ converted_model.tflite”,   “ wb”)。write(tflite_model)

1 个答案:

答案 0 :(得分:3)

尝试使用具体功能:

export_dir = "tmp"
serving_input_fn = tf.estimator.export.build_parsing_serving_input_receiver_fn(
  tf.feature_column.make_parse_example_spec(feat_cols))

estimator.export_saved_model(export_dir, serving_input_fn)

# Convert the model.
saved_model_obj = tf.saved_model.load(export_dir="tmp/1571728920/")
concrete_func = saved_model_obj.signatures['serving_default']

converter = tf.lite.TFLiteConverter.from_concrete_functions([concrete_func])

# print(saved_model_obj.signatures.keys())
# converter.optimizations = [tf.lite.Optimize.DEFAULT]
# converter.experimental_new_converter = True

tflite_model = converter.convert()

serving_default是SavedModels中签名的默认密钥。

如果不起作用,请尝试取消注释converter.experimental_new_converter = True及其上方的两行。

简短说明

基于Concrete functions guide

TensorFlow 2中的急切执行将立即评估操作,而无需构建图形。 要保存模型,您需要将图形包装在可调用的python中:一个具体函数。