Last active
November 26, 2020 21:12
-
-
Save mmahbub/1bb75ea6a273d7207616e48a581e35a8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def plot_confusion_matrix(cm, | |
target_names, | |
title, | |
cmap=None, | |
normalize=True): | |
accuracy = np.trace(cm) / float(np.sum(cm)) | |
misclass = 1 - accuracy | |
if cmap is None: | |
cmap = plt.get_cmap('Blues') | |
plt.figure(figsize=(8, 6)) | |
plt.imshow(cm, interpolation='nearest', cmap=cmap) | |
plt.title(title) | |
plt.colorbar() | |
if target_names is not None: | |
tick_marks = np.arange(len(target_names)) | |
plt.xticks(tick_marks, target_names, rotation=45) | |
plt.yticks(tick_marks, target_names) | |
if normalize: | |
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] | |
thresh = cm.max() / 1.5 if normalize else cm.max() / 2 | |
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): | |
if normalize: | |
plt.text(j, i, "{:0.4f}".format(cm[i, j]), | |
horizontalalignment="center", | |
color="white" if cm[i, j] > thresh else "black") | |
else: | |
plt.text(j, i, "{:,}".format(cm[i, j]), | |
horizontalalignment="center", | |
color="white" if cm[i, j] > thresh else "black") | |
plt.tight_layout() | |
plt.ylabel('True label') | |
plt.xlabel('Predicted label\naccuracy={:0.4f}; misclass={:0.4f}'.format(accuracy, misclass)) | |
plt.show() | |
from sklearn.metrics import confusion_matrix | |
cm = confusion_matrix(y_test, y_pred) | |
plot_confusion_matrix(cm, | |
normalize = False, | |
target_names = sorted(set(df['author'])), | |
title = "Confusion Matrix") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment