Anudocs
Anudocs

Reputation: 686

How to check the predicted output during fitting of the model in Keras?

I am new in Keras and I learned fitting and evaluating the model. After evaluating the model one can see the actual predictions made by model.

I am wondering Is it also possible to see the predictions during fitting in Keras? Till now I cant find any code doing this.

Upvotes: 3

Views: 1857

Answers (1)

Daniel Möller
Daniel Möller

Reputation: 86630

Since this question doesn't specify "epochs", and since using callbacks may represent extra computation, I don't think it's exactly a duplication.

With tensorflow, you can use a custom training loop with eager execution turned on. A simple tutorial for creating a custom training loop: https://www.tensorflow.org/tutorials/eager/custom_training_walkthrough

Basically you will:

#transform your data in to a Dataset:
dataset = tf.data.Dataset.from_tensor_slices(
    (x_train, y_train)).shuffle(some_buffer).batch(batchSize) 
     #the above is buggy in some versions regarding shuffling, you may need to shuffle
     #again between each epoch    


#create an optimizer    
optimizer = tf.keras.optimizers.Adam()

#create an epoch loop:
for e in range(epochs):

    #create a batch loop
    for i, (x, y_true) in enumerate(dataset):

        #create a tape to record actions
        with  tf.GradientTape() as tape:

            #take the model's predictions
            y_pred = model(x)

            #calculate loss
            loss = tf.keras.losses.binary_crossentropy(y_true, y_pred)

        #calculate gradients
        gradients = tape.gradient(loss, model.trainable_weights)

        #apply gradients
        optimizer.apply_gradients(zip(gradients, model.trainable_weights)

You can use the y_pred var for doing anything, including getting its numpy_pred = y_pred.numpy() value.

The tutorial gives some more details about metrics and validation loop.

Upvotes: 2

Related Questions