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

将自定义模型转为浮点型TFLite并生成label.txt适配Flutter

解决方案:生成浮点型TFLite模型及label.txt文件

一、保证TFLite模型为浮点型

默认TFLite转换未开启量化时,输出的就是32位浮点模型。为彻底避免量化干扰,可在转换代码中明确配置:

# 禁用所有优化,确保输出浮点模型
converter.optimizations = []
# 可选:强制指定输入输出为浮点32位
converter.inference_input_type = tf.float32
converter.inference_output_type = tf.float32

二、生成label.txt文件

label.txt的内容取决于你自定义模型的分类标签,需要手动定义标签列表后写入文件。标签顺序必须和模型训练时的分类顺序完全一致,否则Flutter端预测结果会对应错误标签。

修改后的完整转换代码

import tensorflow as tf
import os

# SavedModel路径(用原始字符串避免Windows路径转义问题)
saved_model_dir = r"C:\Users\PC\Desktop\models\2"
# 替换为你自定义模型的真实分类标签
labels = ["类别A", "类别B", "类别C"]

try:
    # 加载模型
    converter = tf.lite.TFLiteConverter.from_saved_model(saved_model_dir)
    print("模型加载成功")

    # 配置浮点型模型参数
    converter.optimizations = []
    converter.inference_input_type = tf.float32
    converter.inference_output_type = tf.float32

    # 执行转换
    tflite_model = converter.convert()
    print("模型转换成功")

    # 设置输出目录
    output_dir = r"C:\Users\PC\Desktop\models\converted"
    os.makedirs(output_dir, exist_ok=True)
    tflite_path = os.path.join(output_dir, "converted_model.tflite")
    label_path = os.path.join(output_dir, "label.txt")

    # 保存TFLite模型
    with open(tflite_path, "wb") as f:
        f.write(tflite_model)
    print(f"TFLite模型已保存:{tflite_path}")

    # 保存label.txt
    with open(label_path, "w", encoding="utf-8") as f:
        for label in labels:
            f.write(f"{label}\n")
    print(f"label.txt已保存:{label_path}")

except Exception as e:
    print(f"转换出错:{e}")

验证模型浮点型的方法

如果需要确认转换后的模型类型,可添加以下代码验证:

# 加载转换后的模型查看数据类型
interpreter = tf.lite.Interpreter(model_path=tflite_path)
interpreter.allocate_tensors()
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
print(f"输入数据类型:{input_details[0]['dtype']}")
print(f"输出数据类型:{output_details[0]['dtype']}")

输出显示tf.float32即说明是浮点型模型。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 03:19:52