Matplotlib
@snippets
Confusion matrix
Custom plotting for confusion matrix, using the class labels and coloring based on frequency:
def plot_confusion_matrix(conf_mat, classes, title='Confusion matrix', cmap=plt.cm.Blues):
"""
This function prints and plots the confusion matrix
"""
plt.imshow(conf_mat, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=90)
plt.yticks(tick_marks, classes)
thresh = conf_mat.max() / 2.
for i, j in itertools.product(range(conf_mat.shape[0]), range(conf_mat.shape[1])):
plt.text(j, i, conf_mat[i, j], horizontalalignment="center",
color="white" if conf_mat[i, j] > thresh else "black")
plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label')
Source: ISMI course.
My own code for plotting confusion matrices, optionally using label encoders.
def visualize_classification(y_true, y_pred, label_encoder=None):
'''
Plot confusion matrix
accepts label encoder to display class names instead of labels
'''
cm = confusion_matrix(y_true, y_pred)
print(cm)
if label_encoder is not None:
# The uncommented lines will produce wrong results if a label is not in the data set
# labels = label_encoder.classes_
# label_mapping = dict(zip(labels, label_encoder.transform(labels)))
targets = list(np.unique(y_true)) # also sorts
labels = label_encoder.inverse_transform(targets)
label_mapping = dict(zip(targets, labels))
print("Label mapping ", label_mapping)
disp = ConfusionMatrixDisplay(confusion_matrix=cm, display_labels=labels)
else:
disp = ConfusionMatrixDisplay(confusion_matrix=cm)
disp.plot(xticks_rotation='vertical')
plt.grid(False)
plt.tight_layout()
plt.show()
plt.clf()
def get_confusion_matrix(y_true, y_pred, label_encoder=None):
cm = confusion_matrix(y_true, y_pred)
if label_encoder is not None:
labels = label_encoder.classes_
label_mapping = dict(zip(labels, label_encoder.transform(labels)))
log.info(f"Label mapping {label_mapping}\n")
log.info(f"{cm}")
return cm