Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python/Keras - How to access each epoch prediction?

Tags:

I'm using Keras to predict a time series. As standard I'm using 20 epochs. I want to check if my model is learning well, by predicting for each one of the 20 epochs.

By using model.predict() I'm getting only one prediction among all epochs (not sure how Keras selects it). I want all predictions, or at least the 10 best.

Would anyone know how to help me?

like image 439
aabujamra Avatar asked Apr 26 '16 12:04

aabujamra


People also ask

How do you save a model after each epoch Keras?

We can use the Keras callback keras. callbacks. ModelCheckpoint() to save the model at its best performing epoch.

How do you connect model input data with predictions for machine learning?

To give inputs to a machine learning model, you have to create a NumPy array, where you have to input the values of the features you used to train your machine learning model. Then we can use that array in the model. predict() method, and at the end, it will give the predicted value as an output based on the inputs.


2 Answers

I think there is a bit of a confusion here.

An epoch is only used while training the neural network, so when training stops (in this case, after the 20th epoch), then the weights correspond to the ones computed on the last epoch.

Keras prints current loss values on the validation set during training after each epoch. If the weights after each epoch are not saved, then they are lost. You can save weights for each epoch with the ModelCheckpoint callback, and then load them back with load_weights on your model.

You can compute your predictions after each training epoch by implementing an appropriate callback by subclassing Callback and calling predict on the model inside the on_epoch_end function.

Then to use it, you instantiate your callback, make a list and use it as keyword argument callbacks to model.fit.

like image 187
Dr. Snoopy Avatar answered Sep 22 '22 07:09

Dr. Snoopy


The following code will do the desired job:

import tensorflow as tf
import keras

# define your custom callback for prediction
class PredictionCallback(tf.keras.callbacks.Callback):    
  def on_epoch_end(self, epoch, logs={}):
    y_pred = self.model.predict(self.validation_data[0])
    print('prediction: {} at epoch: {}'.format(y_pred, epoch))

# ...

# register the callback before training starts
model.fit(X_train, y_train, batch_size=32, epochs=25, 
          validation_data=(X_valid, y_valid), 
          callbacks=[PredictionCallback()])
like image 25
Sandipan Dey Avatar answered Sep 19 '22 07:09

Sandipan Dey