Caojunjie
Caojunjie

Reputation: 69

How to predict after each epoch of training in Keras?

I want to visualize and save the predictions of the the validation data after each training epoch. In a way that I can further use the predictions to analyse them offline.

I know the callback functionality of keras might work, but I would like to understand how to use it in model.fit().

Upvotes: 3

Views: 963

Answers (1)

mrk
mrk

Reputation: 10396

You can write your own callback function and then call it within your model_fit() method

See official Keras documentation here:

class LossHistory(keras.callbacks.Callback):
    def on_train_begin(self, logs={}):
        self.losses = []

    def on_batch_end(self, batch, logs={}):
        self.losses.append(logs.get('loss'))

model = Sequential()
model.add(Dense(10, input_dim=784, kernel_initializer='uniform'))
model.add(Activation('softmax'))
model.compile(loss='categorical_crossentropy', optimizer='rmsprop')

history = LossHistory()
model.fit(x_train, y_train, batch_size=128, epochs=20, verbose=0, callbacks=[history])

print(history.losses)
# outputs
'''
[0.66047596406559383, 0.3547245744908703, ..., 0.25953155204159617, 0.25901699725311789]
'''

Obviously instead of saving losses, and appending them. You can also call model.predict() and save the results within your own callback.

Upvotes: 3

Related Questions