Click4Ai

67.

Easy

Implement the **Precision Score** for binary classification.

Formula:

Precision = TP / (TP + FP)

Where:

  • **TP (True Positives):** Predicted 1 AND actually 1
  • **FP (False Positives):** Predicted 1 BUT actually 0
  • Write a function precision(y_true, y_pred) that returns the precision score.

    Example:

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

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

    precision(y_true, y_pred) → 0.8

    **Explanation:** The model predicted positive 5 times (indices 0,3,4,5,7). Of those, 4 were actually positive (TP=4) and 1 was actually negative (FP=1). Precision = 4/5 = 0.8.

    Constraints:

  • Return 0.0 if there are no positive predictions (TP + FP = 0)
  • Return a float between 0.0 and 1.0
  • 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: 0.8
    Test Case 2
    Input: y_true=[1,1,1], y_pred=[1,1,1]
    Expected: 1.0
    Test Case 3
    Input: y_true=[0,0,0], y_pred=[1,1,1]
    Expected: 0.0
    + 2 hidden test cases