TensorFlow2.3转换Keras图像字幕模型为TFLite时触发input_signature不匹配报错
报错根因
你看到的这个“输入结构不匹配”的报错,根本不是你定义的张量形状、数据类型、名字写错了,是TF 2.3.0版本里三个坑叠一块触发的:
- 自定义RNN_Decoder的call方法上叠了两层
@tf.function装饰器,离方法近的那个带input_signature的装饰会和外层的空装饰产生签名解析冲突,TF 2.3.0对多输入的自定义模型处理这块本来就有已知bug - 你手动调用了
_set_inputs()这个Keras私有方法,这玩意本来是Keras内部在首次训练/推理时自动触发的,手动提前调用会把传入的TensorSpec列表包装成嵌套结构,最后生成的计算图输入是“列表套张量”的形式,和你预定义的元组形式的input_signature外层结构对不上 - 同版本的TFLite转换器校验输入结构时是严格比对嵌套层级的,哪怕每个张量的参数全对,只要外层结构不匹配(列表vs元组),就会直接抛错。
可直接复用的修复步骤
按下面的顺序改代码,不用升级TF版本就能顺畅通转换:
- 直接删掉两段手动调用
_set_inputs()的代码,这俩方法对自定义多输入模型不仅没用,还会添乱 - 去掉叠加的空
@tf.function装饰器,给每个模型的call方法单独配明确的input_signature,不要叠装饰
改完的核心代码片段参考:# CNN_Encoder的call方法调整 @tf.function(input_signature=[tf.TensorSpec(shape=(1, 64, features_shape), dtype=tf.float32, name='encoder_input')]) def call(self, x): x = self.fc(x) x = tf.nn.relu(x) return x # RNN_Decoder的call方法调整,原有逻辑完全保留,只改装饰器 @tf.function(input_signature=[ tf.TensorSpec(shape=[1, 1], dtype=tf.int32, name='decoder_input_token'), tf.TensorSpec(shape=[1, 64, 256], dtype=tf.float32, name='encoder_feature_output'), tf.TensorSpec(shape=[1, 512], dtype=tf.float32, name='decoder_hidden_state') ]) def call(self, x, features, hidden): context_vector, attention_weights = self.attention(features, hidden) x = self.embedding(x) x = tf.concat([tf.expand_dims(context_vector, 1), x], axis=-1) output, state = self.gru(x) x = self.fc1(output) x = tf.reshape(x, (-1, x.shape[2])) x = self.fc2(x) return x, state, attention_weights - 给TFLite转换器补上适配配置,不然就算签名不报错,转GRU层的时候也会抛算子不支持的错:
encoder_converter = tf.lite.TFLiteConverter.from_keras_model(encoder) # 开启新版转换器解决旧版的签名校验bug encoder_converter.experimental_new_converter = True # 加载对TF原生算子的支持,适配unroll=True的GRU层 encoder_converter.target_spec.supported_ops = [ tf.lite.OpsSet.TFLITE_BUILTINS, tf.lite.OpsSet.SELECT_TF_OPS ] decoder_converter = tf.lite.TFLiteConverter.from_keras_model(decoder) decoder_converter.experimental_new_converter = True decoder_converter.target_spec.supported_ops = [ tf.lite.OpsSet.TFLITE_BUILTINS, tf.lite.OpsSet.SELECT_TF_OPS ] - 顺手修个潜在的后续坑:
BahdanauAttention类的初始化参数名现在写的是utils,属于笔误,应该改成units,不然后续加载预训练权重的时候会因为参数名不匹配报错。
内容的提问来源于stack exchange,提问作者David_a17
相关产品推荐
相关产品推荐

