蓝色天空.知识 · 实践 · 创造
我的收藏
TensorFlow 教程目录 24章
TensorFlow / LEARN BY DOING

TensorFlow 模型保存与加载

实际比较 .keras、旧 HDF5、SavedModel、权重和可续训的 TensorFlow 检查点。

学完这一章,你能够

  • 实际比较 .keras、旧 HDF5、SavedModel、权重和可续训的 TensorFlow 检查点。

先确定是续训、共享还是推理

在 Keras 3 中,model.save 写 .keras 整体模型,也支持历史 .h5 形式。用于 TensorFlow 推理的 SavedModel 由 model.export 生成。要从中断点恢复训练,可显式保存模型、优化器和步数。每种用途的载入接口、必要定义与训练状态不同。

按续训、推理、权重或显式状态选择保存方式。
本站依据实测的保存与载入路径绘制。

按格式保存可运行的模型

历史 Keras 2 允许 model.save 使用无扩展名目录写 SavedModel。Keras 3 的现代入口使用 export(format='tf_saved_model');本章实测用数字版本目录 serving/1,检查 saved_model.pb、variables.index 和变量数据。assets 可用于随模型存放外部资源,是否有文件取决于模型。

当前推荐 .keras 保存 Keras 架构、权重、编译配置及已有优化器状态。旧 .h5 仍可读写,跨版本使用时须验证自定义类与优化器。下载实例逐个记录实际文件尺寸,模型结构、附加资产和存储格式都会影响数值。

用正确接口恢复推理或续训

Keras 3 的 load_model 可恢复 .keras 和旧 HDF5。SavedModel 目录改用 tf.saved_model.load 的 serve 与 serving_default,或以 TFSMLayer 包装推理端点。本站检查了实际输入名称、类型和输出值。HDF5 用 compile=False 载入,然后显式编译评价;这条路径创建新优化器。

区分权重、回调和显式状态

save_weights 使用 .weights.h5 后缀,载入方先建立匹配架构。练习同时检查了不匹配层宽的异常。ModelCheckpoint 可在每轮写权重快照;自定义循环可用 tf.train.Checkpoint 跟踪模型、优化器和步数,经 CheckpointManager 管理版本。显式恢复后再运行一个相同批次核对结果。

注册自定义层并记录发行条件

目录按模型版本编号,保存前记录输入输出约定与环境。自定义 Keras 层用 get_config 保留构造参数,借助可序列化注册或 custom_objects 让载入方获得可信实现;SavedModel 可执行已导出的跟踪计算。历史 save_format='tf' 对应当前 export。

跨版本应分别测试预测与续训。TensorFlow Serving 通常使用带数字版本目录的 SavedModel;本站在本机实测签名,服务进程另待验证。只需要在相同架构恢复已训练权重时,可单独保存权重;本章记录实际文件字节,保存耗时需要单独测量。

当前格式能力

能力SavedModel 导出HDF5 及现代 Keras
自定义层已导出端点执行跟踪计算;重建训练类另需配置。旧 HDF5 需要载入方的可信类,本章用注册类实测 .keras。
优化器与续训model.export 提供推理端点,按签名调用。本章实际验证 .keras 的 Adam 状态与下一步;HDF5 用新优化器显式复编。
推理服务入口SavedModel 原生模型格式,核对 serving_default。先转换或加载验证后重新导出。
存储大小由图、变量和资源决定;按目录总字节计量。本章报告 .h5、.weights.h5 和 .keras 的实际字节。

保存并重载真实模型、推理端点与可续训状态

含完整源码 · 202 行
展开查看收起
python
"""Compare Keras archives, legacy HDF5, SavedModel endpoints, and resumable checkpoints."""
from hashlib import file_digest
from pathlib import Path
from tempfile import TemporaryDirectory
import json
import platform

import h5py
import numpy as np
import tensorflow as tf
from tensorflow import keras


def digest(path):
    with path.open("rb") as stream:
        return file_digest(stream,"sha256").hexdigest()


def observe(cases,name,operation,inputs,expected,actual,measurements=None):
    assert actual==expected,(name,expected,actual)
    row=dict(name=name,operation=operation,inputs=inputs,expected=expected,actual=actual,passed=True)
    if measurements is not None:
        row["measurements"]=measurements
    cases.append(row)


def fresh(width=12, compiled=True):
    model=keras.Sequential([keras.Input((3,),name="features"),keras.layers.Dense(width,activation="relu"),
                            keras.layers.Dense(3,activation="softmax")])
    if compiled:
        configure(model)
    return model


def configure(model):
    model.compile(optimizer=keras.optimizers.Adam(0.01),loss=keras.losses.SparseCategoricalCrossentropy(),
        metrics=[keras.metrics.SparseCategoricalAccuracy(name="accuracy")])


def match(model,values,reference):
    return bool(np.allclose(model(values,training=False).numpy(),reference,atol=1e-6))


