Save and load weights in keras

前端 未结 3 852
逝去的感伤
逝去的感伤 2020-11-30 20:56

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_         


        
相关标签:
3条回答
  • 2020-11-30 21:16

    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 :

    0 讨论(0)
  • 2020-11-30 21:23

    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')
    
    0 讨论(0)
  • 2020-11-30 21:26

    Here is a YouTube video that explains exactly what you're wanting to do: Save and load a Keras model

    There are three different saving methods that Keras makes available. These are described in the video link above (with examples), as well as below.

    First, the reason you're receiving the error is because you're calling load_model incorrectly.

    To save and load the weights of the model, you would first use

    model.save_weights('my_model_weights.h5')
    

    to save the weights, as you've displayed. To load the weights, you would first need to build your model, and then call load_weights on the model, as in

    model.load_weights('my_model_weights.h5')
    

    Another saving technique is model.save(filepath). This save function saves:

    • The architecture of the model, allowing to re-create the model.
    • The weights of the model.
    • The training configuration (loss, optimizer).
    • The state of the optimizer, allowing to resume training exactly where you left off.

    To load this saved model, you would use the following:

    from keras.models import load_model
    new_model = load_model(filepath)'
    

    Lastly, model.to_json(), saves only the architecture of the model. To load the architecture, you would use

    from keras.models import model_from_json
    model = model_from_json(json_string)
    
    0 讨论(0)
提交回复
热议问题