TensorFlow Lite转换concrete functions官方示例运行报错如何解决
代码报错原因及修复方案
报错的根本原因是调用get_concrete_function()时没有提供输入参数的签名信息:你定义的__call__方法需要接收输入参数x,未声明x的类型、形状时,TensorFlow无法生成对应的Concrete Function,因此抛出参数缺失的错误。
修复方法
有两种可行的修复方式:
- 方式1:调用
get_concrete_function时显式传入输入签名 - 方式2:先调用一次模型传入实际张量,触发tf.function的追踪逻辑后再获取Concrete Function
完整可运行代码
import tensorflow as tf # Create a model using low-level tf.* APIs class Squared(tf.Module): @tf.function def __call__(self, x): return tf.square(x) model = Squared() # 选用任意一种方式获取concrete_func即可 # 方式1:指定输入张量的形状、类型,shape设为None可支持动态形状输入 concrete_func = model.__call__.get_concrete_function(tf.TensorSpec(shape=None, dtype=tf.float32, name='x')) # 方式2:先执行一次模型调用完成内部追踪 # model(tf.constant(5.0)) # concrete_func = model.__call__.get_concrete_function() # 转换模型 converter = tf.lite.TFLiteConverter.from_concrete_functions([concrete_func], model) tflite_model = converter.convert() # 可选:验证转换后模型的可用性 interpreter = tf.lite.Interpreter(model_content=tflite_model) interpreter.allocate_tensors() input_details = interpreter.get_input_details() output_details = interpreter.get_output_details() interpreter.set_tensor(input_details[0]['index'], tf.constant(5.0)) interpreter.invoke() print(interpreter.get_tensor(output_details[0]['index'])) # 输出为25.0,验证运行正常
上述代码在TensorFlow 2.3、2.4版本均可正常运行,官方示例省略了输入签名的显式声明步骤,仅在部分高版本TensorFlow环境中可自动推断,低版本需要显式补充该配置。
内容的提问来源于stack exchange,提问作者Jay_ESE
相关产品推荐
相关产品推荐

