二、模型训练与优化(5):验证优化后的模型

目录

一、在 PC 上使用 TFLite Python Interpreter 进行推理

1. 安装 TFLite Python Interpreter

2. 编写推理验证脚本

脚本说明:

3. 性能测试(可选)

二、在嵌入式平台(STM32Cube.AI)上验证

在嵌入式平台上对比准确率的方法

三、总结


下面将以 PC 上使用 TFLite Python Interpreter嵌入式平台(STM32Cube.AI) 两个典型场景为例,详细说明如何验证量化后(.tflite)的模型推理精度与性能。


一、在 PC 上使用 TFLite Python Interpreter 进行推理

1. 安装 TFLite Python Interpreter

  1. 使用 pip 安装(适用于常见的 Windows/macOS/Linux 环境):

    pip install tflite-runtime
    
    • 或者安装 tensorflow 本身就可以使用内置的 tensorflow.lite.Interpreter(2.5+ 版本的 TF 通常都包含该功能)。
  2. 验证安装

    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)  
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

魂兮-龙游

你的鼓励是我创作最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值