You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TFLite调用set_tensor报维度不匹配错误的原因与解决方法

问题产生原因
  • 核心错误是分词API调用方式错误:texts_to_sequences方法的入参要求是文本组成的列表,你直接传入单个字符串时,方法会把字符串按单个字符遍历拆分,把每个字符当成独立文本处理,最终生成的序列结构、长度和训练时的预处理结果完全不一致。
  • 维度不匹配报错的本质:你的TFLite文本分类模型输入要求形状为[batch_size, 固定序列长度],单条推理时batch_size为1,对应形状应为[1, 训练时设定的序列填充长度]。错误调用分词API后生成的张量维度不符合要求,才会触发Got 60 but expected 1 for dimension 1的报错。
  • 后续强行把长度为60的序列强制reshape为[1,1]属于逻辑错误,输入数据本身的元素个数和目标形状完全不匹配,自然会触发张量形状不支持的错误。
可落地修复方案

按以下步骤调整代码即可,不需要强行修改模型输入形状:

  1. 先确认模型输入的真实形状,修正预处理逻辑
import numpy as np
import tensorflow as tf

# 加载TFLite模型
interpreter = tf.lite.Interpreter(model_path="/model.tflite")
interpreter.allocate_tensors()
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()

# 打印模型要求的输入形状,确认第二个维度值和训练时的序列填充长度一致
print("模型输入要求形状:", input_details[0]['shape'])

text = 'We know what we are, but know not what we may be.'
# 关键修正:单条文本要包装成列表传入分词方法
seq = self.tokeniser.texts_to_sequences([text])
# 按训练时的填充规则做序列填充,maxlen直接取模型要求的序列长度即可
padded_input = tf.keras.preprocessing.sequence.pad_sequences(
    seq, 
    maxlen=input_details[0]['shape'][1],
    dtype=np.float32
)
# 核对形状,此时padded_input的形状应该和input_details[0]['shape']完全一致,即(1, 固定序列长度)
print("预处理后输入张量形状:", padded_input.shape)
  1. 执行推理获取结果
# 传入预处理完成的张量
interpreter.set_tensor(input_details[0]['index'], padded_input)
# 启动推理
interpreter.invoke()
# 取出预测结果
predict_result = interpreter.get_tensor(output_details[0]['index'])
print("类别预测结果:", predict_result)

补充说明:如果打印出的模型输入形状第二个维度和你训练时用的序列长度不一致,说明SavedModel转TFLite的过程中输入签名配置错误,需要重新执行模型转换,不要在推理阶段硬改张量形状适配。

内容的提问来源于stack exchange,提问作者MarkK

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.31 21:09:21