How to save a Tensorflow / Keras model weights in a HDF file ?

Published: February 13, 2022

Updated: December 09, 2022

Tags: Python; Tensorflow; Keras;

DMCA.com Protection Status

Example of how to save a tensorflow model

Create a model

Let's create and compile a model with Tensorflow

from keras.utils.data_utils import get_file
from tensorflow import keras
from tensorflow.keras import layers

model = keras.Sequential([
    layers.Dense(20, activation='relu', input_shape=[11]),
    layers.Dense(10, activation='relu'),
    layers.Dense(10, activation='relu'),
    layers.Dense(1, activation='sigmoid')
    ])

model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])

model.summary()

gives

Model: "sequential_1"
_________________________________________________________________
 Layer (type)                Output Shape              Param #   
=================================================================
 dense_2 (Dense)             (None, 20)                240

 dense_3 (Dense)             (None, 10)                210

 dense_4 (Dense)             (None, 10)                110

 dense_5 (Dense)             (None, 1)                 11

=================================================================
Total params: 571
Trainable params: 571
Non-trainable params: 0
_________________________

Note: here the model has not be trained with any data .

Save weights in a HDF file

To save weights in a HDF file (called for example 'model_weights.h5'), a soution is to use tensorflow: save & load:

filename = 'model_weights.h5'

model.save(filename)

Load weights

To reoad the weights later a solution is to do:

filename = 'model_weights.h5'

my_saved_model = keras.models.load_model(filename)