← back

Generate a Confusion Matrix for Binary Classification

#75 · Machine Learning · Easy

⊣ Solve on deep-ml.com

Problem

Generate a confusion matrix for binary classification given true labels and predicted labels. The confusion matrix is a 2x2 matrix showing true negatives, false positives, false negatives, and true positives.

Solution

1
2
3
4
5
6
7
def confusion_matrix(y_true, y_pred):
    tp = sum(1 for t, p in zip(y_true, y_pred) if t == 1 and p == 1)
    tn = sum(1 for t, p in zip(y_true, y_pred) if t == 0 and p == 0)
    fp = sum(1 for t, p in zip(y_true, y_pred) if t == 0 and p == 1)
    fn = sum(1 for t, p in zip(y_true, y_pred) if t == 1 and p == 0)

    return [[tn, fp], [fn, tp]]

Explanation

  1. True Negative (TN): both true and predicted are 0.
  2. False Positive (FP): true is 0 but predicted is 1 (Type I error).
  3. False Negative (FN): true is 1 but predicted is 0 (Type II error).
  4. True Positive (TP): both true and predicted are 1.
  5. The matrix is arranged as: [[TN, FP], [FN, TP]], with actual classes as rows and predicted as columns.

Complexity

  • Time: O(n) where n is the number of samples
  • Space: O(1) (the output is always 2x2)