save() captures everything needed to resume working with a model exactly as it was: its architecture, its learned weights, its compiled optimizer along with its current state, and its loss/metrics configuration. Saving with a filepath ending in .keras, the modern recommended format, produces a single self-contained file; the model can later be fully reconstructed with tf.keras.models.load_model(), without needing to redefine the architecture or recompile it manually.
1Understanding model.save()
save() captures everything needed to resume working with a model exactly as it was: its architecture, its learned weights, its compiled optimizer along with its current state, and its loss/metrics configuration. Saving with a filepath ending in .keras, the modern recommended format, produces a single self-contained file; the model can later be fully reconstructed with tf.keras.models.load_model(), without needing to redefine the architecture or recompile it manually.
Use the modern .keras file extension when calling model.save() — it's the current recommended single-file format, replacing the older SavedModel directory and HDF5 (.h5) formats for most use cases.
import tensorflow as tf
from tensorflow.keras import layers, Sequential
import os
model = Sequential([layers.Dense(1, input_shape=(1,))])
model.compile(optimizer='sgd', loss='mse')
model.save('my_model.keras')
print(os.path.exists('my_model.keras'))2Practical Example
Here is a real-world application of model.save() showing how it is used in production TensorFlow code.
import tensorflow as tf
from tensorflow.keras import layers, Sequential
model = Sequential([layers.Dense(1, input_shape=(1,))])
model.compile(optimizer='adam', loss='mse')
model.save('my_model.keras')
restored = tf.keras.models.load_model('my_model.keras')
print(restored.optimizer.__class__.__name__)3Best Practices
Follow these guidelines when working with model.save():
1. Save the full model with model.save() when you need to later restore it completely, ready to keep training or make predictions immediately, without re-defining or re-compiling anything
2. Use the .keras file extension for the modern, recommended single-file save format
3. Save periodically during long training runs, such as via a ModelCheckpoint callback, rather than relying on a single save at the very end that a crash could prevent
Tip: Use the modern .keras file extension when calling model.save() — it's the current recommended single-file format, replacing the older SavedModel directory and HDF5 (.h5) formats for most use cases.
import tensorflow as tf
from tensorflow.keras import layers, Sequential
import os
model = Sequential([layers.Dense(1, input_shape=(1,))])
model.compile(optimizer='sgd', loss='mse')
model.save('my_model.keras')
print(os.path.exists('my_model.keras'))