Python / Python Mathematical Intuition and Scikit Learn Interview Questions
Explain the mathematical tradeoff between precision and recall, and why F1 score is the harmonic mean rather than the arithmetic mean.
Precision is TP/(TP+FP) — of everything predicted positive, what fraction was actually positive. Recall is TP/(TP+FN) — of everything that was actually positive, what fraction did the model find. Adjusting the classification threshold creates an inherent tradeoff: lowering the threshold to capture more true positives (raising recall) inevitably captures more false positives too (lowering precision), and vice versa.
F1 score is the harmonic mean of precision and recall: F1 = 2·(P·R)/(P+R), rather than the simple arithmetic mean (P+R)/2. The harmonic mean punishes extreme imbalance between the two values much more heavily — if precision is 1.0 and recall is 0.0, the arithmetic mean gives a deceptively decent 0.5, while the harmonic mean correctly gives 0.0, since a model with zero recall is useless regardless of how precise its rare positive predictions are.
from sklearn.metrics import precision_score, recall_score, f1_score from sklearn.metrics import precision_recall_curve import numpy as np # Demonstrating why harmonic mean is preferred precision, recall = 1.0, 0.01 # extreme imbalance arithmetic_mean = (precision + recall) / 2 harmonic_mean = 2 * (precision * recall) / (precision + recall) print(f'Arithmetic: {arithmetic_mean:.3f}') # 0.505 â misleadingly good print(f'Harmonic: {harmonic_mean:.3f}') # 0.020 â correctly reflects uselessness # Using scikit-learn metrics y_true = [1, 0, 1, 1, 0, 1, 0, 0] y_pred = [1, 0, 0, 1, 0, 1, 1, 0] print('Precision:', precision_score(y_true, y_pred)) print('Recall:', recall_score(y_true, y_pred)) print('F1:', f1_score(y_true, y_pred)) # Tuning threshold to favor one metric over the other y_scores = [0.9, 0.2, 0.4, 0.85, 0.1, 0.7, 0.55, 0.3] precisions, recalls, thresholds = precision_recall_curve(y_true, y_scores)
More Related questions...