How do I input a list to plot a Confusion Matrix?

Viewed 36

I have defined a function plot_confusion_matrix(cm, class_names, filename) which returns a matplotlib figure containing the plotted confusion matrix.

My args are:

  1. cm (array, shape = [n, n]): a confusion matrix of integer classes,
  2. class_names (array, shape = [n]): String names of the integer classes
  3. The filename

The code is as follows:

figure = plt.figure(figsize=(8, 8))
plt.imshow(cm, interpolation='nearest', cmap=plt.cm.Blues)
plt.title("Confusion matrix")
plt.colorbar()
tick_marks = np.arange(len(class_names))
plt.xticks(tick_marks, class_names, rotation=45)
plt.yticks(tick_marks, class_names)

# Compute the labels from the normalized confusion matrix.
labels = np.around(cm.astype('float') / cm.sum(axis=1)[:, np.newaxis], decimals=2)

# Use white text if squares are dark; otherwise black.
threshold = cm.max() / 2.
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
    color = "white" if cm[i, j] > threshold else "black"
    plt.text(j, i, labels[i, j], horizontalalignment="center", color=color)

plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label')
    
plt.savefig(filename)

I tried it using

plot_confusion_matrix(health_cm,class_names=self.healthclass,filename=f'test_results/HealthConfusion.png',)

my self.healthclass is ['Healthy', 'Faulty']

However I keep getting the error

TypeError: plot_confusion_matrix() got multiple values for argument 'class_names'

I am confused.....

1 Answers

I should have specified self as the first argument because it was in a class. I forgot to do so, hence the problem. I have rectified that.

Related