AnyLearn
All lessons
AIintermediate

Classification: Logistic Regression and Metrics That Do Not Lie

A classifier outputs a score; you choose where to cut it. Learn how logistic regression and log loss work, why 99% accuracy can be worthless on rare events, how precision, recall and PR curves expose it, and how to pick a threshold from the real costs of each mistake.

Updated · AI-authored, review-gated · how lessons are made

Not signed in: your progress and quiz score won't be saved.
Progress1 / 10

From a score to a probability

Classification predicts a category, but most classifiers first produce a number. Logistic regression, the standard baseline for yes-or-no problems, computes the same weighted sum as linear regression and then squashes it into the range 0 to 1 with the sigmoid function:

z=w⊤x+b,p(y=1∣x)=σ(z)=11+e−zz = w^\top x + b, \qquad p(y = 1 \mid x) = \sigma(z) = \frac{1}{1 + e^{-z}}

A score of z=0z = 0 maps to 0.5, large positive scores approach 1, large negative ones approach 0. Each weight has a readable meaning: increasing feature jj by one unit multiplies the odds p/(1−p)p/(1-p) by ewje^{w_j}.

Key idea: The model's output is a probability-like score, not a decision. Turning 0.37 into "fraud" or "not fraud" is a separate step, and most evaluation mistakes come from treating the two as one.

Full lesson text

All 10 steps on one page, for reading, reference, and search.

Show

1. From a score to a probability

Classification predicts a category, but most classifiers first produce a number. Logistic regression, the standard baseline for yes-or-no problems, computes the same weighted sum as linear regression and then squashes it into the range 0 to 1 with the sigmoid function:

z=w⊤x+b,p(y=1∣x)=σ(z)=11+e−zz = w^\top x + b, \qquad p(y = 1 \mid x) = \sigma(z) = \frac{1}{1 + e^{-z}}

A score of z=0z = 0 maps to 0.5, large positive scores approach 1, large negative ones approach 0. Each weight has a readable meaning: increasing feature jj by one unit multiplies the odds p/(1−p)p/(1-p) by ewje^{w_j}.

Key idea: The model's output is a probability-like score, not a decision. Turning 0.37 into "fraud" or "not fraud" is a separate step, and most evaluation mistakes come from treating the two as one.

2. Log loss: punishing confident mistakes

Logistic regression is trained by minimising log loss, also called cross-entropy:

LogLoss=−1n∑i=1n[yilog⁡pi+(1−yi)log⁡(1−pi)]\text{LogLoss} = -\frac{1}{n}\sum_{i=1}^{n}\Big[y_i \log p_i + (1 - y_i)\log(1 - p_i)\Big]

For each example only one term survives: −log⁡p-\log p when the true label is 1, −log⁡(1−p)-\log(1-p) when it is 0. The penalty grows without limit as a wrong prediction becomes more confident.

True labelPredicted ppLoss
10.90.11
10.60.51
10.12.30
10.014.61

That shape is the point. Log loss rewards a model for being uncertain when it should be, which is why models trained on it, logistic regression included, tend to output probabilities you can use as probabilities. Accuracy cannot tell 0.51 from 0.99; log loss can.

3. The threshold is a business decision

The default rule, predict 1 when p>0.5p > 0.5, silently assumes both mistakes cost the same. They rarely do. If the probabilities are trustworthy, the cheapest rule flags an example when the expected cost of ignoring it exceeds the expected cost of acting:

p⋅CFN>(1−p)⋅CFP⟺p>CFPCFP+CFNp \cdot C_{\text{FN}} > (1 - p) \cdot C_{\text{FP}} \quad\Longleftrightarrow\quad p > \frac{C_{\text{FP}}}{C_{\text{FP}} + C_{\text{FN}}}

Suppose a missed fraud costs 500 and a manual review of a false alarm costs 5. The threshold is 5/505≈0.015 / 505 \approx 0.01: review anything with more than a 1% chance of fraud. For a cancer screen where a false alarm means a follow-up test and a miss can be fatal, the threshold goes lower still. For a spam filter, where losing a real email is the expensive error, it goes up.

