TensorFlow Model Saving and Loading
In machine learning and deep learning projects, model saving and loading are crucial.
TensorFlow provides multiple ways to save and restore models, enabling developers to:
- Save trained models for later use
- Share models with other developers
- Resume training from checkpoints
- Deploy models to production
TensorFlow 2.x mainly supports three model saving formats:
- SavedModel format (recommended)
- HDF5 format (.h5)
- Legacy Keras format
Save the Entire Model
SavedModel Format
SavedModel is the model saving format recommended by TensorFlow; it contains complete model information:
Example
import
tensorflow
as
tf
Create and train a simple model
model
=
tf.
keras
.
Sequential
(
[
tf.
keras
.
layers
.
Dense
(
64
,
activation
=
'relu'
)
,
tf.
keras
.
layers
.
Dense
(
10
,
activation
=
'softmax'
)
]
)
model.
compile
(
optimizer
=
'adam'
,
loss
=
'sparse_categorical_crossentropy'
,
metrics
=
[
'accuracy'
]
)
model.
fit
(
x_train
,
y_train
,
epochs
=
5
)
Save in SavedModel format
model.
save
(
'my_model'
)
Note: no file extension
Directory structure after saving:
my_model/
├── assets/
├── variables/
│ ├── variables.data-00000-of-00001
│ └── variables.index
└── saved_model.pb
HDF5 Format
HDF5 is another commonly used model saving format:
Example
Save in HDF5 format
model.
save
(
'my_model.h5'
)
Note the .h5 extension
Differences Between the Two Formats
| Feature | SavedModel | HDF5 |
|---|---|---|
| Contains custom objects | Is | Requires additional configuration |
| Contains optimizer state | Is | Optional |
| TensorFlow Serving | Native support | Not supported |
| // Process file content | Larger | Smaller |
Load the Entire Model
Load from SavedModel
Example
Load from SavedModel
loaded_model
=
tf.
keras
.
models
.
load_model
(
'my_model'
)
Verify the model
loss
,
acc
=
loaded_model.
evaluate
(
x_test
,
y_test
,
verbose
=
2
)
(
f
"Restored model, accuracy: {100*acc:.1f}%"
)
Load from an HDF5 file
Example
Load from an HDF5 file
loaded_model
=
tf.
keras
.
models
.
load_model
(
'my_model.h5'
)
Verify the model
loss
,
acc
=
loaded_model.
evaluate
(
x_test
,
y_test
,
verbose
=
2
)
(
f
"Restored model, accuracy: {100*acc:.1f}%"
)
Selective Saving and Loading
Save weights only
Example
Save weights
model.
save_weights
(
'my_model_weights'
)
Save weights in HDF5 format
model.
save_weights
(
'my_model_weights.h5'
)
Load weights
Example
Create a model with the same architecture
new_model
=
tf.
keras
.
Sequential
(
[
tf.
keras
.
layers
.
Dense
(
64
,
activation
=
'relu'
)
,
tf.
keras
.
layers
.
Dense
(
10
,
activation
=
'softmax'
)
]
)
new_model.
compile
(
optimizer
=
'adam'
,
loss
=
'sparse_categorical_crossentropy'
,
metrics
=
[
'accuracy'
]
)
Load weights
new_model.
load_weights
(
'my_model_weights'
)
Or for a .h5 file
new_model.
load_weights
(
'my_model_weights.h5'
)
Save checkpoints for a custom training loop
Example
Create a checkpoint callback
checkpoint_path
=
"training_1/cp.ckpt"
cp_callback
=
tf.
keras
.
callbacks
.
ModelCheckpoint
(
filepath
=
checkpoint_path
,
save_weights_only
=
True
,
verbose
=
1
)
Train the model with the callback
model.
fit
(
x_train
,
y_train
,
epochs
=
10
,
callbacks
=
[
cp_callback
]
)
Best Practices for Model Saving and Loading
- Production deployment: Prefer the SavedModel format
- Cross-platform sharing: HDF5 format is more general
- Resume from Training Interruption: Save regularly using checkpoint callbacks
- Custom object handling:
model.save('custom_model', save_format='tf') - Model version control: Create different directories for different model versions
Common Problems and Solutions
Custom layer/model saving issues
Example
Custom layer example
class
CustomLayer
(
tf.
keras
.
layers
.
Layer
)
:
def
init
(
self
,
units
=
32
,
**kwargs
)
:
super
(
)
.
init
(
**kwargs
)
self
.
units
=
units
def
build
(
self
,
input_shape
)
:
self
.
w
=
self
.
add_weight
(
shape
=
(
input_shape
[
1
]
,
self
.
units
)
,
initializer
=
"random_normal"
,
trainable
=
True
)
def
call
(
self
,
inputs
)
:
return
tf.
matmul
(
inputs
,
self
.
w
)
def
get_config
(
self
)
:
config
=
super
(
)
.
get_config
(
)
config.
update
(
{
"units"
:
self
.
units
}
)
return
config
Use a custom layer and save
model
=
tf.
keras
.
Sequential
(
[
CustomLayer
(
10
)
]
)
model.
compile
(
optimizer
=
'adam'
,
loss
=
'mse'
)
model.
save
(
'custom_model'
)
Custom layers are saved automatically
Cross-version compatibility issues
- Try to use the same version of TensorFlow to save and load models
- For production, consider using TensorFlow Serving to avoid version issues
Large model saving optimization
Example
Use save_weights instead of save to reduce saving time
model.
save_weights
(
'large_model_weights.h5'
)