Example of how to save a tensorflow model
Table of contents
Create a model
Let's create and compile a model with Tensorflow
from keras.utils.data_utils import get_filefrom tensorflow import kerasfrom tensorflow.keras import layersmodel = 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) 240dense_3 (Dense) (None, 10) 210dense_4 (Dense) (None, 10) 110dense_5 (Dense) (None, 1) 11=================================================================Total params: 571Trainable params: 571Non-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)
