Click4Ai

70.

Easy

Implement a **Confusion Matrix** for binary classification.

A confusion matrix is a 2x2 table that summarizes the performance of a classifier:

Predicted 0 Predicted 1

Actual 0 [ TN , FP ]

Actual 1 [ FN , TP ]

Where:

  • **TN:** True Negatives (predicted 0, actually 0)
  • **FP:** False Positives (predicted 1, actually 0)
  • **FN:** False Negatives (predicted 0, actually 1)
  • **TP:** True Positives (predicted 1, actually 1)
  • Write a function confusion_matrix(y_true, y_pred) that returns a 2x2 numpy array.

    Example:

    y_true = [1, 0, 1, 1, 0, 1, 0, 1]

    y_pred = [1, 0, 0, 1, 1, 1, 0, 1]

    confusion_matrix(y_true, y_pred) → [[2, 1], [1, 4]]

    Constraints:

  • Return a numpy array of shape (2, 2) with integer counts
  • Layout: [[TN, FP], [FN, TP]]
  • Test Cases

    Test Case 1
    Input: y_true=[1,0,1,1,0,1,0,1], y_pred=[1,0,0,1,1,1,0,1]
    Expected: [[2,1],[1,4]]
    Test Case 2
    Input: y_true=[1,1,1], y_pred=[1,1,1]
    Expected: [[0,0],[0,3]]
    Test Case 3
    Input: y_true=[0,0,0], y_pred=[0,0,0]
    Expected: [[3,0],[0,0]]
    + 2 hidden test cases