← All questions
Python & DataMedium· Coding Challenges

Write precision, recall, and F1 from scratch, and expla...

Precision is TP / (TP + FP): of everything the model flagged as positive, what fraction actually was. It’s the metric to optimize when false positives are the costly mistake — a spam filter that blocks a real, important email is worse than one that lets a few spam messages through. Recall is TP / (TP + FN): of everything that was actually positive, what fraction did the model catch. It matters when false negatives are the costly mistake — missing an actual cancer case is far worse than a false alarm that gets ruled out on follow-up. F1 is the harmonic mean of the two, useful as a single number when neither error type dominates and you want a balance.

Writing it from scratch is mostly bookkeeping: count true positives, false positives, and false negatives by comparing predicted and actual labels pairwise, then compute the three ratios. The detail that trips people up is guarding every division — if the model predicted zero positives, TP + FP is zero, and dividing by it without a guard throws a ZeroDivisionError instead of returning a sensible 0.

Code playground (Python)