Search code examples
kerassaveloadgoogle-colaboratory

How to save and load the trained LSTM model?


I am trying to save and load with the following code but it is not working. It is showing me an error telling me that it is not able to find the model. Am I missing something? I'm using Google Colab. Thank you

import keras
callbacks_list = [keras.callbacks.EarlyStopping(monitor='val_loss',patience=6,),
                  keras.callbacks.ModelCheckpoint(filepath='my_model.h5',monitor='val_loss',mode='min', save_freq='epoch',save_best_only=True,)]
model.compile(loss=MeanAbsoluteError(), optimizer='Adam',metrics=[RootMeanSquaredError()]) 
history= model.fit(X_train, y_train,batch_size=512, epochs=100,callbacks=callbacks_list,validation_data=(X_val, y_val))

from tensorflow.keras.models import load_model
#save model to single file
model.save('my_model.h5')
#To load model
model = load_model('my_model.h5')

Solution

  • Since you are using Google Colab, you must mount your drive to access the data on Colab. Assuming that the notebook you are executing is in the directory my_dir (update the path according to YOUR particular path) you can add the following code to a cell before your save and load code:

    from google.colab import drive
    drive.mount('/content/drive')  # mounts the drive
    %cd /content/drive/MyDrive/my_dir/  # moves your position inside the directory where you are executing the code
    
    # ... your code to save and your code to load