Saving and exporting models

Keras · Practical · 10 min

You need to resume training, share models and deploy them; each needs a different save format.

Keras 3 has three ways to persist a model:

  • `model.save("model.keras")`: the native format, a zip with the architecture config, weights and optimizer state. Reload with keras.saving.load_model("model.keras"); the result is ready to predict or continue fit. Custom layers must be registered or passed via custom_objects.
  • `model.save_weights("model.weights.h5")` and load_weights(...): weights only. The file name must end in .weights.h5, and you rebuild the same architecture in code before loading.
  • `model.export("dir")`: an inference-only artifact. By default it writes a TensorFlow SavedModel (needs TensorFlow installed) for TF Serving or LiteRT conversion; recent versions also offer format="onnx".

The legacy .h5 full-model format and the old SavedModel mode of model.save() from Keras 2 are no longer the way to save in Keras 3.

The .keras format is backend-independent: a model trained with JAX can be loaded under PyTorch. For checkpoints during training, use the ModelCheckpoint callback, which writes the same formats.

Loading runs in safe_mode by default, which refuses to deserialise arbitrary Python code such as Lambda layers from untrusted files.

Example

import numpy as np
import keras

model = keras.Sequential([keras.Input((3,)), keras.layers.Dense(2)])
model.compile(optimizer="adam", loss="mse")

model.save("model.keras")                         # config + weights + optimizer
restored = keras.saving.load_model("model.keras")
x = np.ones((1, 3), dtype="float32")
print(np.allclose(model.predict(x, verbose=0),
                  restored.predict(x, verbose=0)))   # True

model.save_weights("model.weights.h5")            # weights only
clone = keras.Sequential([keras.Input((3,)), keras.layers.Dense(2)])
clone.load_weights("model.weights.h5")            # same architecture required
print(clone.get_weights()[0].shape)               # (3, 2)

# For serving (requires TensorFlow): model.export("export_dir")

Remember

  • .keras = full model, backend-independent
  • .weights.h5 = weights only, rebuild architecture first
  • model.export() produces inference artifacts for serving

Watch out for

  • Saving weights to a file not ending in .weights.h5, which Keras 3 rejects.

Check yourself

  1. You trained with the JAX backend and saved model.keras. Can you load it with the PyTorch backend?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: keras.io/guides/serialization_and_saving/