1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| import numpy as np import matplotlib.pyplot as plt
def plot_confusion_matrix(cm, classes, title='Confusion Matrix'): plt.figure(figsize=(8,6)) plt.imshow(cm, interpolation='nearest', cmap=plt.cm.Blues) plt.title(title, fontsize=14) plt.colorbar() tick_marks = np.arange(len(classes)) plt.xticks(tick_marks, classes, rotation=45) plt.yticks(tick_marks, classes) for i in range(cm.shape[0]): for j in range(cm.shape[1]): plt.text(j, i, format(cm[i, j], 'd'), ha="center", va="center", color="white" if cm[i, j] > cm.max()/2 else "black")
plt.ylabel('True Label', fontsize=12) plt.xlabel('Predicted Label', fontsize=12) plt.tight_layout()
true_labels = [0,1,0,1,1,0,0,1] pred_labels = [0,1,0,0,1,0,1,1] classes = ['Negative', 'Positive']
from sklearn.metrics import confusion_matrix cm = confusion_matrix(true_labels, pred_labels)
plot_confusion_matrix(cm, classes) plt.show()
|