pythonmachine-learningdeep-learningclassificationvgg-net

NameError: name 'plot_confusion_matrix' is not defined


I am trying to make a classification model using VGG16 but at the end of the project I faced an error for getting the Confusion Matrix. Below the codes are given,

Imported packages and modules are:

import os
import keras
import numpy as np
import tensorflow as tf
from keras.models import Model
import matplotlib.pyplot as plt
from keras.optimizers import Adam
from keras.applications import MobileNet
from sklearn.metrics import confusion_matrix
from keras.layers.core import Dense, Activation
from keras.metrics import categorical_crossentropy
from sklearn.model_selection import train_test_split
from keras.preprocessing.image import ImageDataGenerator
from keras.applications.mobilenet import preprocess_input
from tensorflow.keras.preprocessing import image_dataset_from_directory

N.B: For shorting I just skipping of dataset linked

Below define VGG16:

vgg16_model = keras.applications.vgg16.VGG16()
vgg16_model.summary()

Now, Define the model:

model = Sequential()
for layer in vgg16_model.layers:
  model.add(layer)

for layer in model.layers:
  layer.trainable = False

model.add(Dense(2, activation='softmax'))

Compile the model:

model.compile(Adam(lr=.0001), loss='categorical_crossentropy', metrics=['accuracy'])

Fit the model:

model.fit_generator(train_batches, steps_per_epoch=4, validation_data=valid_batches, validation_steps=4, epochs=10, verbose=2)

Now for confusion matrix:

test_imgs, test_labels = next(test_batches)
plots(test_imgs, titles=test_labels)
test_labels = test_labels[:,0] 
predictions = model.predict_generator(test_batches, steps=1, verbose=0)
cm = confusion_matrix(test_labels, np.round(predictions[:,0]))

Below I faced an error, Please concern below code,

cm_plot_labels = ['diseaseAffectedEggplant','freshEggplant']
plot_confusion_matrix(cm, cm_plot_labels, title="Confusion Matrix")   // this line, I faced an error

The Error is given below,

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-28-43b96d543746> in <module>()
      1 cm_plot_labels = ['diseaseAffectedEggplant','freshEggplant']
----> 2 plot_confusion_matrix(cm, cm_plot_labels, title="Confusion Matrix")

NameError: name 'plot_confusion_matrix' is not defined

Solution

  • You need to import plot_confusion_matrix from the sklearn.metrics module:

    from sklearn.metrics import plot_confusion_matrix
    

    See documentation.


    Function plot_confusion_matrix was deprecated in 1.0 and was removed in 1.2. Use one of the class methods: ConfusionMatrixDisplay.from_predictions or ConfusionMatrixDisplay.from_estimator.

    See documentation