How can we plot accuracy and loss graphs from a Keras model saved earlier?

后端 未结 2 659
不知归路
不知归路 2020-12-17 07:08

Is there a way to plot accuracy and loss graphs from the CNN model saved earlier? Or can we only plot graphs during training and evaluating the model?

model          


        
相关标签:
2条回答
  • 2020-12-17 07:26

    None of the available options for saving models in Keras includes the training history, which is what exactly you are asking for here. To keep this history available, you have to do some trivial modifications to your training code so as to save it separately; here is a reproducible example based on the Keras MNIST example and only 3 training epochs:

    hist = model.fit(x_train, y_train,
              batch_size=batch_size,
              epochs=3,
              verbose=1,
              validation_data=(x_test, y_test))
    

    hist is a Keras callback, and it includes a history dictionary, which contains the metrics you are looking for:

    hist.history
    # result:
    {'acc': [0.9234666666348775, 0.9744000000317892, 0.9805999999682109],
     'loss': [0.249011807457606, 0.08651042315363884, 0.06568188704450925],
     'val_acc': [0.9799, 0.9843, 0.9876],
     'val_loss': [0.06219216037504375, 0.04431889447008725, 0.03649089169385843]}
    

    i.e. the training & validation metrics (here loss & accuracy) for each one of the training epochs (here 3).

    Now it is trivial to save this dictionary using Pickle, and to restore it as required:

    import pickle
    
    # save:
    f = open('history.pckl', 'wb')
    pickle.dump(hist.history, f)
    f.close()
    
    # retrieve:    
    f = open('history.pckl', 'rb')
    history = pickle.load(f)
    f.close()
    

    A simple check here confirms that the original and the retrieved variables are indeed identical:

    hist.history == history
    # True
    
    0 讨论(0)
  • 2020-12-17 07:30

    It depends on the way you saved the model.

    In general, there are two cases, the first one is saving and loading the whole model (including architecture and weights):

    from keras.models import load_model
    
    model.save('my_model.h5')  # creates a HDF5 file 'my_model.h5'
    ...
    model = load_model('my_model.h5')
    

    The second is saving only the weights:

    def create_model():
       model = Sequential() 
       # ... creating the model exactly as it was defined in the training time
    
    # You must create the model since loading only the weights
    model = create_model()
    model.load_weights('my_model_weights.h5')
    

    For more details read Keras documentation

    0 讨论(0)
提交回复
热议问题