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
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 for every point (the signed distance to the line, times ) 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 .
The first starts from knowing nothing (: every point gets probability 0.5 and the loss is ); 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 pushes every probability closer to 0 or 1 and lowers the loss — forever. is 3.52 at step 1000 and 4.42 at step 5000, still growing, and the transition band keeps narrowing.
Math
Model
Loss: cross-entropy
Treat as the probability that ; the likelihood of the data is . Its averaged negative logarithm is the cross-entropy; this page adds an optional L2 penalty (the bias is not penalised, as in scikit-learn):
The right-hand form () does not overflow even when is huge, and it is what the lab computes.
Gradient: surprisingly simple
The sigmoid's derivative cancels exactly against the denominators in the cross-entropy:
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
It is positive semi-definite, so the loss is convex. Newton's method jumps to the minimum of a quadratic approximation in one step: . Near the optimum it converges quadratically — the number of correct digits roughly doubles each step. On the two blobs Newton's gradient norms are:
Steps needed to get within of the optimal loss:
| Optimiser | Steps |
|---|---|
| Gradient descent η = 0.1 | 3293 |
| Gradient descent η = 0.5 (default) | 655 |
| Gradient descent η = 2 | 158 |
| Gradient descent η = 20 | 56 |
| Newton's method | 7 |
Even η = 20 converges, unlike linear regression: logistic regression's curvature changes with the parameters. At the start () 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, 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 along it moves every 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 of 2.00, 1.18 and 0.52.
Thresholds and ROC
By default a point is class 1 when (that is, ). 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. Start from nothing
Do not train yet; look at the starting state: w = 0, b = 0.
2. Gradient descent
Default learning rate 0.5 for 300 steps. Look at the "Sigmoid view" tab.
3. Newton's method
Switch the optimiser to Newton's method.
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.
5. Add regularisation
Set the L2 strength to 0.1 and use Newton's method.
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 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 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 .
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 at most 1.5 while keeping training accuracy at 94% or more. Without regularisation the optimal 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
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
- Cox, The Regression Analysis of Binary Sequences, 1958: the classic source of logistic regression.
- Hastie, Tibshirani, Friedman, The Elements of Statistical Learning, section 4.4: logistic regression and Newton's method (IRLS).
- Bishop, Pattern Recognition and Machine Learning, section 4.3: probabilistic discriminative models and iteratively reweighted least squares.
- Fawcett, An introduction to ROC analysis, 2006: ROC curves and AUC.
- scikit-learn, LogisticRegression: this page's reference implementation.