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

如何基于TensorFlow Lite模型执行预测及解决predict方法报错问题

报错原因

hand = model_hands.predict(X)[0] - 'str' object has no attribute 'predict'
错误的根本原因有两个:

  1. 代码中model_hands变量被赋值为tflite模型的文件路径字符串,本身不具备predict方法
  2. TensorFlow Lite模型不支持Keras训练模型的predict()直接调用,必须通过tf.lite.Interpreter实例完成推理流程
修正后的完整代码
import tensorflow as tf
import numpy as np
import pandas as pd

# 加载tflite模型,原有加载逻辑保留,调整变量名避免混淆
model_hands_path = 'converted_model.tflite'
with open(model_hands_path, 'rb') as fid:
    tflite_model = fid.read()

interpreter = tf.lite.Interpreter(model_content=tflite_model)
interpreter.allocate_tensors()

# 获取模型输入输出张量详情
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()

# 手部关键点提取逻辑保持原有逻辑不变
right = result.rightHand.hand
row = list(np.array([[res.x, res.y, res.z] for res in right]).flatten())

# 输入预处理 + 推理,替换原有predict部分的代码
# 转换为模型要求的形状和数据类型,默认适配常见的(1, 特征数)浮点输入场景
input_data = np.array(row, dtype=np.float32).reshape(input_details[0]['shape'])
# 喂入输入数据
interpreter.set_tensor(input_details[0]['index'], input_data)
# 执行推理
interpreter.invoke()
# 获取推理输出
hand = interpreter.get_tensor(output_details[0]['index'])[0]

# 后续结果处理逻辑保持不变
e_result = np.argmax(hand)
prob = str(round(hand[np.argmax(hand)], 2))
注意事项
  • 确保row的特征数量和训练模型时的输入特征数完全一致,否则会触发形状不匹配报错
  • 如果训练时对输入数据做了归一化、标准化等预处理操作,推理前必须对input_data执行完全相同的预处理
  • 若使用的是量化模型,输入数据类型需要对应调整为uint8/int8类型,可执行print(input_details)查看模型要求的输入参数

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 05:45:02