Single logo
  • Courses
  • Blog
  • About
Join for freeJoin free
Learning pathClassify and Evaluate: Logistic Regression to Cross-Validation
  1. 1
    Logistic Regression and the Sigmoid: Score, Squash, Decide
  2. 2
    Logistic Regression in scikit-learn: predict, predict_proba and Softmax
  3. 3
    Why Accuracy Lies: The Confusion Matrix, Baselines and Type I/II Errors
  4. 4
    Precision, Recall and F1 Score: Two Questions and One Balance
  5. 5
    ROC Curve, AUC and Choosing a Classification Threshold
  6. 6
    Handling Imbalanced Data: class_weight, SMOTE and the Resampling Leak
  7. 7
    Cross-Validation: KFold, StratifiedKFold, cross_val_score and cross_validate
  1. Blog
  2. /
  3. Machine Learning
  4. /
  5. Supervised Learning

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.

Chaand Sheikh

·27 November 2026Classification and Evaluation

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 and recall on the confusion matrix pred. normal pred. fraud actual normal actual fraud TN 4,949 FP 1 FN 29 TP 21 Precision (column) TP / (TP + FP) 21 / 22 = 0.955 Recall (row) TP / (TP + FN) 21 / 50 = 0.42 Specificity: TN / (TN + FP) = 4,949 / 4,950 = 0.9998
Precision looks down the predicted-fraud column: of everything flagged, how much was fraud? Recall looks along the actual-fraud row: of all real frauds, how many were caught?
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

AverageHowF1
Macroevery class counts the same: (0.997 + 0.583) / 20.790
Weightedevery row counts the same, so 4,950 normal rows drown 50 frauds0.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 mistakeExampleFavour
Missing a real case (FN)fraud, illness screeningrecall
A false alarm (FP)spam filter sending good mail to spamprecision
Both hurt, class is raremany real problemsF1 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_score scores label 1 by default. Make sure 1 is the class you care about.

Quick recap

ScoreQuestionFraud model
PrecisionIs its yes right?0.955
Recall (sensitivity)Did it find them all?0.42
SpecificityWere the normal ones left alone?0.9998
F1Harsh balance of the two0.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 →
← Previous
Why Accuracy Lies: The Confusion Matrix, Baselines and Type I/II Errors
Next →
ROC Curve, AUC and Choosing a Classification Threshold
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool
Go deeper with a course

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.

On this page
  • The four boxes
  • Precision reads a column, recall reads a row
  • F1 balances the two
  • The same with scikit-learn
  • Everything at once: classification_report
  • Macro counts classes, weighted counts rows
  • Which score should you care about?
  • Common mistakes
  • Quick recap
  • Try it yourself
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool
Go deeper with a course

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.