def failure(function):
    try:
        function()
    except ValueError as exc:
        return str(exc)
    raise AssertionError("Expected ValueError for this incompatible format.")


@keras.utils.register_keras_serializable(package="BlueSkyTutorial")
class LinearFeatureMap(keras.layers.Layer):
    def __init__(self, units, gain=1., **kwargs):
        super().__init__(**kwargs)
        self.units=units
        self.gain=gain

    def build(self,input_shape):
        self.kernel=self.add_weight(name="kernel",shape=(int(input_shape[-1]),self.units),initializer="glorot_uniform")

    def call(self,inputs):
        return tf.matmul(inputs,self.kernel)*self.gain

    def get_config(self):
        return {**super().get_config(),"units":self.units,"gain":self.gain}


def main():
    keras.utils.set_random_seed(1907)
    rng=np.random.default_rng(1913)
    values=rng.normal(size=(24,3)).astype(np.float32)
    labels=np.argmax(values,axis=1).astype(np.int32)
    options=tf.data.Options()
    options.threading.private_threadpool_size=1
    dataset=tf.data.Dataset.from_tensor_slices((values,labels)).with_options(options).batch(8)
    cases=[]
    trained=fresh()
    trained.fit(dataset,epochs=3,verbose=0,shuffle=False)
    target=trained(values[:5],training=False).numpy()
    trained_steps=int(trained.optimizer.iterations)
    assert trained_steps==9

    with TemporaryDirectory(prefix="blue-sky-artifact-format-") as directory:
        root=Path(directory)
        modern=root/"classifier.keras"
        legacy=root/"classifier.h5"
        export=root/"serving"/"1"
        weights=root/"classifier.weights.h5"
        trained.save(modern)
        restored=keras.models.load_model(modern)
        observe(cases,"keras_archive_resume","Restore architecture, inference, compile configuration and Adam iteration state",
            {"input":[5,3],"initial_updates":9},[True,9,"Adam"],
            [match(restored,values[:5],target),int(restored.optimizer.iterations),type(restored.optimizer).__name__],
            {"sha256":digest(modern),"bytes":modern.stat().st_size})
        compared_original=trained.train_on_batch(values[:8],labels[:8])
        compared_reloaded=restored.train_on_batch(values[:8],labels[:8])
        observe(cases,"keras_next_update","Apply the same next update to live and .keras-restored models",
            {"batch_rows":8},[10,10,True,True],
            [int(trained.optimizer.iterations),int(restored.optimizer.iterations),
             match(restored,values[:5],trained(values[:5],training=False).numpy()),
             bool(np.allclose(compared_original,compared_reloaded,atol=1e-6))])
        target=trained(values[:5],training=False).numpy()

        legacy_path_errors=[failure(lambda:trained.save(root/"old_style")),
            failure(lambda:trained.save_weights(root/"custom.h5"))]
        observe(cases,"keras3_extension_errors","Check extension diagnostics for the old extensionless saves and weight filename",
            {"operations":["save without extension","save_weights with plain h5"]},[True,True],
            ["extension" in legacy_path_errors[0].lower(),".weights.h5" in legacy_path_errors[1]],legacy_path_errors)

        trained.export(export,format="tf_saved_model",verbose=False)
        names=sorted(path.relative_to(export).as_posix() for path in export.rglob("*") if path.is_file())
        loaded=tf.saved_model.load(export)
        served=loaded.serve(tf.constant(values[:5])).numpy()
        endpoint=loaded.signatures["serving_default"]
        inputs=endpoint.structured_input_signature[1]
        output=endpoint(**{next(iter(inputs)):tf.constant(values[:5])})
        nested=keras.Sequential([keras.Input((3,)),keras.layers.TFSMLayer(export,call_endpoint="serve")])
        observe(cases,"savedmodel_endpoint","Read the exported graph and run the serve signature and TFSMLayer on real tensors",
            {"model_version":1,"batch_shape":[5,3]},[True,True,True,True,True],
            ["saved_model.pb" in names,"variables/variables.index" in names,
             bool(np.allclose(served,target,atol=1e-6)),
             bool(np.allclose(next(iter(output.values())).numpy(),target,atol=1e-6)),
             match(nested,values[:5],target)],
            {"files":[dict(name=name,sha256=digest(export/name),bytes=(export/name).stat().st_size) for name in names],
             "endpoints":sorted(loaded.signatures),"named_inputs":list(inputs),
             "input_dtype":next(iter(inputs.values())).dtype.name})
        error=failure(lambda:keras.models.load_model(export))
        observe(cases,"keras_loader_rejects_savedmodel","Use the Keras whole-model loader on the SavedModel folder and inspect the diagnostic",
            {"format":"tf_saved_model"},[True],["SavedModel" in error],error)

        trained.save(legacy)
        with h5py.File(legacy,"r") as content:
            groups=sorted(content.keys())
        h5=keras.models.load_model(legacy,compile=False)
        configure(h5)
        h5_evaluation=h5.evaluate(dataset,verbose=0,return_dict=True)
        observe(cases,"legacy_hdf5_round_trip","Inspect HDF5 contents, load with compile=False and evaluate with an explicit fresh optimizer",
            {"extension":".h5"},[True,True,0,True],
            ["model_weights" in groups,match(h5,values[:5],target),int(h5.optimizer.iterations),
             bool(np.isfinite(list(h5_evaluation.values())).all())],
            {"groups":groups,"sha256":digest(legacy),"bytes":legacy.stat().st_size,"evaluation":h5_evaluation})

        trained.save_weights(weights)
        rebuilt=fresh(compiled=False)
        rebuilt.load_weights(weights)
        error=failure(lambda:fresh(width=4,compiled=False).load_weights(weights))
        observe(cases,"weight_file_matching_architecture","Restore weights into matching architecture and detect an incompatible hidden layer",
            {"width_saved":12,"width_mismatch":4},[True,True],
            [match(rebuilt,values[:5],target),"could not be loaded" in error],
            {"sha256":digest(weights),"bytes":weights.stat().st_size,
             "whole_model_bytes":modern.stat().st_size,"legacy_bytes":legacy.stat().st_size,
             "savedmodel_bytes":sum((export/name).stat().st_size for name in names)})

        callback_path=root/"latest.weights.h5"
        callback=keras.callbacks.ModelCheckpoint(callback_path,save_weights_only=True,save_freq="epoch")
        trained.fit(dataset,epochs=2,callbacks=[callback],verbose=0,shuffle=False)
        again=fresh(compiled=False)
        again.load_weights(callback_path)
        observe(cases,"epoch_weight_callback","Write a weights checkpoint after each epoch and compare the last saved weights",
            {"epochs":2},[True,True],[callback_path.is_file(),match(again,values[:5],trained(values[:5]).numpy())],
            {"sha256":digest(callback_path),"bytes":callback_path.stat().st_size})

        step=tf.Variable(7,dtype=tf.int64)
        checkpoint=tf.train.Checkpoint(model=trained,optimizer=trained.optimizer,step=step)
        manager=tf.train.CheckpointManager(checkpoint,str(root/"steps"),max_to_keep=2)
        saved=manager.save()
        resume=fresh()
        resume.optimizer.build(resume.trainable_variables)
        resumed_step=tf.Variable(0,dtype=tf.int64)
        resume_checkpoint=tf.train.Checkpoint(model=resume,optimizer=resume.optimizer,step=resumed_step)
        resume_checkpoint.restore(saved).assert_consumed()
        iterations=int(resume.optimizer.iterations)
        before=match(resume,values[:5],trained(values[:5]).numpy())
        trained.train_on_batch(values[:8],labels[:8])
        resume.train_on_batch(values[:8],labels[:8])
        observe(cases,"explicit_tracking_checkpoint","Restore model, optimizer slots and a custom training step then compare the next update",
            {"expected_optimizer_before":16,"custom_step":7},[16,7,True,True],
            [iterations,int(resumed_step),before,match(resume,values[:5],trained(values[:5]).numpy())],
            {"members":[path.name for path in (root/"steps").iterdir()]})

        custom=keras.Sequential([keras.Input((3,)),LinearFeatureMap(5,gain=.7)])
        custom_output=custom(values[:3],training=False).numpy()
        custom_archive=root/"custom.keras"
        custom.save(custom_archive)
        restored_custom=keras.models.load_model(custom_archive,safe_mode=True)
        custom_export=root/"custom-serving"
        custom.export(custom_export,verbose=False)
        loaded_custom=tf.saved_model.load(custom_export)
        observe(cases,"serialized_custom_layer","Keep constructor data in get_config and compare both .keras reload and graph export",
            {"units":5,"gain":.7},[5,.7,True,True],
            [restored_custom.layers[0].units,restored_custom.layers[0].gain,match(restored_custom,values[:3],custom_output),
             bool(np.allclose(loaded_custom.serve(tf.constant(values[:3])).numpy(),custom_output,atol=1e-6))],
            {"keras_archive_sha256":digest(custom_archive),"savedmodel_sha256":digest(custom_export/"saved_model.pb")})

    print(json.dumps(dict(version=platform.python_version(),tensorflow=tf.__version__,keras=keras.__version__,
        system=platform.system(),devices=[device.name for device in tf.config.list_physical_devices()],cases=cases)))


if __name__=="__main__":
    main()
同一组输入的预测在不同入口逐项核对,确定 .keras 和跟踪检查点可接上同一个优化步骤。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 运行本站程序。

下载本章实验包 (mbskycom202612a359.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:TensorFlow

课程关联工程包(登记关联24章) · 含当前章节或实例 · mbskycom202612a359.zip

下载课程关联工程包:TensorFlow

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a378.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

先建立匹配的模型架构与输入形状,再载入权重。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习