Learning path: Classify and Evaluate: Logistic Regression to Cross-Validation · Step 4 of 7
Precision, Recall and F1 Score: Two Questions and One Balance
Precision asks whether the model's yes is right; recall asks whether it found them all. Worked by hand and with scikit-learn on a fraud model with 99.4% accuracy and only 0.42 recall.
What you will learn
- Compute precision, recall and specificity from the four boxes
- Explain why F1 is lower than the plain average
- Read classification_report, including macro and weighted averages
- Pick the score that matches the costly mistake
Before you start
- Why Accuracy Lies: The Confusion Matrix
You go fishing in a small lake with 11 fish and one old boot. You pull up the net: three fish and the boot.
Two different questions. How much of the catch is fish? Three out of four. Pretty good. How many of the lake's fish did we catch? Three out of eleven. Eight got away. The same net looks great on one question and poor on the other.
The first question is precision. The second is recall. Let's compute both for the fraud model from Why Accuracy Lies, the one with 99.4% accuracy.
The four boxes
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import confusion_matrix
df = pd.read_csv("payments.csv")
X, y = df.drop(columns="fraud"), df["fraud"]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=42)
model = LogisticRegression().fit(X_train, y_train)
y_pred = model.predict(X_test)
cm = confusion_matrix(y_test, y_pred)
tn, fp, fn, tp = cm.ravel()
print("TN", tn, "FP", fp, "FN", fn, "TP", tp)
TN 4949 FP 1 FN 29 TP 21
Precision reads a column, recall reads a row
precision = tp / (tp + fp)
recall = tp / (tp + fn)
specificity = tn / (tn + fp)
print(round(precision, 3), round(recall, 3))
print(round(specificity, 4))
0.955 0.42
0.9998
- Precision 0.955: when the model shouts fraud, it's right 95.5% of the time.
- Recall 0.42: it catches only 42% of the frauds. Recall is also called sensitivity. This is the weak spot.
- Specificity 0.9998: of all normal payments, almost all were left alone.
F1 balances the two
F1 puts precision and recall into one number:
F1 = 2 × precision × recall / (precision + recall)
f1 = 2 * precision * recall / (precision + recall)
print(round(f1, 3))
0.583
Compare it with a plain average:
plain = (precision + recall) / 2
print(round(plain, 3))
0.687
Why is F1 lower? It's pulled towards the weaker score. A model can't hide a bad recall behind a great precision. F1 is a harsh average.
The same with scikit-learn
from sklearn import metrics
p = metrics.precision_score(y_test, y_pred)
r = metrics.recall_score(y_test, y_pred)
f = metrics.f1_score(y_test, y_pred)
print(round(p, 3), round(r, 3), round(f, 3))
0.955 0.42 0.583
The same numbers we worked out by hand. Fraud, the label 1, counts as the positive class, so that's the class these functions score.
Everything at once: classification_report
report = metrics.classification_report(
y_test, y_pred, digits=3,
target_names=["normal", "fraud"])
print(report)
precision recall f1-score support
normal 0.994 1.000 0.997 4950
fraud 0.955 0.420 0.583 50
accuracy 0.994 5000
macro avg 0.974 0.710 0.790 5000
weighted avg 0.994 0.994 0.993 5000
One row per class. For normal, everything is near 1; its recall is the specificity we just computed. Support is the number of rows: 4,950 normal, 50 fraud.
Macro counts classes, weighted counts rows
| Average | How | F1 |
|---|---|---|
| Macro | every class counts the same: (0.997 + 0.583) / 2 | 0.790 |
| Weighted | every row counts the same, so 4,950 normal rows drown 50 frauds | 0.993 |
Macro shows how the rare class is doing; weighted mostly shows the big one. With three or more classes you read these two rows the same way.
Which score should you care about?
| Costly mistake | Example | Favour |
|---|---|---|
| Missing a real case (FN) | fraud, illness screening | recall |
| A false alarm (FP) | spam filter sending good mail to spam | precision |
| Both hurt, class is rare | many real problems | F1 and the macro average |
For our fraud model, accuracy is 99.4% but recall is 0.42. That's the real problem. There's no best score, only the one that fits the cost of a mistake.
Common mistakes
- Reading the weighted average on rare-class data. 0.993 hides a fraud F1 of 0.583.
- Swapping the formulas. Precision divides by everything predicted positive; recall divides by everything actually positive.
- Forgetting which class is positive.
precision_scorescores label 1 by default. Make sure 1 is the class you care about.
Quick recap
| Score | Question | Fraud model |
|---|---|---|
| Precision | Is its yes right? | 0.955 |
| Recall (sensitivity) | Did it find them all? | 0.42 |
| Specificity | Were the normal ones left alone? | 0.9998 |
| F1 | Harsh balance of the two | 0.583 |
Try it yourself
Run classification_report on DummyClassifier(strategy="most_frequent"). What are its fraud recall and its macro F1? Next, raise the recall by moving the cut: ROC, AUC and Choosing a Threshold.
The notebook and payments.csv are in the StudyEasy AI Community, free to join.
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →Why Accuracy Lies: The Confusion Matrix, Baselines and Type I/II Errors
Next →ROC Curve, AUC and Choosing a Classification Threshold
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)Related articles
Linear Regression and the Cost Function: Draw a Line, Score It
Draw a straight line through six kids' ages and weights, measure every miss, and turn the misses into one score, the mean squared error. Then let np.polyfit find the line with the lowest score.
Gradient Descent Explained: Feel the Slope, Step Downhill
Instead of handing over the best line, let the computer walk to it: measure the slope of the cost, step downhill with a learning rate, repeat. Shown step by step on six kids' ages and weights.
Linear Regression in scikit-learn: Fit, Predict and Read the Price Tags
Predict a yearly medical bill with scikit-learn's LinearRegression: first from age alone, then from every column inside a pipeline. Each coefficient reads like a price tag, and smoker_yes is by far the biggest.
Regression Metrics: MAE, RMSE, R-squared and the Baseline to Beat
Score a regression model honestly: MAE, MSE and RMSE from four darts, then the insurance model on 268 test people, a DummyRegressor baseline to beat, R-squared and adjusted R-squared, and a residual plot.