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

如何在Python桌面应用中不导入Keras加载Keras模型?

解决Keras模型打包exe体积过大的方案

针对你的场景(Python3.11.7 + Keras2.15.0/TensorFlow2.15 + PyInstaller),以下是几种可行的方案:

方案1:转换为TFLite轻量化模型

TFLite是TensorFlow专为部署设计的轻量级格式,体积远小于H5,且加载时仅需依赖TensorFlow Lite模块,无需完整Keras/TensorFlow:

  • 转换模型(训练环境执行):
import tensorflow as tf

# 加载原H5模型
model = tf.keras.models.load_model("model.h5")
# 转换为TFLite
converter = tf.lite.TFLiteConverter.from_keras_model(model)
tflite_model = converter.convert()
# 保存为.tflite文件
with open("model.tflite", "wb") as f:
    f.write(tflite_model)
  • 部署加载(打包到exe的代码):
import tensorflow as tf

# 加载TFLite模型
interpreter = tf.lite.Interpreter(model_path="model.tflite")
interpreter.allocate_tensors()

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

# 运行推理示例
input_data = ... # 你的输入数据,需匹配模型输入形状/类型
interpreter.set_tensor(input_details[0]['index'], input_data)
interpreter.invoke()
output_data = interpreter.get_tensor(output_details[0]['index'])

方案2:优化PyInstaller打包配置

通过精简依赖、排除冗余模块来缩小exe体积:

  • 使用纯净虚拟环境:仅安装tensorflow、PyInstaller和GUI依赖(如PyQt/Tkinter),避免多余库被打包。
  • 定制.spec文件排除冗余:
    生成.spec文件:pyi-makespec your_script.py
    编辑.spec文件,在hiddenimports中仅保留必要依赖,同时在excludes中添加冗余模块:
    excludes=[
        'tensorflow.python.tests',
        'tensorflow.examples',
        'tensorflow.doc',
        'keras.applications', # 如果你没用到预训练模型
        'keras.datasets'      # 如果你没用到内置数据集
    ]
    
  • 使用UPX压缩:打包时添加--upx-dir=path/to/upx参数,UPX可大幅压缩exe体积(需提前下载UPX工具)。
  • 采用--onedir模式:相比--onefile,目录模式体积更小,运行速度更快,适合对体积敏感的场景。

方案3:手动加载模型结构与权重(避免完整Keras导入)

如果必须保留H5格式,可拆分模型结构和权重加载,仅导入必要模块:

  • 训练时导出模型结构为JSON:
model = tf.keras.models.load_model("model.h5")
model_json = model.to_json()
with open("model_structure.json", "w") as f:
    f.write(model_json)
model.save_weights("model_weights.h5")
  • 部署时加载:
# 仅导入必要模块,避免导入完整keras.models
from tensorflow.keras.models import model_from_json
from tensorflow.keras.models import load_weights

# 加载结构
with open("model_structure.json", "r") as f:
    model_structure = f.read()
model = model_from_json(model_structure)
# 加载权重
model.load_weights("model_weights.h5")

# 运行推理
output = model.predict(input_data)

这种方式仅引入模型结构解析和权重加载的必要模块,比直接用keras.models.load_model减少部分冗余依赖。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 19:02:45