目录
一、在 PC 上使用 TFLite Python Interpreter 进行推理
1. 安装 TFLite Python Interpreter
下面将以 PC 上使用 TFLite Python Interpreter 和 嵌入式平台(STM32Cube.AI) 两个典型场景为例,详细说明如何验证量化后(.tflite
)的模型推理精度与性能。
一、在 PC 上使用 TFLite Python Interpreter 进行推理
1. 安装 TFLite Python Interpreter
-
使用 pip 安装(适用于常见的 Windows/macOS/Linux 环境):
pip install tflite-runtime
- 或者安装
tensorflow
本身就可以使用内置的tensorflow.lite.Interpreter
(2.5+ 版本的 TF 通常都包含该功能)。
- 或者安装
-
验证安装:
python -c "import tflite_runtime; print(tflite_runtime.__version__)"
如果没有报错且输出相应版本,说明安装成功。
2. 编写推理验证脚本
我们可以编写如下 Python 脚本(例如 test_tflite_inference.py
)来加载并推理。
import numpy as np
import tflite_runtime.interpreter as tflite
# 如果是使用 TensorFlow 2.x 的 tf.lite.Interpreter:
# from tensorflow.lite import Interpreter
def load_mnist_data():
# 加载 MNIST 测试集
(_, _), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
x_test = x_test.astype("float32") / 255.0
x_test = x_test.reshape(-1, 28 * 28)
return x_test, y_test
def evaluate_tflite_model(tflite_model_path):
# 1. 加载 TFLite Interpreter
interpreter = tflite.Interpreter(model_path=tflite_model_path)
interpreter.allocate_tensors()
# 2. 获取输入、输出张量的索引
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
# 3. 加载 MNIST 测试数据
x_test, y_test = load_mnist_data()
correct = 0
total = len(x_test)
for i in range(total):
# 取出第 i 个测试样本
input_data = x_test[i].reshape(1, 28 * 28).astype(np.float32)