[python] Save and load weights in keras

Im trying to save and load weights from the model i have trained.

the code im using to save the model is.

TensorBoard(log_dir='/output')
model.fit_generator(image_a_b_gen(batch_size), steps_per_epoch=1, epochs=1)
model.save_weights('model.hdf5')
model.save_weights('myModel.h5')

Let me know if this an incorrect way to do it,or if there is a better way to do it.

but when i try to load them,using this,

from keras.models import load_model
model = load_model('myModel.h5')

but i get this error:


ValueError                                Traceback (most recent call 
last)
<ipython-input-7-27d58dc8bb48> in <module>()
      1 from keras.models import load_model
----> 2 model = load_model('myModel.h5')

/home/decentmakeover2/anaconda3/lib/python3.5/site-
packages/keras/models.py in load_model(filepath, custom_objects, compile)
    235         model_config = f.attrs.get('model_config')
    236         if model_config is None:
--> 237             raise ValueError('No model found in config file.')
    238         model_config = json.loads(model_config.decode('utf-8'))
    239         model = model_from_config(model_config, 
custom_objects=custom_objects)

ValueError: No model found in config file.

Any suggestions on what i may be doing wrong? Thank you in advance.

This question is related to python keras

The answer is


For loading weights, you need to have a model first. It must be:

existingModel.save_weights('weightsfile.h5')
existingModel.load_weights('weightsfile.h5')     

If you want to save and load the entire model (this includes the model's configuration, it's weights and the optimizer states for further training):

model.save_model('filename')
model = load_model('filename')

Since this question is quite old, but still comes up in google searches, I thought it would be good to point out the newer (and recommended) way to save Keras models. Instead of saving them using the older h5 format like has been shown before, it is now advised to use the SavedModel format, which is actually a dictionary that contains both the model configuration and the weights.

More information can be found here: https://www.tensorflow.org/guide/keras/save_and_serialize

The snippets to save & load can be found below:

model.fit(test_input, test_target)
# Calling save('my_model') creates a SavedModel folder 'my_model'.
model.save('my_model')

# It can be used to reconstruct the model identically.
reconstructed_model = keras.models.load_model('my_model')

A sample output of this :

enter image description here