Logistic regression

Logistic regression trained live in your browser: probability map, sigmoid surface, log-loss landscape, gradient descent vs Newton, threshold, confusion matrix, ROC and AUC. Matches scikit-learn.

Updated

  • Sigmoid and probabilities
  • Cross-entropy loss
  • Gradient descent and Newton's method
  • Decision boundary and threshold
  • Confusion matrix, ROC and AUC
iter 1 · L = 0.656iter 2 · L = 0.628iter 4 · L = 0.593iter 8 · L = 0.560iter 16 · L = 0.539iter 32 · L = 0.532iter 64 · L = 0.531Newton · L = 0.531σ(z)p = σ(w·x + b)
Preparing the lab…

Intuition

From scores to probabilities

The simplest way to split points into two classes is a straight line: class 1 on one side, class 0 on the other. Logistic regression adds one idea: the further from the line, the surer we are. It computes a score z=w⋅x+bz = w\cdot x + b for every point (the signed distance to the line, times ∥w∥\|w\|) and squashes it into a probability between 0 and 1 with the S-shaped sigmoid.

The three small labs below train for real in your browser. The background is the model's probability (blue = class 1, orange = class 0, cream = fifty-fifty) and the black line is the decision boundary z=0z = 0.

Two blobs: 300 gradient stepsPreparing…
Overlap: Newton's methodPreparing…
Separable: no finish linePreparing…

The first starts from knowing nothing (w=0w = 0: every point gets probability 0.5 and the loss is ln⁡2≈0.693\ln 2 \approx 0.693); after 300 steps the boundary cuts diagonally between the blobs and 95% of points are classified correctly.

In the second the classes overlap. Newton's method converges in 6 steps, yet accuracy is only 77.5%: points in the overlap genuinely cannot be told apart, the model honestly gives them probabilities near 0.5, and the transition band is wide.

In the third a gap separates the classes and a line can split them perfectly. The model then discovers that scaling up ww pushes every probability closer to 0 or 1 and lowers the loss — forever. ∥w∥\|w\| is 3.52 at step 1000 and 4.42 at step 5000, still growing, and the transition band keeps narrowing.

Math

Model

zi=w⋅xi+b,pi=σ(zi)=11+e−ziz_i = w\cdot x_i + b, \qquad p_i = \sigma(z_i) = \frac{1}{1+e^{-z_i}}

Loss: cross-entropy

Treat pip_i as the probability that yi=1y_i = 1; the likelihood of the data is ∏ipiyi(1−pi)1−yi\prod_i p_i^{y_i}(1-p_i)^{1-y_i}. Its averaged negative logarithm is the cross-entropy; this page adds an optional L2 penalty (the bias is not penalised, as in scikit-learn):

L=1n∑i[−yiln⁡pi−(1−yi)ln⁡(1−pi)]+λ2∥w∥2=1n∑i[softplus⁡(zi)−yizi]+λ2∥w∥2L = \frac1n\sum_i\Big[-y_i\ln p_i - (1-y_i)\ln(1-p_i)\Big] + \frac\lambda2\|w\|^2 = \frac1n\sum_i\big[\operatorname{softplus}(z_i) - y_i z_i\big] + \frac\lambda2\|w\|^2

The right-hand form (softplus⁡(z)=ln⁡(1+ez)\operatorname{softplus}(z) = \ln(1+e^z)) does not overflow even when ∣z∣|z| is huge, and it is what the lab computes.

Gradient: surprisingly simple

The sigmoid's derivative σ(1−σ)\sigma(1-\sigma) cancels exactly against the denominators in the cross-entropy:

∇wL=1n∑i(pi−yi) xi+λw,∂L∂b=1n∑i(pi−yi)\nabla_w L = \frac1n\sum_i (p_i - y_i)\,x_i + \lambda w, \qquad \frac{\partial L}{\partial b} = \frac1n\sum_i (p_i - y_i)

Each sample contributes "predicted probability minus label" times its input — the same form as linear regression's residuals.

Newton's method

The Hessian (curvature matrix) is

H=1n∑ipi(1−pi) x~ix~i⊤+λ diag(1,1,0),x~i=(xi,1)H = \frac1n\sum_i p_i(1-p_i)\,\tilde x_i\tilde x_i^\top + \lambda\,\mathrm{diag}(1,1,0), \qquad \tilde x_i = (x_i, 1)

It is positive semi-definite, so the loss is convex. Newton's method jumps to the minimum of a quadratic approximation in one step: θ←θ−H−1∇L\theta \leftarrow \theta - H^{-1}\nabla L. Near the optimum it converges quadratically — the number of correct digits roughly doubles each step. On the two blobs Newton's gradient norms are:

0.24→0.089→0.033→0.0105→0.0022→1.6×10−4→1.0×10−6→4.3×10−110.24 \to 0.089 \to 0.033 \to 0.0105 \to 0.0022 \to 1.6\times10^{-4} \to 1.0\times10^{-6} \to 4.3\times10^{-11}

Steps needed to get within 10−610^{-6} of the optimal loss:

OptimiserSteps
Gradient descent η = 0.13293
Gradient descent η = 0.5 (default)655
Gradient descent η = 2158
Gradient descent η = 2056
Newton's method7

