You need to enable JavaScript to run this app. Mobilenet SSD v1转TFLite后推理提示输入维度不匹配错误如何解决
优惠活动
大模型
产品
解决方案
定价
更多

Mobilenet SSD v1转TFLite后推理提示输入维度不匹配错误如何解决

错误原因
  • 维度不匹配的直接诱因是输入张量被额外增加了一维:你读取图片并调用np.expand_dims(img,0)后,input_tensor已经是符合模型要求的4维结构(格式为[batch_size, height, width, channel],对应维度(1,224,224,3)),但在调用interpreter.set_tensor()时你又将input_tensor放入了列表中,相当于多套了一层维度,最终传入的张量维度变为5维,和模型要求的4维输入不符。
  • 你提供的随机输入测试代码可正常运行,正是因为测试代码直接传入生成的4维张量,没有额外做列表包裹的操作。
  • 额外注意:你当前的输出后处理逻辑是为图像分类模型设计的,你训练的是Mobilenet SSD目标检测模型,推理完成后需要调整后处理逻辑,才能正确解析检测框坐标、置信度和类别结果。
修复方法

仅需要修改set_tensor对应的代码行,去掉外层的列表包裹即可,修改后的推理代码如下:

# Load TFLite model and allocate tensors.
interpreter = tf.lite.Interpreter("model.tflite")
#allocate the tensors
interpreter.allocate_tensors()

#get input and output tensors
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()

import cv2
# Read the image and decode to a tensor
image_path='117.jpg' 
img = cv2.imread(image_path)
img = cv2.resize(img,(224,224))
#Preprocess the image to required size and cast
input_shape = input_details[0]['shape']
input_tensor= np.array(np.expand_dims(img,0), dtype=np.uint8)

#set the tensor to point to the input data to be inferred
input_index = interpreter.get_input_details()[0]["index"]
# 仅修改此行,去掉input_tensor外层的[]
interpreter.set_tensor(input_index, input_tensor)
#Run the inference
interpreter.invoke()
output_details = interpreter.get_output_details()

output_data = interpreter.get_tensor(output_details[0]['index'])
results = np.squeeze(output_data)
# 此处后处理逻辑需要适配SSD目标检测模型的输出格式,当前代码仅适用于分类任务

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 12:15:04