Keras: how to record validation loss

Question:

Note: this is a duplicate question, but I’m not looking for the answer. Rather, how better to find the answer myself.

How do I record loss, training accuracy, testing loss and testing accuracy, from a model, across epochs? I’d like to plot a graph that shows validation loss against each epoch.

I know that the callback object, which can be called in fit(), or maybe model.history has something to do with it, but examining the source and docstrings are just a wall of code to me. Numpy, for instance, typically provides a very small use case as an example of very simple implementation. And yet I know that the answer to this is just a one-liner, because this really is just a question of input.

Asked By: AndreyIto

||

Answers:

As detailed in the doc https://keras.io/models/sequential/#fit, when you call model.fit, it returns a callbacks.History object. You can get loss and other metrics from it:

...
train_history = model.fit(X_train, Y_train,
                    batch_size=batch_size, nb_epoch=nb_epoch,
                    verbose=1, validation_data=(X_test, Y_test))
loss = train_history.history['loss']
val_loss = train_history.history['val_loss']
plt.plot(loss)
plt.plot(val_loss)
plt.legend(['loss', 'val_loss'])
plt.show()
Answered By: Mikael Rousson
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.