Python : Save and Load Tensorflow Keras Model

This post shows how to save and load your Keras model. The loaded model contains the same parameters (weights and biases) and the model structure as the final model you saved.




Save and Load Tensorflow Keras Model



In this post, we use the same data in the following previous post so I omit the data preparation part.



Fitting a Keras model and Saving it as h5 file


As a simple example, the following deep learning model is constructed. After fitting the model and forecasting using the test data, this Keras deep learning model is saved by using save() function. The saved file name has the h5 extention.

from keras.models import Sequential
from keras.layers import Dense, LSTM, Dropout
from keras.callbacks import EarlyStopping
from keras import optimizers
 
#==============================================
# define a simple Sequential model
#==============================================
seed_everything(1# fix the random seed
model = Sequential()
model.add(LSTM(50, input_shape=(n_steps,1)))
model.add(Dropout(0.2))
model.add(Dense(6))
model.add(Dense(1))
model.compile(loss='mean_squared_error'
              optimizer='adam'
              metrics = ['mse'])
 
#==============================================
# fit the model
#==============================================
early_stop = EarlyStopping(monitor='loss'
                  patience=50, verbose=0)
 
model.fit(X_train, y_train, epochs=1000
          batch_size=32, verbose=2
          callbacks=[early_stop])
 
#==============================================
# Evaluate model
#==============================================
test_loss, test_acc = model.evaluate(X_test,  y_test, verbose=2)
print(test_loss, test_acc)
 
#==============================================
# Forecast using test data
#==============================================
y_pred = model.predict(X_test, verbose=0)
 
plt.figure().set_figwidth(12)
plt.plot(np.c_[y_pred, y_test])
plt.legend(('Test data','Forecast'))
plt.show()
 
#==============================================
# Save the final model
#==============================================
model.save('model_1234.h5')
 
 
cs


Python : Save and Load Tensorflow Keras Model


Loading the Keras model


Loading the Keras model is straightforward; simply use the load_model() function with the saved file name and the h5 file extension.

#==============================================
# Load the final model saved
#==============================================
model_loaded = tf.keras.models.load_model('model_1234.h5')
 
#==============================================
# Evaluate model
#==============================================
test_loss, test_acc = model_loaded.evaluate(X_test, y_test, verbose=2)
print(test_loss, test_acc)
 
#==============================================
# Forecast using test data
#==============================================
y_pred_from_model_loaded = model.predict(X_test, verbose=0)
 
plt.figure().set_figwidth(12)
plt.plot(np.c_[y_pred_from_model_loaded, y_test])
plt.legend(('Test data','Forecast from the model loaded'))
plt.show()
 
 
cs


Python : Save and Load Tensorflow Keras Model

The model saved is located in the working directory as follows.
Python : Save and Load Tensorflow Keras Model


Concluding Remarks


This post explained how to save and load your Keras model. This appears to be beneficial for preserving the reproducibility of your study. \(\blacksquare\)


No comments:

Post a Comment