Skip to content

Instantly share code, notes, and snippets.

@daa233
Created November 14, 2017 14:57
Show Gist options
  • Save daa233/e6f237a70a3586904c615334a1fea27c to your computer and use it in GitHub Desktop.
Save daa233/e6f237a70a3586904c615334a1fea27c to your computer and use it in GitHub Desktop.
def plot_confusion_matrix(cm, classes,
normalize=False,
title='Confusion matrix',
cmap=plt.cm.jet):
"""
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
"""
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=45)
plt.yticks(tick_marks, classes)
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
print("Normalized confusion matrix")
else:
print('Confusion matrix, without normalization')
print(cm)
thresh = cm.max() / 2.
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
plt.text(j, i, '',
horizontalalignment="center",
color="white" if cm[i, j] > thresh else "black")
plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label')
confusion_matrix = np.array([[4, 1], [2, 8]])
classes = [0, 1]
plot_confusion_matrix(confusion_matrix, classes)
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment