Python – How to predict after each training epoch in Keras?

How to predict after each training epoch in Keras?… here is a solution to the problem.

How to predict after each training epoch in Keras?

I want to visualize and save predictions for validation data after each training epoch. In a way, I can further use predictions to analyze them offline.

I know

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

Solution

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

See the 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 not saving losses, but adding losses. You can also call model.predict() and save the result in your own callback.

Related Problems and Solutions