Measure Precision and Recall for an Imbalanced Classifier
Compare accuracy, precision and recall using the same 100 fictional labelled examples and account for each false alert and missed positive.
Difficulty Beginner
Prepare a fixture
Use Python 3 in a virtual environment with scikit-learn. A CPU workstation is enough. Treat class 1 as the event you want to detect. The first ten labels are positive and the other 90 are negative.
from sklearn.metrics import (
accuracy_score, confusion_matrix, precision_score, recall_score,
)
actual = [1] * 10 + [0] * 90
all_negative = [0] * 100
candidate = [1] * 7 + [0] * 3 + [1] * 8 + [0] * 82
for name, predicted in [("Baseline", all_negative), ("Candidate", candidate)]:
tn, fp, fn, tp = confusion_matrix(actual, predicted, labels=[0, 1]).ravel()
print(name, {"TN": tn, "FP": fp, "FN": fn, "TP": tp})
print("accuracy", accuracy_score(actual, predicted))
print("precision", precision_score(actual, predicted, zero_division=0))
print("recall", recall_score(actual, predicted, zero_division=0))
Interpret the output
The baseline scores 0.90 for accuracy and detects zero positive examples. Its precision is undefined mathematically, and the explicit zero_division setting reports that case as zero. The candidate scores 0.89 accuracy with seven detections out of ten positives and seven correct alerts out of fifteen. Recall measures the proportion of positives found. Precision measures the proportion of alerts that were correct.
Troubleshooting and practice
Mismatched array lengths usually indicate rows were removed during prediction or joined incorrectly. Align by a stable sample identifier before measuring. Change one false positive to a true negative and verify that precision improves while recall remains fixed. Then change a false negative to a true positive and calculate the new fractions by hand. Record the number of examples alongside each metric. Small fixtures illustrate arithmetic. Real evaluation needs held-out data and appropriate review of error costs.