VThomaz
VThomaz

Reputation: 11

How to do a classification_report and a confusion_matrix from the predict_generator output using a segmentation images dataset ? ( Keras Tensorflow)

I have created a classifier for ImageDataGenerator, created using flow_from_directory that loads my dataset and then I perform the training of model and prediction.

My question is how to get metrics (i.e. acc, recall, FPR, etc) from the output of classifier.predict_generator?

If I'm not mistake using the methods confusion_matrix and classification_report would help a lot. The images (.tif files) are found in

/data/test/image ---> RGB images 
/data/test/label ---> Binary mask images
/data/train/image ---> RGB images 
/data/train/label ---> Binary mask images

The images are like the following: RGB image Mask image. The predict_generator method returns images likes this: Predicted image

I already tried codes like the following to generate confusion matrix but not working properly:

predicted_classes_indices = np.argmax(results,axis=1)
labels = (image_generator.class_indices)
labels = dict((v, k) for k, v in labels.items())
predictions = [labels[k] for k in predicted_classes_indices]
cm = confusion_matrix(labels, predicted_classes_indices)

All code:

from redeUnet import get_unet
import matplotlib.pyplot as plt
import numpy as np
import os
from tensorflow.python.keras.preprocessing.image import ImageDataGenerator
from tensorflow.python.keras.models import model_from_json
from tensorflow.python.keras.callbacks import EarlyStopping
from tensorflow.python.keras.callbacks import ModelCheckpoint

PATH_TRAIN = "..\\data\\train\\"

btSize = 4
alt = 256 # image row
larg = 256 # image col
image_folder = 'image'
mask_folder = 'label'
image_color_mode = 'rgb'
mask_color_mode = 'grayscale'
clMode =  'None' #'binary'
epocas = 5 
qtdPatience = 60

'''
Data augmentation
'''
data_gen_args = dict(featurewise_center=False,
                     samplewise_center=False,  # set each sample mean to 0
                     featurewise_std_normalization=False,  # divide inputs by std of the dataset
                     samplewise_std_normalization=False,  # divide each input by its std
                     zca_whitening=False,  # apply ZCA whitening
                     rotation_range=40,  # randomly rotate images in the range (degrees, 0 to 180)
                     zoom_range = 0.2, # Randomly zoom image 
                     width_shift_range=0.2,  # randomly shift images horizontally (fraction of total width)
                     height_shift_range=0.2,  # randomly shift images vertically (fraction of total height)
                     horizontal_flip=True,  # randomly flip images
                     vertical_flip=False,
                     rescale=1./255,
                     validation_split = 0.2)  # randomly flip images
train_image_datagen = ImageDataGenerator(**data_gen_args)
train_mask_datagen = ImageDataGenerator(**data_gen_args)

'''
DATASET prepare and load (20% Validation)
'''
# Load RGB images TRAINING
image_generator = train_image_datagen.flow_from_directory(PATH_TRAIN, 
                                                          classes = [image_folder],
                                                          class_mode = None,
                                                          color_mode = image_color_mode,
                                                          target_size = (larg, alt),
                                                          batch_size = btSize,
                                                          save_to_dir = None,
                                                          shuffle = False,
                                                          subset = 'training',
                                                          seed = 1)
# Load BINARY (Mask) images TRAINING
mask_generator = train_mask_datagen.flow_from_directory(PATH_TRAIN, 
                                                          classes = [mask_folder],
                                                          class_mode = None,
                                                          color_mode = mask_color_mode,
                                                          target_size = (larg, alt),
                                                          batch_size = btSize,
                                                          save_to_dir = None,
                                                          shuffle = False,
                                                          subset = 'training',
                                                          seed = 1)

train_generator = zip(image_generator, mask_generator)

#-------------------------------------------------
# VALIDATION images RGB
valid_image_generator = train_image_datagen.flow_from_directory(PATH_TRAIN, 
                                                          classes = [image_folder],
                                                          class_mode = None,
                                                          color_mode = image_color_mode,
                                                          target_size = (larg, alt),
                                                          batch_size = btSize,
                                                          save_to_dir = None,
                                                          shuffle = False,
                                                          subset = 'validation',
                                                          seed = 1)

# VALIDATION images BINARY (Mask)
valid_mask_generator = train_mask_datagen.flow_from_directory(PATH_TRAIN, 
                                                          classes = [mask_folder],
                                                          class_mode = None,
                                                          color_mode = mask_color_mode,
                                                          target_size = (larg, alt),
                                                          batch_size = btSize,
                                                          save_to_dir = None,
                                                          shuffle = False,
                                                          subset = 'validation',
                                                          seed = 1)
valid_generator = zip(valid_image_generator, valid_mask_generator)
#-------------------------------------------------

'''
RUN TRAINING
'''
# Get UNET
classificador = get_unet(larg, alt, 3)
classificador.compile(optimizer = Adam(lr = 1e-4), loss = 'binary_crossentropy', metrics = ['accuracy']) #metrics = ['accuracy', minhaMetrica])

# Salvando o Modelo e Pesos (Best Model, StopEarly)
es = EarlyStopping(monitor = 'val_loss', mode = 'min', verbose = 1, patience = qtdPatience)
mc = ModelCheckpoint('best_polyp_unet_model.h5', monitor = 'val_loss', verbose = 1, save_best_only = True)


history = classificador.fit_generator(train_generator, 
                            steps_per_epoch = image_generator.n // btSize,
                            validation_data = valid_generator,
                            validation_steps = valid_image_generator.n // btSize,
                            epochs = epocas, callbacks=[es, mc])

resultados = classificador.predict_generator(valid_generator, 
                                           steps = valid_image_generator.n,
                                           verbose = 1)
#-------------------------------------------------

#HOW TO GET THE METRICS?

predicted_classes_indices = np.argmax(resultados,axis=1)
labels = (image_generator.class_indices)
labels = dict((v, k) for k, v in labels.items())
predictions = [labels[k] for k in predicted_classes_indices]
cm = confusion_matrix(ground_truth, predicted_classes)

#-------------------------------------------------

I got an error message in this line: predictions = [labels[k] for k in predicted_classes_indices]

Error: unhashable type: 'numpy.ndarray'

When I checked the output variable of prediction ("resultados") by running this command: resultados.shape.Shows that:

(480, 256, 256, 1)

There is 480 images generated from U-net predictions.

But how I can transform this information to match with "confusion_matrix" or "classification_report" for example? I think that is more difficult because is a segmentation problem.

Any suggestions will be appreciated.

Upvotes: 1

Views: 1696

Answers (1)

Jørgen Kongsro
Jørgen Kongsro

Reputation: 21

You need to flatten your predictions and ground truth (y):

import numpy as np
predictions_flat = predictions.flatten()
y_flat = y.flatten()

Then you can run classification report and confusion matrix on the flattened matrix

from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix


print('Train report', classification_report(y_flat, predictions_flat))
print('Train conf matrix', confusion_matrix(y_flat, predictions_flat))

Upvotes: 2

Related Questions