bhylu.com

Advertisements

AI Precision and Recall

Make denominators and undefined cases visible.

How it works

Precision asks how many predicted positives were actually positive. Recall asks how many observed positives were detected. These answer different questions and can move differently when a threshold changes. When a denominator is zero, return an explicit undefined result or a documented metric policy rather than silently inventing evidence.

Run the code

Try in playground loads this complete standard-library Python example without executing it. Choose Run when ready. Local review uses Python 3.12.14; the existing browser editor uses Pyodide 0.27.7. These small fictional examples need no account, external data, model-provider key or database service.

Download the complete precision-recall.py

Example

precision-recall.py

def ratio(numerator, denominator):
    return None if denominator == 0 else numerator/denominator

tp, fp, fn = 2, 1, 2
print(f"precision: {ratio(tp,tp+fp):.3f}")
print(f"recall: {ratio(tp,tp+fn):.3f}")
print("precision with no predicted positives:", ratio(0,0))

Expected result

precision: 0.667
recall: 0.500
precision with no predicted positives: None

The model found two of four positives, giving recall one half. It predicted three positives, giving precision two thirds. The final None distinguishes no defined precision from observed precision zero. Report support counts alongside rates.

Technical references