Skip to content
Classical machine learning Foundation 24 min read

Logistic regression and classification

Take linear regression's weighted sum, read it as the log-odds of a yes/no outcome, squash it through a sigmoid into a probability, and train it by maximum likelihood. The result is the simplest model that outputs honest probabilities, and its multi-class form, softmax plus cross-entropy, is the output layer of every language model.

10,000 ft

Most decisions are classifications: spam or not, default or not, which of 100,000 tokens comes next. Logistic regression is the canonical probabilistic classifier: a linear score turned into a probability, fitted by maximising likelihood. It sits at a crossroads of the field. It is a generalised linear model, the statistical family that also contains linear regression. It is a single neuron with a sigmoid activation, so a neural network classifier is "logistic regression on learned features". Its loss, cross-entropy, is the loss that trains language models, and its softmax generalisation is literally the last layer of GPT. In industry it remains the workhorse for credit scoring, click-through prediction and medical risk scores because it is fast, convex, interpretable and well calibrated.

2,000 ft

Compute a score \(z = \mathbf{w}^\top\mathbf{x} + b\). Interpret it as log-odds, so the probability of the positive class is \(p = \sigma(z) = 1/(1+e^{-z})\). Fit \(\mathbf{w}, b\) by maximising the likelihood of the observed labels, which is the same as minimising the cross-entropy (log loss). The gradient has the beautifully simple form "error times input", \((p - y)\,\mathbf{x}\), the loss is convex so there is one optimum, and Newton's method finds it in a handful of steps. To classify, threshold the probability, at 0.5 by default or wherever the costs of the two kinds of mistake say. For \(K\) classes, replace the sigmoid with a softmax over \(K\) scores.

Logistic regression, forward and backward
Logistic regression, forward and backward. Features x, Score (log-odds) z = wᵀx + b, Probability p = σ(z), Cross-entropy −[y log p + (1−y) log(1−p)], Decision predict 1 if p > t, label y, gradient p − yLogistic regression, forward and backward. Features x, Score (log-odds) z = wᵀx + b, Probability p = σ(z), Cross-entropy −[y log p + (1−y) log(1−p)], Decision predict 1 if p > t, label y, gradient p − y

Ground level

Why not just use linear regression on 0/1 labels?

You can fit least squares to labels coded 0 and 1 (it is called the linear probability model), and the boundary it finds is sometimes not bad. But its outputs are not probabilities: they run below 0 and above 1, and one extreme but correctly classified point (a customer with ten times the usual income who obviously repays) drags the line and moves the boundary for everyone else, because least squares punishes being "too right". We want an output that lives in \((0,1)\), changes fastest near the boundary and saturates far from it, and a loss that does not punish confident correct answers.

Odds, log-odds and the sigmoid

Probabilities live in \((0,1)\), which a linear score cannot respect. Odds \(p/(1-p)\) live in \((0,\infty)\). Log-odds, the logit, \(\log\frac{p}{1-p}\), live on the whole real line, exactly where a linear score lives. So the model is

\[ \log\frac{p}{1-p} = \mathbf{w}^\top\mathbf{x} + b \quad\Longleftrightarrow\quad p = \sigma(\mathbf{w}^\top\mathbf{x}+b), \qquad \sigma(z) = \frac{1}{1+e^{-z}} . \]

