gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 16:50:34 33 4
gpt4 key购买 nike

我在下面的以下代码生成了常规的 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 converter The TensorFlow Lite converter is a tool available as a Python API that converts trained TensorFlow models into the TensorFlow Lite format. It can also introduce optimizations, which are covered in section 4, Optimize your model.

The following example shows a TensorFlow SavedModel being converted into the TensorFlow Lite format:

import tensorflow as tf

converter = tf.lite.TFLiteConverter.from_saved_model(saved_model_dir) tflite_model = converter.convert() open("converted_model.tflite", "wb").write(tflite_model)

最佳答案

尝试使用具体功能:

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 中签名的默认 key 。

如果不起作用,请尝试取消注释 converter.experimental_new_converter = True以及它上面的两条线。

简短说明

基于 Concrete functions guide

TensorFlow 2 中的 Eager execution 会立即评估操作,而无需构建图表。
要保存模型,您需要包含在 python 可调用文件中的 graph/s:具体函数。

关于python - 如何将 tensorflow 2.0 估计器模型转换为 tensorflow lite?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58499146/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com