Inference and evaluation
Restore a previously saved model for prediction or evaluation.
Keras · Function
Loads a Keras model from a saved model file or Orbax checkpoint. It can restore compilation and resolve custom serialized objects while protecting against unsafe lambda deserialization by default.
The function deserializes a model from a Keras file or Orbax checkpoint, reconstructing its configuration and state. It can also restore compilation, while custom classes and functions can be supplied for deserialization.
keras.saving.load_model(filepath, custom_objects=None, compile=True, safe_mode=True)| Name | Type | Description |
|---|---|---|
filepath | str | pathlib.Path | String or pathlib.Path identifying the saved model file or Orbax checkpoint directory. |
custom_objects | dict | None | Optional mapping from serialized names to custom classes or functions. |
compile | bool | Whether to compile the model after loading. |
safe_mode | bool | Whether to disallow unsafe lambda deserialization. |
A Keras model instance. If the original model was compiled and compile=True, the returned model is compiled; otherwise it is uncompiled.
import keras
model = keras.models.load_model("classifier.keras")
predictions = model.predict(x_test)Loads a saved Keras model and uses the returned model for inference.
Restore a previously saved model for prediction or evaluation.
Reconstruct a model that uses registered custom layers or functions.
Resume work with model state stored in an Orbax checkpoint directory.
It loads a model saved with model.save(), or an Orbax checkpoint, and returns a Keras model instance. The model's configuration and saved state are reconstructed during deserialization.
Follow-up: How would you load a model containing custom layers? Pass a custom_objects dictionary mapping the serialized names to the corresponding classes or functions.
compile controls whether Keras compiles the model after loading. With its default value of true, a previously compiled model is returned compiled; otherwise the returned model remains uncompiled.
Follow-up: When might you deliberately set compile to false? Set it when only inference is needed or when the saved training configuration should not be restored.
safe_mode defaults to true and prevents unsafe lambda deserialization. Setting it to false permits that deserialization but can allow arbitrary code execution, so it should only be used with trusted files.
Follow-up: What input types can filepath identify? It can be a string or pathlib.Path pointing to a saved model file or an Orbax checkpoint directory.
keras.saving.save_modelkeras.Model.savekeras.saving.load_assetskeras.saving.load_own_variables