The sigmoid \(\sigma\) is the inverse of the logit. A few values worth knowing: \(\sigma(0) = 0.5\), \(\sigma(\pm 2.2) \approx 0.9 / 0.1\), \(\sigma(\pm 4.6)\approx 0.99/0.01\), and \(\sigma(-z) = 1 - \sigma(z)\). Its derivative is \(\sigma'(z) = \sigma(z)(1-\sigma(z))\), largest (0.25) at the boundary.

A worked example: hours studied and passing

Ten students, hours studied \(h = (0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5)\), passed \(y = (0,0,0,0,1,0,1,1,1,1)\). Note the overlap: the student at 2.5 hours passed and the one at 3 hours failed, so no threshold separates the classes perfectly. Maximum likelihood (Newton's method, six iterations, below) gives

\[ \log\text{odds(pass)} = -7.159 + 2.603\,h . \]
12345hours studied 00.51 boundary 2.75 h p = σ(−7.16 + 2.60h)
The fitted probability of passing. The boundary (p = 0.5) is where the log-odds are zero: h = 7.159 / 2.603 = 2.75 hours. The two overlapping students (2.5 h passed, 3 h failed) keep the curve from becoming a vertical step.

Reading it:

  • The boundary is where log-odds are zero: \(h = 7.159/2.603 = 2.75\) hours.
  • The coefficient \(2.603\) is the change in log-odds per extra hour. Exponentiate: each hour multiplies the odds of passing by \(e^{2.603} \approx 13.5\). That "odds ratio" reading is why medicine and credit scoring like this model.
  • Predictions: at 2 hours, \(z = -1.952\), \(p = 0.124\); at 3 hours, \(z = 0.651\), \(p = 0.657\); at 4 hours, \(p = 0.963\).
  • The loss for one student. Suppose a model says \(p = \sigma(0.5) = 0.622\) for some student. If she passed, her contribution to the loss is \(-\ln 0.622 = 0.474\); if she failed, \(-\ln(1-0.622) = 0.974\). Confidently wrong costs far more than mildly wrong, and as \(p \to 0\) for a true positive the loss goes to infinity.

And the first gradient step, by hand: at \(\mathbf{w} = \mathbf{0}\) every prediction is \(0.5\), the average loss is \(\ln 2 = 0.693\), and the gradient of the mean loss is \(\frac{1}{n}\sum_i (p_i - y_i)(1, h_i) = (0.5 - 0.5,\; 0.5\cdot 2.75 - 1.95) = (0, -0.575)\). The intercept is already balanced (half the students passed); the slope gets pushed up, because students who passed studied more.

Training: cross-entropy, gradient descent and Newton

The loss over the dataset is the average binary cross-entropy (also called log loss, or the negative log-likelihood of a Bernoulli model):

\[ L(\mathbf{w}) = -\frac{1}{n}\sum_{i=1}^{n}\Big[y_i\log p_i + (1-y_i)\log(1-p_i)\Big], \qquad p_i = \sigma(\mathbf{w}^\top\mathbf{x}_i). \]

Its gradient is

\[ \nabla L = \frac{1}{n}\sum_i (p_i - y_i)\,\mathbf{x}_i = \frac1n X^\top(\mathbf{p}-\mathbf{y}), \]

the same shape as linear regression's \(\frac1n X^\top(\hat{\mathbf{y}}-\mathbf{y})\): prediction error times input. This is no coincidence (see one recipe, many models). Unlike least squares, setting it to zero has no closed-form solution, because \(\mathbf{p}\) depends non-linearly on \(\mathbf{w}\). But the loss is convex, so gradient descent cannot get stuck, and because it is smooth with an easy Hessian, Newton's method converges in a few iterations. On the toy data, Newton's negative log-likelihood (summed) goes \(3.270, 2.672, 2.526, 2.509, 2.5090089, 2.5090087, \dots\): the number of correct digits roughly doubles per step once close, the signature of quadratic convergence. For large or sparse data, practitioners use L-BFGS or (stochastic) gradient methods instead, because Newton needs a \(d\times d\) solve per step.

The decision boundary is a hyperplane

\(p > 0.5 \iff \mathbf{w}^\top\mathbf{x} + b > 0\). So for any fixed threshold, logistic regression draws a straight line in 2-D (a hyperplane in \(d\) dimensions); the level sets of the probability are parallel hyperplanes, and the probability rises along the direction \(\mathbf{w}\). The signed distance from a point to the boundary is \(z/\lVert\mathbf{w}\rVert\), so \(\lVert\mathbf{w}\rVert\) sets how sharply probability rises with distance: large weights mean a near-step function, small weights a gentle ramp. Watch a linear classifier find a boundary on 2-D points:

The perceptron (Rosenblatt, 1958) updates only on mistakes; logistic regression updates on every point in proportion to \(p - y\), so even correctly classified points near the boundary nudge it. That difference is what makes logistic regression's probabilities meaningful.

Thresholds, costs and imbalanced classes

The model outputs a probability; the decision is a separate step. If a false negative costs \(c_{\text{FN}}\) and a false positive \(c_{\text{FP}}\), predicting positive has expected cost \((1-p)\,c_{\text{FP}}\) and predicting negative \(p\,c_{\text{FN}}\). Predict positive when

\[ p > t^\ast = \frac{c_{\text{FP}}}{c_{\text{FP}} + c_{\text{FN}}} . \]

If missing a fraud costs nine times as much as a false alarm, \(t^\ast = 1/(1+9) = 0.1\). This is why "accuracy at threshold 0.5" is the wrong target for most real problems, and why threshold-free metrics such as ROC-AUC and PR-AUC exist.

With rare positives (1 in 1,000), a well-fitted model will rarely output \(p > 0.5\), and that is correct behaviour, not a bug. Reweighting or resampling the classes changes the intercept: training on data where positives are oversampled from rate \(\pi\) to rate \(\pi'\) adds \(\log\frac{\pi'/(1-\pi')}{\pi/(1-\pi)}\) to every logit, so subtract that offset at prediction time if you need calibrated probabilities. Usually it is better to keep the natural class balance and move the threshold.

Probabilities you can trust: calibration

A model is calibrated if, among all cases where it says 0.7, about 70% are positive. Logistic regression tends to be well calibrated when the model is roughly right, because maximum likelihood with an intercept forces \(\sum_i p_i = \sum_i y_i\) on the training data (the intercept component of the zero-gradient condition), and more generally matches the average of each feature weighted by predicted versus actual labels. In the Build-it run below, test examples predicted in \([0.6, 0.8)\) averaged 0.709 predicted and 0.669 observed. Niculescu-Mizil and Caruana (2005) found that boosted trees and SVMs, by contrast, distort probabilities systematically, and Guo et al. (2017) showed that modern deep networks are overconfident; both fixes are, in effect, a logistic regression fitted on top of the model's scores (Platt scaling, or its one-parameter version, temperature scaling).

Many classes: softmax regression

For \(K\) classes, give each class its own weight vector \(\mathbf{w}_k\) and score \(z_k = \mathbf{w}_k^\top\mathbf{x}\), then normalise with the softmax:

\[ p(y = k\mid\mathbf{x}) = \operatorname{softmax}(\mathbf{z})_k = \frac{e^{z_k}}{\sum_{j=1}^{K}e^{z_j}} . \]

The loss is the cross-entropy \(-\log p(y = y_i\mid\mathbf{x}_i)\) and the gradient with respect to the scores is again "prediction minus truth": \(\mathbf{p} - \mathbf{e}_{y}\), where \(\mathbf{e}_y\) is the one-hot label. Adding the same constant to every score changes nothing, so one class's weights can be fixed at zero; with \(K=2\) that recovers the sigmoid, since \(\frac{e^{z_1}}{e^{z_0}+e^{z_1}} = \sigma(z_1 - z_0)\).

A language model's output layer is exactly this, with \(K\) equal to the vocabulary size (tens of thousands to a few hundred thousand tokens) and \(\mathbf{x}\) the final hidden state: pre-training is multinomial logistic regression on features that the rest of the network learns. Temperature divides every score by \(T\) before the softmax:

One recipe, many models

Logistic and linear regression are two instances of one recipe, the generalised linear model (GLM; Nelder and Wedderburn, 1972): choose a distribution for \(y\) given \(\mathbf{x}\), model its mean through a link function of a linear score, and fit by maximum likelihood. For every member with the "canonical" link, the gradient is \(X^\top(\boldsymbol{\mu} - \mathbf{y})\): error times input.

Target Noise model Link \(g(\mu) = \mathbf{w}^\top\mathbf{x}\) Loss Name
real number Gaussian identity squared error linear regression
yes / no Bernoulli logit \(\log\frac{\mu}{1-\mu}\) binary cross-entropy logistic regression
one of \(K\) categorical softmax (multi-logit) cross-entropy softmax regression; an LLM's output layer
count Poisson \(\log\mu\) Poisson deviance Poisson regression (claims, clicks per hour)

The lesson generalises far beyond GLMs: choose the output distribution, and the loss follows as its negative log-likelihood. That is how every deep network's loss is chosen too.

History

From population curves to credit scores

The logistic curve was introduced by Pierre-François Verhulst in the 1830s–40s to model population growth that saturates. Joseph Berkson coined the word logit in 1944 and argued for it over the then-standard probit (the Gaussian CDF) in bioassay, where you model the fraction of animals that respond to a dose. David Cox's 1958 paper "The regression analysis of binary sequences" set out logistic regression in essentially its modern form. Nelder and Wedderburn unified it with linear and Poisson regression as generalised linear models in 1972, together with the iteratively reweighted least-squares algorithm. In machine learning it re-entered as the single sigmoid neuron and as "maximum entropy" classifiers in 1990s NLP; Ng and Jordan's 2001 paper on discriminative versus generative classifiers is the classic comparison with naive Bayes.

First principles

Why the sigmoid, and not some other squashing function? Three routes lead to it.

  1. Log-odds are linear. If you believe each feature adds a fixed amount of evidence on the log-odds scale (the way independent pieces of evidence add in Bayes' rule written in log form), the sigmoid is forced: it is the inverse of the logit.
  2. Bayes with Gaussian classes. Suppose each class generates \(\mathbf{x}\) from a Gaussian with its own mean but a shared covariance \(\Sigma\). Then by Bayes' rule, \(\log\frac{p(1\mid\mathbf{x})}{p(0\mid\mathbf{x})}\) is exactly linear in \(\mathbf{x}\) (the quadratic terms cancel because the covariances are equal), so the posterior is a sigmoid of a linear function. Logistic regression fits that posterior directly without modelling \(p(\mathbf{x})\) at all: it is the discriminative twin of the generative linear discriminant analysis. The same holds for any exponential-family class-conditionals with shared dispersion, which is why the model is so broadly right.
  3. Maximum entropy. Among all distributions \(p(y\mid\mathbf{x})\) whose expected features match the data, the one with maximum entropy is the softmax of a linear score. Assume nothing beyond the constraints and you get logistic regression.

Why cross-entropy and not squared error? Cross-entropy is the negative log-likelihood of a Bernoulli outcome, so it is what maximum likelihood demands. It also behaves better. With squared error on a sigmoid output the gradient is \((p-y)\,p(1-p)\,\mathbf{x}\): when the model is confidently wrong (\(p \approx 0\), \(y = 1\)) the factor \(p(1-p)\) is tiny and learning stalls exactly when it is most needed, and the loss is not convex in \(\mathbf{w}\). Cross-entropy's \(\log\) cancels the sigmoid's exponential and leaves the clean \((p - y)\mathbf{x}\), convex, with gradients proportional to how wrong you are. This cancellation is why deep networks pair sigmoid/softmax outputs with cross-entropy. Cross-entropy is also a strictly proper scoring rule: its expected value is minimised only by reporting the true probability, so it rewards honesty (entropy, cross-entropy and KL).

What breaks. Perfect separation: if a hyperplane separates the classes, the likelihood can always be increased by scaling \(\mathbf{w}\) up, so the maximum-likelihood estimate does not exist; the weights grow without bound and the probabilities become 0 and 1. Gradient descent's weights grow only logarithmically in the number of steps, and their direction converges to the maximum-margin (hard-margin SVM) separator, a result due to Soudry et al. (2018); an L2 penalty restores a finite answer. Non-linear boundaries need features: interactions, polynomials, splines, or a learned representation (a neural network). Correlated features inflate the variance of the weights just as in linear regression.

The maths

Notation. \(X\in\mathbb{R}^{n\times p}\) including a ones column, \(\mathbf{y}\in\{0,1\}^n\), \(\mathbf{p} = \sigma(X\mathbf{w})\) applied elementwise, \(S = \operatorname{diag}(p_i(1-p_i))\).

Likelihood. Each label is Bernoulli: \(P(y_i\mid\mathbf{x}_i) = p_i^{y_i}(1-p_i)^{1-y_i}\). The negative log-likelihood is

\[ \ell(\mathbf{w}) = -\sum_i\big[y_i\log p_i + (1-y_i)\log(1-p_i)\big] = \sum_i\big[\log(1+e^{z_i}) - y_i z_i\big], \quad z_i = \mathbf{w}^\top\mathbf{x}_i , \]

where the second form uses \(\log p = z - \log(1+e^z)\) and \(\log(1-p) = -\log(1+e^z)\). Implement it in this form with logaddexp(0, z); computing \(\sigma\) then \(\log\) underflows for large \(|z|\) (floating point and log-sum-exp).

Derivation: gradient and Hessian of the log loss

Per example, \(\ell_i = \log(1+e^{z_i}) - y_i z_i\). Differentiate in \(z_i\): \(\frac{\partial\ell_i}{\partial z_i} = \frac{e^{z_i}}{1+e^{z_i}} - y_i = \sigma(z_i) - y_i = p_i - y_i\). By the chain rule with \(\partial z_i/\partial\mathbf{w} = \mathbf{x}_i\):

\[ \nabla\ell = \sum_i (p_i - y_i)\mathbf{x}_i = X^\top(\mathbf{p}-\mathbf{y}) . \]

Differentiate again, using \(\sigma'(z) = \sigma(z)(1-\sigma(z))\):

\[ \nabla^2\ell = \sum_i p_i(1-p_i)\,\mathbf{x}_i\mathbf{x}_i^\top = X^\top S X . \]

For any \(\mathbf{v}\), \(\mathbf{v}^\top X^\top SX\mathbf{v} = \sum_i p_i(1-p_i)(\mathbf{x}_i^\top\mathbf{v})^2 \ge 0\), so \(\ell\) is convex. It is strictly convex when \(X\) has full column rank and no \(p_i\) is exactly 0 or 1.

Newton's method is iteratively reweighted least squares (IRLS). The Newton step is \(\mathbf{w}_{\text{new}} = \mathbf{w} - (X^\top SX)^{-1}X^\top(\mathbf{p}-\mathbf{y})\). Rearranged,

\[ \mathbf{w}_{\text{new}} = (X^\top SX)^{-1}X^\top S\,\mathbf{u}, \qquad \mathbf{u} = X\mathbf{w} + S^{-1}(\mathbf{y}-\mathbf{p}), \]

which is a weighted least-squares fit of a "working response" \(\mathbf{u}\) with weights \(p_i(1-p_i)\). Each iteration is a linear regression; points near the boundary (where \(p(1-p)\) is largest) get the most weight. That is how R's glm fits every GLM.

Softmax regression. With \(W\in\mathbb{R}^{K\times p}\), scores \(\mathbf{z} = W\mathbf{x}\), \(\mathbf{p} = \operatorname{softmax}(\mathbf{z})\) and loss \(-\log p_{y}\):

\[ \frac{\partial(-\log p_y)}{\partial z_k} = p_k - \mathbb{1}[k=y], \qquad \nabla_W = (\mathbf{p}-\mathbf{e}_y)\,\mathbf{x}^\top \;\in\mathbb{R}^{K\times p}. \]

For a batch, \(\nabla_W = (P - Y)^\top X\) with \(P, Y\in\mathbb{R}^{n\times K}\). Shapes for an LLM head: hidden state \(\mathbf{h}\in\mathbb{R}^{d_{\text{model}}}\), unembedding \(W_U\in\mathbb{R}^{V\times d_{\text{model}}}\), logits \(\in\mathbb{R}^{V}\).

Regularised logistic regression minimises \(\ell(\mathbf{w}) + \frac{\lambda}{2}\lVert\mathbf{w}\rVert^2\) (usually not penalising the intercept). This is MAP estimation with a Gaussian prior on the weights, keeps the problem strictly convex, guarantees a finite solution on separable data, and is scikit-learn's default (C \(= 1/\lambda\)).

Inference. Asymptotically, \(\hat{\mathbf{w}}\sim\mathcal{N}(\mathbf{w}, (X^\top SX)^{-1})\): the inverse Hessian at the optimum gives standard errors, and \(\exp(\hat w_j \pm 1.96\,\text{se}_j)\) gives a confidence interval for an odds ratio.

In practice

  • Default first classifier for tabular data: standardise numeric features, one-hot categorical ones (features and tabular data), fit L2-regularised logistic regression with C chosen by cross-validation. If gradient-boosted trees beat it, the gap tells you how much non-linearity and interaction the data hold.
  • Solvers. scikit-learn's lbfgs is a good default; liblinear or saga for L1 penalties; SGD for data that does not fit in memory.
  • Report log loss or Brier score, not just accuracy, if the probabilities will be used; and choose thresholds from costs, not 0.5 (metrics).
  • Separation warnings ("perfect separation", huge coefficients) usually mean a leaky or ID-like feature, or too many features for too few positives. Look before you regularise it away.
  • Coefficients are conditional log-odds ratios. Interpret them only alongside the other features, with standardised inputs, and not causally.

Common misconceptions

Logistic regression is a regression model, so it is not for classification

It regresses the log-odds, a continuous quantity, which is where the name comes from; its use is classification. The name is historical, from the GLM family.

Imbalanced data must be rebalanced before training

Rebalancing shifts the intercept and miscalibrates the probabilities. With enough positives to learn from, keep the natural rate and choose the threshold from the costs. Resample or reweight when the minority class is so rare that the optimiser ignores it, and correct the intercept afterwards if you need probabilities.

A probability of 0.9 from any classifier means 90%

Only if it is calibrated. Check with a reliability diagram on held-out data; boosted trees, SVM scores and large neural networks often need Platt or temperature scaling.

Build it

NumPy only: gradient descent and Newton on the same 2-D problem, a calibration table on held-out data, and the separable case.

import numpy as np

rng = np.random.default_rng(1)
def blobs(n, gap):
    X = np.r_[rng.normal(-gap / 2, 1, (n, 2)), rng.normal(gap / 2, 1, (n, 2))]
    return np.column_stack([np.ones(2 * n), X]), np.r_[np.zeros(n), np.ones(n)]

sigmoid = lambda z: 0.5 * (1 + np.tanh(0.5 * z))            # stable for large |z|
def nll(w, X, y):                                           # mean cross-entropy
    z = X @ w
    return np.mean(np.logaddexp(0, z) - y * z)              # log(1+e^z) - y z

def fit_gd(X, y, lr=0.5, steps=2000, l2=0.0):
    w = np.zeros(X.shape[1])
    for _ in range(steps):
        w -= lr * (X.T @ (sigmoid(X @ w) - y) / len(y) + l2 * np.r_[0, w[1:]])
    return w

def fit_newton(X, y, iters=10):
    w = np.zeros(X.shape[1])
    for _ in range(iters):
        p = sigmoid(X @ w)
        H = X.T @ (X * (p * (1 - p))[:, None]) / len(y)
        w -= np.linalg.solve(H, X.T @ (p - y) / len(y))
    return w

X, y = blobs(500, gap=2.0)
Xt, yt = blobs(5000, gap=2.0)
w_gd, w_nt = fit_gd(X, y), fit_newton(X, y)
np.set_printoptions(precision=4, suppress=True)
print("GD     w =", w_gd, " train NLL = %.4f" % nll(w_gd, X, y))
print("Newton w =", w_nt, " train NLL = %.4f" % nll(w_nt, X, y))
p = sigmoid(Xt @ w_nt)
print("test acc = %.3f  test NLL = %.4f" % (np.mean((p > 0.5) == yt), nll(w_nt, Xt, yt)))
for lo in np.arange(0, 1, 0.2):                            # calibration by bins
    m = (p >= lo) & (p < lo + 0.2)
    print(f"  p in [{lo:.1f},{lo+.2:.1f}): mean predicted {p[m].mean():.3f}"
          f"  observed {yt[m].mean():.3f}  (n={m.sum()})")

Xs, ys = blobs(50, gap=8.0)                                 # linearly separable
for steps in (10**2, 10**3, 10**4, 10**5):
    w = fit_gd(Xs, ys, lr=1.0, steps=steps)
    print(f"separable, {steps:>6} steps: |w| = {np.linalg.norm(w):5.2f}"
          f"  NLL = {nll(w, Xs, ys):.2e}  direction = {w[1:] / np.linalg.norm(w[1:])}")
print("with L2=0.01, 10000 steps: |w| = %.2f" % np.linalg.norm(fit_gd(Xs, ys, 1.0, 10000, l2=0.01)))

Output:

GD     w = [0.18   2.4066 2.1218]  train NLL = 0.1599
Newton w = [0.18   2.4066 2.1218]  train NLL = 0.1599
test acc = 0.925  test NLL = 0.1866
  p in [0.0,0.2): mean predicted 0.029  observed 0.034  (n=4288)
  p in [0.2,0.4): mean predicted 0.287  observed 0.275  (n=473)
  p in [0.4,0.6): mean predicted 0.497  observed 0.459  (n=392)
  p in [0.6,0.8): mean predicted 0.709  observed 0.669  (n=456)
  p in [0.8,1.0): mean predicted 0.973  observed 0.966  (n=4391)
separable,    100 steps: |w| =  2.90  NLL = 1.52e-06  direction = [0.6982 0.7159]
separable,   1000 steps: |w| =  2.91  NLL = 1.49e-06  direction = [0.698  0.7161]
separable,  10000 steps: |w| =  2.95  NLL = 1.25e-06  direction = [0.6966 0.7174]
separable, 100000 steps: |w| =  3.20  NLL = 4.86e-07  direction = [0.6893 0.7245]
with L2=0.01, 10000 steps: |w| = 1.17

Gradient descent (2,000 steps) and Newton (10 steps) reach the same weights. The two classes are Gaussian blobs with equal covariance, so (by the argument in First principles) logistic regression is the correct model here, and the held-out calibration table shows predicted and observed rates agreeing to within a few points. On separable data the loss keeps falling towards zero and \(\lVert\mathbf{w}\rVert\) keeps creeping up, logarithmically, with no finite optimum, while the direction of \(\mathbf{w}\) drifts slowly towards the maximum-margin direction; a small L2 penalty stops the growth.

Things to try

  • Count Newton's iterations to convergence versus gradient descent's steps; print the loss per iteration and see the doubling of correct digits.
  • Make the classes have different covariances. Logistic regression's linear boundary is now wrong (the Bayes boundary is quadratic). Add the features \(x_1^2, x_2^2, x_1x_2\) and refit.
  • Oversample the positives 10× and refit. Check that the intercept rises by about \(\log 10 \approx 2.3\) and that the calibration table breaks; subtract the offset and check it is restored.
  • Implement softmax regression for 3 blobs; verify the gradient numerically with finite differences.
  • Replace cross-entropy with squared error on \(\sigma(z)\) and start from a badly wrong \(\mathbf{w}\); watch learning stall.

Check yourself

A coefficient is 0.7 on a standardised feature. What does that mean?

A one-standard-deviation increase in that feature, holding the others fixed, adds 0.7 to the log-odds, i.e. multiplies the odds of the positive class by \(e^{0.7}\approx 2.01\). The effect on the probability depends on where you start: near \(p = 0.5\) it raises \(p\) by about \(0.7 \times 0.25 = 0.175\); near \(p = 0.01\) it roughly doubles a tiny number.

Derive \(\sigma'(z) = \sigma(z)(1-\sigma(z))\) and explain why it makes the cross-entropy gradient so simple.

\(\sigma(z) = (1+e^{-z})^{-1}\), so \(\sigma'(z) = e^{-z}(1+e^{-z})^{-2} = \sigma(z)\cdot\frac{e^{-z}}{1+e^{-z}} = \sigma(z)(1-\sigma(z))\). In \(\partial\ell/\partial z = -\frac{y}{p}\sigma' + \frac{1-y}{1-p}\sigma'\), the factors \(p(1-p)\) cancel the denominators and leave \(p - y\).

Why does logistic regression fail to converge on perfectly separable data, and what are two fixes?

Any separating \(\mathbf{w}\) can be scaled up to push every \(p_i\) closer to its label, so the likelihood keeps increasing and has no maximiser; the weights diverge. Fixes: add an L2 (or L1) penalty, which gives a finite MAP solution; or stop early (gradient descent's direction converges to the max-margin separator, its norm grows only like \(\log t\)). Also check whether separation reveals leakage.

Fraud costs 50 times more to miss than a false alarm costs to investigate. What threshold should you use on a calibrated model?

\(t^\ast = c_{\text{FP}}/(c_{\text{FP}}+c_{\text{FN}}) = 1/(1+50) \approx 0.0196\). Flag anything with \(p > 2\%\). This assumes the probabilities are calibrated; if not, calibrate first on held-out data.

Show that two-class softmax is the sigmoid. Why is one weight vector redundant?

\(\frac{e^{z_1}}{e^{z_0}+e^{z_1}} = \frac{1}{1+e^{-(z_1-z_0)}} = \sigma(z_1-z_0)\), which depends only on \(\mathbf{w}_1-\mathbf{w}_0\). Adding any vector to both weight vectors leaves every probability unchanged, so the parameters are not identifiable; fix one class at zero or regularise.

Why is squared error a poor loss on a sigmoid output?

Its gradient carries a \(p(1-p)\) factor, which vanishes when the model is confidently wrong, so learning stalls where it matters most, and the loss is non-convex in \(\mathbf{w}\). Cross-entropy is the Bernoulli negative log-likelihood, convex in \(\mathbf{w}\), with gradient \((p-y)\mathbf{x}\), and a strictly proper scoring rule.

Hard: under what generative model is logistic regression exactly right, and what do you lose by fitting it discriminatively?

If \(\mathbf{x}\mid y\) is Gaussian with class-specific means and a shared covariance (or, more generally, from an exponential family with shared dispersion), the posterior log-odds are linear, so logistic regression is correctly specified. LDA fits the generative model and is more statistically efficient when the assumption holds (Ng and Jordan: generative classifiers can approach their asymptotic error with far fewer samples); logistic regression makes no assumption about \(p(\mathbf{x})\), so it is more robust when that assumption fails and has lower asymptotic error when the generative model is wrong.

Go deeper

Papers

Videos and lectures

Articles and blog posts

Courses and books

Code

Where this leads