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

Python中如何加载已保存的TFLite模型进行推理?

加载预训练TFLite图像分类模型并执行推理的简便方法

方法一:复用TensorFlow Lite Model Maker的ImageClassifier接口

你之前用image_classifier.create训练模型,其实可以直接用Model Maker提供的加载方法,一步得到和训练后一致的model对象,无需重新训练:

from tflite_model_maker import image_classifier

# 从本地tflite文件加载模型
model = image_classifier.ImageClassifier.load('你的模型文件.tflite')

# 加载已准备好的测试数据集(格式和训练时的trainData/valData一致)
# 直接执行评估或推理
loss, accuracy = model.evaluate(test_data)
# 或者用tflite模型文件评估
model.evaluate_tflite('你的模型文件.tflite', test_data)

这个方法完全匹配你训练时的使用习惯,加载后的model变量和训练生成的对象功能一致,不需要额外调整数据格式,直接复用现有数据集即可。

方法二:直接用TensorFlow Lite Interpreter做轻量推理

如果不想依赖Model Maker,用TFLite原生的Interpreter也能快速实现推理,适合更灵活的场景:

import tensorflow as tf
import numpy as np

# 初始化TFLite解释器
interpreter = tf.lite.Interpreter(model_path='你的模型文件.tflite')
interpreter.allocate_tensors()

# 获取模型的输入输出信息
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()

# 预处理测试图像(需匹配模型输入尺寸、数据类型,比如(1, 224, 224, 3),float32类型)
# 这里假设你已经完成了图像的resize、归一化等预处理
test_image = np.expand_dims(预处理后的图像数组, axis=0).astype(input_details[0]['dtype'])

# 设置输入张量
interpreter.set_tensor(input_details[0]['index'], test_image)

# 执行推理
interpreter.invoke()

# 获取推理结果
output_data = interpreter.get_tensor(output_details[0]['index'])
predicted_class_idx = np.argmax(output_data)

这种方式是TFLite通用的推理流程,不依赖训练时的工具链,适合需要自定义预处理逻辑或者轻量化部署的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 07:15:35