In practice: Keep the model and the threshold separate in your code and your conversations. The data scientist owns the scores; the people who bear the costs of each mistake should own the cut-off.

4. A confusion matrix for rare events

Take 10,000 card transactions, of which 100 are fraudulent. A model at its chosen threshold flags 150 of them, and 80 of those are real fraud. Every prediction lands in one of four cells:

Predicted fraudPredicted legitimateTotal
Actually fraud80 (true positives)20 (false negatives)100
Actually legitimate70 (false positives)9,830 (true negatives)9,900
Total1509,85010,000

Every classification metric is some ratio of these four numbers. The trouble is that the 9,830 true negatives dwarf everything else, so any metric that counts them generously will look excellent almost regardless of how the model treats fraud.

Predict first

This model's accuracy is (80 + 9,830) / 10,000 = 99.1%. What accuracy does a "model" get that predicts legitimate for every transaction?

5. Precision, recall and F1

Two ratios ignore the true negatives and so stay honest on rare events:

Precision=TPTP+FP=80150=53.3%,Recall=TPTP+FN=80100=80%\text{Precision} = \frac{TP}{TP + FP} = \frac{80}{150} = 53.3\%, \qquad \text{Recall} = \frac{TP}{TP + FN} = \frac{80}{100} = 80\%

Precision answers "when the model raises an alarm, how often is it right?" Here, barely half the time, which is what the review team experiences. Recall (also called sensitivity, or true positive rate) answers "of the real cases, how many did we catch?"

The two trade against each other through the threshold. Lower it and you catch more fraud but raise more false alarms; raise it and alarms get more reliable while more fraud slips through. F1 summarises both as their harmonic mean:

F1=2⋅Precision⋅RecallPrecision+Recall=2×0.533×0.81.333=0.64F_1 = \frac{2 \cdot \text{Precision} \cdot \text{Recall}}{\text{Precision} + \text{Recall}} = \frac{2 \times 0.533 \times 0.8}{1.333} = 0.64

Gotcha: F1 weights precision and recall equally, which is itself a cost assumption. When a miss costs a hundred times a false alarm, optimise the costed threshold, not F1.

6. Four numbers, one model

Here are four common metrics computed on the same confusion matrix. They describe one model at one threshold.

The same fraud model, four metrics
Metric value (%)02040608010099.199.38053.3AccuracySpecificityRecallPrecision
Source: Computed from this lesson's worked example: 10,000 transactions, 100 fraudulent, 80 true positives, 70 false positives

Specificity, TN/(TN+FP)=9,830/9,900TN / (TN + FP) = 9{,}830 / 9{,}900, is the share of legitimate transactions correctly left alone. Like accuracy it is dominated by the huge negative class, so both sit above 99%. The metrics that concern the rare class, recall and precision, tell a less flattering story.

None of these numbers is wrong. The mistake is choosing the one that answers a question nobody asked. A fraud team's question is usually "of our alerts, how many are real, and how much fraud gets through", which is precision and recall.

7. ROC curves and precision-recall curves

Sweeping the threshold from high to low traces a curve, which summarises the model across every possible cut-off.

ROC curvePrecision-recall curve
AxesTrue positive rate vs false positive ratePrecision vs recall
Uses true negatives?Yes, in the false positive rateNo
Random classifierDiagonal, area 0.5Flat line at the positive rate (0.01 for our fraud data)
Summary numberROC-AUCAverage precision (PR-AUC)
Best forBalanced-ish classes, ranking qualityRare positives, where the alert list is what matters

Our fraud model sits at a false positive rate of 70/9,900=0.7%70 / 9{,}900 = 0.7\% with a true positive rate of 80%, which looks superb on an ROC plot. Its precision of 53% does not.

Saito and Rehmsmeier (PLOS ONE, 2015) examined exactly this and concluded that on strongly imbalanced data the visual interpretability of ROC plots "can be deceptive", while precision-recall plots give an accurate picture of future classification performance, because they measure the fraction of true positives among positive predictions.

8. Choosing a threshold in code

Fit on training data, pick the threshold on validation data, and report once on test data.

