nikos99n commited on
Commit
2d9d6c4
·
1 Parent(s): 23831eb

add normalized confusion matrices

Browse files
Files changed (1) hide show
  1. src/plots.py +25 -2
src/plots.py CHANGED
@@ -8,13 +8,16 @@ from . import config
8
 
9
 
10
  def plot_confusion_matrix(y_true, y_pred, classes, model_name):
11
- """Generates and saves a confusion matrix heatmap."""
 
 
12
  cm = confusion_matrix(y_true, y_pred)
13
 
 
14
  plt.figure(figsize=(10, 8))
15
  sns.heatmap(cm, annot=True, fmt='d', cmap='Blues',
16
  xticklabels=classes, yticklabels=classes)
17
- plt.title(f"{model_name} Confusion Matrix")
18
  plt.ylabel('True Label')
19
  plt.xlabel('Predicted Label')
20
  plt.tight_layout()
@@ -23,6 +26,26 @@ def plot_confusion_matrix(y_true, y_pred, classes, model_name):
23
  plt.savefig(os.path.join(config.MODEL_DIR, filename))
24
  plt.close()
25
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
 
27
  def plot_multiclass_roc(model, X_test, y_test, classes, model_name):
28
  """Generates and saves a Multi-class ROC Curve."""
 
8
 
9
 
10
  def plot_confusion_matrix(y_true, y_pred, classes, model_name):
11
+ """Generates and saves both Raw and Normalized confusion matrix heatmaps."""
12
+
13
+ # 1. Calculate Raw Matrix
14
  cm = confusion_matrix(y_true, y_pred)
15
 
16
+ # Plot Raw Counts
17
  plt.figure(figsize=(10, 8))
18
  sns.heatmap(cm, annot=True, fmt='d', cmap='Blues',
19
  xticklabels=classes, yticklabels=classes)
20
+ plt.title(f"{model_name} Confusion Matrix (Counts)")
21
  plt.ylabel('True Label')
22
  plt.xlabel('Predicted Label')
23
  plt.tight_layout()
 
26
  plt.savefig(os.path.join(config.MODEL_DIR, filename))
27
  plt.close()
28
 
29
+ # 2. Calculate Normalized Matrix
30
+ # Divide each row element by the sum of that row (True Label count)
31
+ cm_norm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
32
+ # Replace NaN with 0 (safe guard for empty classes)
33
+ cm_norm = np.nan_to_num(cm_norm)
34
+
35
+ # Plot Normalized Percentages
36
+ plt.figure(figsize=(10, 8))
37
+ # Use fmt='.2f' to show 2 decimal places (e.g., 0.95)
38
+ sns.heatmap(cm_norm, annot=True, fmt='.2f', cmap='Greens',
39
+ xticklabels=classes, yticklabels=classes)
40
+ plt.title(f"{model_name} Confusion Matrix (Normalized)")
41
+ plt.ylabel('True Label')
42
+ plt.xlabel('Predicted Label')
43
+ plt.tight_layout()
44
+
45
+ filename_norm = f"{model_name.lower()}_confusion_matrix_normalized.png"
46
+ plt.savefig(os.path.join(config.MODEL_DIR, filename_norm))
47
+ plt.close()
48
+
49
 
50
  def plot_multiclass_roc(model, X_test, y_test, classes, model_name):
51
  """Generates and saves a Multi-class ROC Curve."""