Last active
July 16, 2020 11:08
-
-
Save sadimanna/d2be7524327ccd6e3c3c04385798ec71 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
| # class_labels should contain names of both the classes | |
| def plot_confusion_matrix(y_true,y_pred,class_labels): | |
| cm = np.zeros((2,2)) | |
| cm[0,0] = np.sum((y_true==1) & (y_pred>0.5)) #TP | |
| cm[0,1] = np.sum((y_true==0) & (y_pred>0.5)) #FP | |
| cm[1,0] = np.sum((y_true==1) & (y_pred<0.5)) #FN | |
| cm[1,1] = np.sum((y_true==0) & (y_pred<0.5)) #TN | |
| cm_sum = np.sum(cm, axis=1, keepdims=True) | |
| cm_perc = cm / cm_sum.astype(float) * 100 | |
| annot = np.empty_like(cm).astype(str) | |
| nrows, ncols = cm.shape | |
| for i in range(nrows): | |
| for j in range(ncols): | |
| c = cm[i, j] | |
| p = cm_perc[i, j] | |
| if i == j: | |
| s = cm_sum[i] | |
| annot[i, j] = '%.1f%%\n%d/%d' % (p, c, s) | |
| elif c == 0: | |
| annot[i, j] = '' | |
| else: | |
| annot[i, j] = '%.1f%%\n%d' % (p, c) | |
| if class_labels==None: | |
| class_labels = ['1','0'] | |
| cm = pd.DataFrame(cm, index=class_labels, columns=class_labels) | |
| cm.index.name = 'Actual' | |
| cm.columns.name = 'Predicted' | |
| fig, ax = plt.subplots(figsize=(6,6)) | |
| sns.set(font_scale=3.0) # Adjust to fit | |
| sns.heatmap(cm, cmap= "YlGnBu", annot=annot, fmt='', ax=ax) | |
| ax.tick_params(axis='both', which='major', labelsize=10) # Adjust to fit | |
| ax.xaxis.set_ticklabels(class_labels) | |
| ax.yaxis.set_ticklabels(class_labels) | |
| fig.savefig('Confusion_Matrix.png') | |
| plt.show() |
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
| #Given y as one-hot vector and pred as logits | |
| plot_confusion_matrix(np.where(y==1)[1],np.argmax(pred,axis=1),class_labels) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment