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

如何不依赖Tensorflow实现Keras模型的保存与加载

无需TensorFlow操作.h5格式Keras模型的可行方案

完全有可落地的实现方案,核心原理是Keras输出的.h5模型本质是标准HDF5格式的文件,存储内容和结构都是公开规范的,不需要依赖完整TensorFlow库就能完成读写操作。

核心依赖

只需要安装轻量的HDF5读写库即可,整体体积远小于TensorFlow:

  • h5py:Python生态下的HDF5格式读写工具
  • 可选依赖numpy:如果需要处理读取到的权重数值、或者自己实现推理逻辑时使用

加载.h5模型的实现方法

Keras的.h5文件内固定存储三类信息,分别读取即可:

  1. 模型结构:存在文件根节点的model_config属性中,是JSON格式的序列化字符串,解析后就能拿到层定义、激活函数、输入输出维度等完整结构信息
  2. 权重参数:存储在model_weights分组下,每个层对应一个子分组,子分组内的数据集就是对应层的kernel、bias等权重数组,可以直接读取为numpy格式
  3. 训练配置(可选):存在根节点的training_config属性中,保存了优化器、损失函数等训练相关参数,不需要复现训练逻辑的话可以跳过读取

示例代码:

import h5py
import json
import numpy as np

def load_keras_h5(file_path):
    with h5py.File(file_path, "r") as f:
        # 读取模型结构
        model_config = json.loads(f.attrs["model_config"].decode("utf-8"))
        # 读取所有权重参数
        weights = {}
        weight_root = f.get("model_weights", f)
        for layer_name in weight_root.keys():
            if not isinstance(weight_root[layer_name], h5py.Group):
                continue
            layer_weight = {}
            for param_name in weight_root[layer_name].keys():
                layer_weight[param_name] = np.array(weight_root[layer_name][param_name])
            weights[layer_name] = layer_weight
        # 读取训练配置(可选)
        training_config = None
        if "training_config" in f.attrs:
            training_config = json.loads(f.attrs["training_config"].decode("utf-8"))
        return model_config, weights, training_config

保存为.h5格式的实现方法

按照Keras的存储规范写入对应内容即可,保存后的文件可以直接被原生Keras/TensorFlow识别:

def save_keras_h5(file_path, model_config, weights, training_config=None):
    with h5py.File(file_path, "w") as f:
        # 写入模型结构元信息
        f.attrs["model_config"] = json.dumps(model_config).encode("utf-8")
        # 写入兼容标识,保证原生Keras可以正常读取
        f.attrs["keras_version"] = "2.10.0".encode("utf-8")
        f.attrs["backend"] = "tensorflow".encode("utf-8")
        # 写入权重参数
        weight_group = f.create_group("model_weights")
        for layer_name, layer_params in weights.items():
            layer_group = weight_group.create_group(layer_name)
            for param_name, param_value in layer_params.items():
                layer_group.create_dataset(param_name, data=param_value)
        # 写入训练配置(可选)
        if training_config:
            f.attrs["training_config"] = json.dumps(training_config).encode("utf-8")

注意事项

  • 上述方法读取到的是原生的结构信息和权重数组,如果要运行推理,需要自己根据结构实现前向传播逻辑,也可以转成ONNX格式后用轻量的ONNX Runtime运行,全程不需要安装TensorFlow
  • 不同版本的Keras存储.h5文件的路径略有差异,遇到读取异常时可以先打印h5文件的目录结构,适配对应的存储路径即可
  • 如果只需要提取部分层的权重做其他用途,不需要解析完整模型结构,直接读取对应层的数据集即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 17:15:03