SafeZone AI Learn
Learn/ Machine Learning/ Supervised Learning · lesson 3 of 8

Logistic regression and calibration

From Bernoulli likelihood to cross-entropy, the geometry of the linear decision boundary, why the threshold is a business decision rather than part of the model — and what it takes for predicted probabilities to mean anything.

Classification’s workhorse is routinely introduced as “regression squashed through a sigmoid,” which gets the formula right and the ideas backwards. Logistic regression is a probability model fitted by maximum likelihood; the sigmoid, the cross-entropy loss, the gradient’s beautiful form, and the entire calibration story all fall out of that starting point rather than being bolted on.

The model: log-odds are linear

For binary y{0,1}y \in \{0, 1\}, model the conditional probability:

p(x)  =  Pr(y=1x)  =  σ(βx),σ(z)=11+ez.p(x) \;=\; \Pr(y = 1 \mid x) \;=\; \sigma(\beta^\top x), \qquad \sigma(z) = \frac{1}{1 + e^{-z}} .

The honest reading inverts the sigmoid: the model asserts that the log-odds are linear,

logp(x)1p(x)=βx,\log \frac{p(x)}{1 - p(x)} = \beta^\top x ,

which gives every coefficient a precise meaning — one unit of xjx_j adds βj\beta_j to the log-odds, i.e. multiplies the odds by eβje^{\beta_j} — and makes the geometry immediate: p(x)=12p(x) = \tfrac12 exactly on the hyperplane βx=0\beta^\top x = 0. The decision boundary is linear, always; the sigmoid curves probabilities, never the boundary. Probability contours are parallel hyperplanes, packed tightly when β\lVert\beta\rVert is large (a confident, sharp model) and spread out when it is small.

The loss: maximum likelihood becomes cross-entropy

Each observation is a Bernoulli draw, so the likelihood of the data set is ipiyi(1pi)1yi\prod_i p_i^{y_i} (1 - p_i)^{1 - y_i}. Maximizing its log = minimizing the negative log-likelihood:

L(β)=i=1n[yilogpi+(1yi)log(1pi)]\mathcal{L}(\beta) = -\sum_{i=1}^n \Big[ y_i \log p_i + (1 - y_i)\log(1 - p_i) \Big]

