Compute precision, recall and F1 from predictions

Accuracy hides a lot when one class is rare. Precision asks how many flagged items were right; recall asks how many right items you flagged; F1 is their harmonic mean.

Write prf1(y_true, y_pred) for binary 0/1 lists. Return (precision, recall, f1). Define any 0 / 0 as 0.0.

Signaturedef prf1(y_true, y_pred)

Understand the idea

When positives are rare, accuracy can look great even if the model never finds them. Precision asks: of everything I flagged, how much was right? Recall asks: of everything truly positive, how much did I flag? F1 combines them with a harmonic mean, which stays low if either one is low. Think of a fishing net: precision is how many caught things are fish, recall is how many fish you caught. Worked example: y_true = [1, 1, 0, 0, 1], y_pred = [1, 0, 0, 0, 0]. True positives = 1, false positives = 0, false negatives = 2. Precision = 1 / 1 = 1.0. Recall = 1 / 3 = 0.333. F1 = 2 x 1 x 0.333 / (1 + 0.333) = 0.5, while a plain average would give 0.667. Rule: P = TP / (TP + FP), R = TP / (TP + FN), F1 = 2PR / (P + R), with any 0 / 0 treated as 0.0. These metrics are standard for moderation, spam and retrieval classifiers.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: mixedprf1([1, 0, 1, 1, 0, 0, 1], [1, 1, 0, 1, 0, 0, 0])
  • Sample 2: never predicts positiveprf1([1, 0, 1], [0, 0, 0])
  • Test 3: perfectprf1([0, 1, 1], [0, 1, 1])