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

Active February 13, 2022    /    Viewed 202    /    Comments 0    /    Edit


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)

References


Card image cap
profile-image
Daidalos

Hi, I am Ben.

I have developed this web site from scratch with Django to share with everyone my notes. If you have any ideas or suggestions to improve the site, let me know ! (you can contact me using the form in the welcome page). Thanks!



Did you find this content useful ?, If so, please consider donating a tip to the author(s). MoonBooks.org is visited by millions of people each year and it will help us to maintain our servers and create new contents.

Amount