Search code examples
keras

Keras: Get True labels (y_test) from ImageDataGenerator or predict_generator


I am using ImageDataGenerator().flow_from_directory(...) to generate batches of data from directories.

After the model builds successfully I'd like to get a two column array of True and Predicted class labels. With model.predict_generator(validation_generator, steps=NUM_STEPS) I can get a numpy array of predicted classes. Is it possible to have the predict_generator output the corresponding True class labels?

To add: validation_generator.classes does print the True labels but in the order that they are retrieved from the directory, it doesn't take into account the batching or sample expansion by augmentation.


Solution

  • You can get the prediction labels by:

     y_pred = numpy.rint(predictions)
    

    and you can get the true labels by:

    y_true = validation_generator.classes
    

    You should set shuffle=False in the validation generator before this.

    Finally, you can print confusion matrix by

    print confusion_matrix(y_true, y_pred)