— the cross-entropy (log) loss, not chosen for convenience but derived from the probability model. Differentiate (the sigmoid’s identity σ=σ(1σ)\sigma' = \sigma(1-\sigma) collapses everything):

βL=i=1n(piyi)xi=X(py).\nabla_\beta \mathcal{L} = \sum_{i=1}^n (p_i - y_i)\, x_i = X^\top(p - y) .

Identical in shape to least squares’ X(y^y)X^\top(\hat y - y)prediction error times features — except pp depends nonlinearly on β\beta, so there is no closed form and we are back in the Optimization module: L\mathcal{L} is convex (its Hessian XWXX^\top W X with W=diag(pi(1pi))W = \mathrm{diag}(p_i(1-p_i)) is PSD), so gradient descent or Newton’s method (a.k.a. iteratively reweighted least squares) finds the global optimum. Two practical notes with mathematical roots: on linearly separable data the MLE does not exist — β\lVert\beta\rVert \to \infty as the loss chases certainty — so an 2\ell_2 penalty is not optional hygiene but what makes the optimum finite; and that same penalty is why library defaults (sklearn’s C) regularize whether you asked or not.

Why not just fit least squares on the labels? Squared loss on 0/1 targets penalizes confidently correct predictions (pp pushed past the label), and its linear-model version happily predicts probabilities outside [0,1][0,1]. Cross-entropy’s asymmetric punishment — a confidently wrong prediction costs log(tiny)-\log(\text{tiny}), i.e. an unbounded loss — is exactly the incentive structure a probability estimate should face. That property has a name worth knowing: log loss is a proper scoring rule, minimized in expectation only by the true conditional probability.

The threshold is not part of the model

The fitted model outputs p(x)p(x). Turning that into a decision requires a threshold tt — predict 1 when p(x)tp(x) \ge t — and nothing in the fitting procedure chose t=0.5t = 0.5. Decision theory does: predicting 1 is optimal when expected cost is lower,

t=cFPcFP+cFN,t^\ast = \frac{c_{\text{FP}}}{c_{\text{FP}} + c_{\text{FN}}} ,

so 0.5 is right only when false positives and false negatives cost the same — almost never true in fraud, medicine, or moderation. Geometrically, changing tt slides the decision hyperplane parallel to itself through the probability contours; it never rotates it. Separating “fit the best probability model” from “choose the operating point” is the clean mental model, and the evaluation lesson builds ROC analysis on exactly this separation.

On the blobs, the boundary is a clean line and the probability shading fades smoothly across it — that gradient is the sigmoid, seen from above. Slide the threshold: the line translates parallel to itself, trading one error type for the other (watch train/test accuracy respond). Now switch to moons or circles: the best line a linear log-odds model can draw fails in a structured way — no threshold fixes a boundary of the wrong shape. Two escapes exist: engineer nonlinear features (last lesson’s polynomial trick applies verbatim), or change model family — which is precisely where the next two lessons go.

Calibration: do the probabilities mean anything?

Accuracy asks “is ptp \ge t on the right side?” Calibration asks something stronger: among all cases where the model said 70%, does the event happen 70% of the time? Formally, Pr(y=1p(x)=q)=q\Pr(y=1 \mid p(x) = q) = q. A model can be accurate yet badly calibrated (confidence systematically inflated), and calibrated yet weakly accurate (honest but vague). The standard diagnostic is the reliability diagram — bin predictions, plot observed frequency against mean predicted probability, hope for the diagonal — summarized by expected calibration error (ECE) or, better, by proper scoring rules: log loss and the Brier score 1ni(piyi)2\tfrac1n\sum_i (p_i - y_i)^2, both of which reward honesty about uncertainty, not just correct ordering.

Field notes worth carrying: logistic regression trained on log loss is typically well-calibrated in-distribution (it is optimizing a proper score); max-margin and ensemble methods — SVMs, boosted trees, bagged forests — typically push probability mass away from 0 and 1, an under-confident sigmoidal distortion at the extremes (Niculescu-Mizil & Caruana’s classic measurement), which is exactly why a sigmoid is the corrective: Platt scaling (fit a 1-D logistic regression on the model’s scores — yes, logistic regression as a patch for other models) or isotonic regression (fit a monotone step function; more flexible, needs more data). Modern deep networks are miscalibrated in the opposite direction — over-confident — and temperature scaling, Platt’s one-parameter cousin, softens them. And calibration is fragile under distribution shift and under resampling: if you balanced your classes for training, your probabilities are calibrated to the balanced world, not the real one — correct the intercept by the log of the sampling ratio, or recalibrate on unresampled data.

from sklearn.linear_model import LogisticRegression
from sklearn.calibration import calibration_curve

clf = LogisticRegression(C=1.0).fit(X_tr, y_tr)          # C = 1/λ
prob = clf.predict_proba(X_te)[:, 1]
frac_pos, mean_pred = calibration_curve(y_te, prob, n_bins=10)
# plot frac_pos vs mean_pred against the diagonal = reliability diagram

Exercises

Work these before the next lesson

  1. Derive L=X(py)\nabla \mathcal{L} = X^\top(p - y) from the log-likelihood, using σ(z)=σ(z)(1σ(z))\sigma'(z) = \sigma(z)(1 - \sigma(z)). Then compute the Hessian and conclude convexity.
    Solution

    Worked solutions are part of Premiumunlock all of them for £5/month →

  2. 4 more exercises — each with a worked solution — are part of Premium. Unlock everything for £5/month →

References

  • ESL §4.4 — logistic regression, IRLS, and the separable-data pathology.
  • J. Platt, “Probabilistic Outputs for Support Vector Machines…”, 1999 — Platt scaling.
  • A. Niculescu-Mizil & R. Caruana, “Predicting Good Probabilities with Supervised Learning”, ICML 2005 — which model families distort probabilities in which direction.
  • B. Zadrozny & C. Elkan, “Transforming classifier scores into accurate multiclass probability estimates”, KDD 2002 — isotonic calibration.
  • C. Guo et al., “On Calibration of Modern Neural Networks”, ICML 2017 — temperature scaling and the deep-nets miscalibration result.
  • T. Gneiting & A. Raftery, “Strictly Proper Scoring Rules, Prediction, and Estimation”, JASA 2007.