from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import (average_precision_score, roc_auc_score,
                             precision_recall_curve, classification_report)

clf = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
clf.fit(X_train, y_train)

val_scores = clf.predict_proba(X_val)[:, 1]
print("ROC-AUC:", roc_auc_score(y_val, val_scores))
print("Average precision:", average_precision_score(y_val, val_scores))

# highest threshold that still catches at least 90% of positives
prec, rec, thr = precision_recall_curve(y_val, val_scores)
t = thr[rec[:-1] >= 0.90].max()

test_pred = clf.predict_proba(X_test)[:, 1] >= t
print(classification_report(y_test, test_pred, digits=3))

precision_recall_curve returns one more precision and recall value than thresholds, hence rec[:-1] to align them. Choosing the threshold on the test set instead would leak exactly as feature selection does.

9. Calibration: can you trust the 0.3?

The costed threshold assumed the probabilities mean what they say: of all transactions scored 0.3, about 30% should be fraud. That property is calibration, and high accuracy does not imply it.

Niculescu-Mizil and Caruana (ICML 2005) compared the probabilities of seven learning methods across seven problems. Neural nets and bagged decision trees gave the best-calibrated probabilities, while SVMs and boosted trees were poorly calibrated despite excellent accuracy and ROC area. Both of their correction methods are standard today:

  • Platt scaling: fit a logistic curve mapping raw scores to probabilities.
  • Isotonic regression: fit a free-form increasing step function; more flexible, needs more data.
from sklearn.calibration import CalibratedClassifierCV
cal = CalibratedClassifierCV(base_model, method="isotonic", cv=5).fit(X_train, y_train)

Try it: Plot a reliability diagram with sklearn.calibration.CalibrationDisplay: bin the predictions, plot mean predicted probability against the observed positive rate, and see how far it strays from the diagonal. The Brier score, the mean of (p−y)2(p - y)^2, summarises the same thing in one number.

10. Which metric for which question

Pick the metric from the decision the model supports, before looking at any results, and write the choice down.

SituationPrimary metricWhy
Classes roughly balanced, errors cost about the sameAccuracySimple and not distorted by imbalance
Rare positives, a team works through the alertsPrecision and recall at the operating threshold, average precisionMeasures the alert list directly
Ranking quality across thresholds, moderate imbalanceROC-AUCThreshold-free and insensitive to the positive rate
Probabilities feed a price, a reserve or an expected costLog loss, Brier score, reliability diagramThe number itself is used, not just the ranking
Costs of each mistake are knownExpected cost at the costed thresholdDirectly the quantity you want to minimise

Key idea: Choosing the metric after seeing which one flatters the model is a form of overfitting to the evaluation. Declaring it first is what makes the reported number mean something.

Check your understanding

The lesson ends with a 5-question quiz. Take it in the player above to see your score.

  1. On 10,000 transactions with 100 frauds, a model has 99.1% accuracy. What is the most important comparison to make first?
    • Against a model with 100% training accuracy
    • Against ROC-AUC
    • Against the 99.0% accuracy of predicting 'legitimate' for everything
    • Against the F1 score of a random model
  2. A model flags 150 transactions, 80 of which are fraud, out of 100 frauds in total. What are its precision and recall?
    • Precision 53.3%, recall 80%
    • Precision 80%, recall 53.3%
    • Precision 80%, recall 80%
    • Precision 99.1%, recall 80%
  3. A missed case costs 500 and a false alarm costs 5. With calibrated probabilities, roughly what threshold minimises expected cost?
    • 0.5
    • 0.99
    • 0.2
    • 0.01
  4. Why can ROC curves look deceptively good on strongly imbalanced data?
    • They cannot be computed when classes are imbalanced
    • The false positive rate divides by the huge number of negatives, so many false alarms still look like a tiny rate
    • They ignore the true positive rate
    • They always show an area of 0.5
  5. According to Niculescu-Mizil and Caruana (2005), which pair of methods produced poorly calibrated probabilities despite excellent accuracy and ROC area?
    • Neural nets and bagged trees
    • Logistic regression and nearest neighbours
    • SVMs and boosted trees
    • Decision stumps and linear regression

Related lessons