Even η = 20 converges, unlike linear regression: logistic regression's curvature changes with the parameters. At the start (w=0w = 0) the largest Hessian eigenvalue is about 1.05 (a quadratic's limit would be about 1.9); towards the optimum the probabilities approach 0 or 1, p(1−p)p(1-p) shrinks, and at the optimum only about 0.060 is left (limit about 33).

Linearly separable: no optimum

If a line separates the classes perfectly, scaling ww along it moves every pip_i closer to its label; the loss falls strictly towards 0 but never reaches it, and no maximum-likelihood estimate exists. L2 regularisation restores a unique solution: on the separable data, λ = 0.01, 0.1 and 1 give optimal ∥w∥\|w\| of 2.00, 1.18 and 0.52.

Thresholds and ROC

By default a point is class 1 when p≥0.5p \ge 0.5 (that is, z≥0z \ge 0). Moving the threshold trades precision against recall; all thresholds together trace the ROC curve, and the area under it (AUC) is the probability that a random positive scores higher than a random negative. The two blobs reach an AUC of about 0.988, the overlapping data about 0.85.

How it is computed, with real numbers

Once the lab above has loaded, this panel works through the same formulas with its current numbers.

Experiment

Follow the lesson

Course

Lesson 1: probabilities, loss and two optimisers

5 steps · each one: set up and run → look → answer

  1. 1. Start from nothing

    Do not train yet; look at the starting state: w = 0, b = 0.

    Why is the starting loss exactly 0.693?
  2. 2. Gradient descent

    Default learning rate 0.5 for 300 steps. Look at the "Sigmoid view" tab.

    In the sigmoid view, which points carry the largest penalty?
  3. 3. Newton's method

    Switch the optimiser to Newton's method.

    Newton's method gets there in 7 steps, gradient descent in 655. What is the cost?
  4. 4. Separable data

    Switch to the "Separable" data and run 1000 gradient steps; read the notice at the top and look at the loss contours.

    Why does the loss keep falling but never finish?
  5. 5. Add regularisation

    Set the L2 strength to 0.1 and use Newton's method.

    What happens now?

Try these settings

Play with the threshold on the imbalanced data: only 24 of 120 points are class 1, so always guessing 0 already scores 80%. The model reaches 91.7% accuracy and an AUC of 0.986; its intercept b≈−1.38b \approx -1.38 shifts the whole S-curve, reflecting how rare class 1 is.

Exercises

Exercises

Exercise 1: the optimum within 10 steps

Keep the data and regularisation. Goal: at step 10 the loss is within 10−610^{-6} of the optimum.

Hint

Even gradient descent's largest learning rate, 20, needs 56 steps. Switch to Newton's method: 7.

  • Excess loss ≤ 1.0e-6
  • at most 10 epochs

Exercise 2: give separable data a finish line

Without regularisation no optimum exists and this metric cannot be computed. Bring it to at most 10−610^{-6}.

Hint

Set the L2 strength to 0.01 or more and an optimum exists; Newton's method reaches it in a few steps.

  • Excess loss ≤ 1.0e-6

Exercise 3: small weights, good accuracy

Make w1w_1 at most 1.5 while keeping training accuracy at 94% or more. Without regularisation the optimal w1w_1 is about 2.86.

Hint

λ = 0.1 shrinks ‖w‖ from 3.23 to 1.23 while accuracy only drops from 95% to 94.2%.

  • w₁ ≤ 1.500
  • Accuracy ≥ 94.0%

Quiz

What shape is logistic regression's decision boundary?
What does a coefficient w₁ = 2 mean?
Why not train logistic regression with mean squared error?

Further reading

Frequently asked questions

Is logistic regression classification or regression?

Classification. It "regresses" the log-odds (a continuous quantity) and a threshold turns the probability into a class. The name comes from statistics: among generalised linear models it is the regression with a binomial distribution and a logit link.

Why is the loss function the cross-entropy?

Treating the output as a Bernoulli probability, maximising the likelihood of the data is the same as minimising the cross-entropy. It is convex, its gradient is simple ((p − y)x), and the more badly a point is misclassified the larger its penalty.

Why doesn't logistic regression converge on linearly separable data?

When the classes can be split perfectly, scaling w along the separating direction moves every probability closer to its label, the loss falls towards 0 and the optimum lies at infinity. L2 regularisation (on by default in scikit-learn, C = 1) gives a unique finite solution.

How does logistic regression differ from linear regression?

Linear regression outputs w·x + b directly, uses squared error and has a closed form. Logistic regression passes the score through a sigmoid to get a probability, uses cross-entropy, has no closed form and needs iteration (gradient descent or Newton's method). Both gradients have the same form: error times input.

Must the threshold be 0.5?

No. 0.5 maximises accuracy when the probabilities are well calibrated; if missing a positive is costlier (screening for a disease, say), lower it to buy recall. The ROC curve shows the trade-off at every threshold, and the AUC does not depend on any one threshold.

What about more than two classes?

Two options: one-versus-rest (one binary classifier per class), or softmax regression (multinomial logistic regression) — replace the sigmoid by a softmax; the cross-entropy keeps its form.

Further reading