A student studies for some hours and then passes or fails an exam. A bank sees a loan application and must say yes or no. A spam filter reads an email. In each case the answer is one of two labels, and a good system also says how sure it is: “ likely to pass”.
Linear regression (P3.A2) draws a line through numbers, and its output can be any number. A probability must stay between and . Logistic regression fixes this with one extra step: compute a score exactly as linear regression does, then squeeze it into with the sigmoid of P1.A5. Despite its name it is a classification model, and it is the first one in this course. Everything it uses (the sigmoid, the log-loss, the gradient , a convex landscape) returns in neural networks.
From a score to a probability
Here is a made-up data set: six students, the hours each one studied, and whether they passed () or failed ().
| hours | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|
| passed | 0 | 0 | 1 | 0 | 1 | 1 |
More hours tend to mean more passes, but not always (the student with hours failed). A straight line fitted by least squares to these labels is . It is at and at : it cannot be read as a probability.
Logistic regression keeps the linear score (also called the logit) and passes it through the sigmoid from P1.A5:
The number is the model’s probability that the label is . A score of gives ; the scores give . A very large score gives a close to and a very negative one a close to , never outside.
The best weights for the six students (found below) are and . For hours the score is and ; for hours it is ; for hours, .
The score is the log-odds
The odds of an event with probability are : means odds of to . The natural logarithm of the odds is the log-odds, or logit. Solving for gives
So the sigmoid is the curve that turns log-odds into a probability (P1.A5), and logistic regression is the model that says: the log-odds of the label are a linear function of the features. That one sentence is the whole model.
It gives the weights a meaning. Raise the feature by and keep every other feature fixed: the score rises by , so the odds are multiplied by . For the students, : every extra hour multiplies the odds of passing by about . At hours the odds are and at hours they are ().
Careful with two points. The odds are multiplied, but the probability is not: going from to hours moves from to , while going from to moves it from to . The same odds ratio gives different probability changes, because the sigmoid is steepest in the middle. And “holding the others fixed” is an assumption: if two features move together in real data (height and weight, say), the individual weights are hard to interpret, and a weight describes association in this data, not what would happen if you changed that feature.
The decision boundary
To turn a probability into a decision, pick a threshold. The usual one is : predict class when . Because and the sigmoid only increases, exactly when . So the model predicts class when
and the decision boundary is the set of points where . That set is a straight line when there are two features and a flat hyperplane in more dimensions, so logistic regression is a linear classifier: its boundary is flat even though its probability curve is an S.
A made-up example with two features: and . The boundary is the line through and . The point has score and ; the point has score and .
The vector is perpendicular to the boundary and points toward the class- side (P1.B3). The score is the signed distance to the line times the length of : the point is units from the line, and . So with the signed distance, and the probability depends only on how far you are from the boundary. A large makes the sigmoid change quickly across the boundary (a sharp, confident model); a small one changes slowly.
Other thresholds. The threshold is a choice, not a law. Requiring means requiring , a line parallel to the first one and shifted. For the score must exceed ; for , . For the students, the boundary at is hours, at it moves to hours and at to hours. Which threshold is right depends on the cost of each kind of mistake, and P3.A9 shows how to choose it.
A limit. A line cannot separate classes that sit in opposite corners (the widget has such a data set). To get a curved boundary you add features such as or (P3.A3) or use a neural network (Part 4). The model stays linear in the features it is given.
The loss: binary cross-entropy
How do we find good weights? Define a loss and minimize it (P3.A1). Suppose for each example the model says “the probability of label is ”. The Bernoulli distribution gives the label the probability : it is if and if . By maximum likelihood (P1.D10) we pick the weights that make the observed labels most probable. Multiplying over independent examples and taking the negative logarithm (so that products become sums and “maximize” becomes “minimize”) gives the loss for one example
and , its average over the training examples, is the binary cross-entropy (BCE), the cross-entropy of P1.E3 for two classes. With , it is the negative log of the probability the model gave to the right answer.
A small check, from P1.D10: for labels and predictions the right answers got , so the losses are and the average is . A confident mistake is costly: for a true costs , and costs . A model that always says has loss , a useful number to compare with when training starts.
Why not squared error on the probability? One could minimize . Two things go wrong. First, the slope is almost zero exactly when the model is most wrong. For a label and a score (so ), the slope of the cross-entropy with respect to is (P1.C3), but the slope of is only because it is multiplied by the flat sigmoid tail . Second, as a function of the weights the squared error of a sigmoid is not convex (box below). Neither fact makes training impossible, and squared error on probabilities is sometimes used, but the cross-entropy is the loss that matches the probability model, and it has neither flaw.
Go deeper The squared error of a sigmoid is not convex
Take one example with and label , so the loss is as a function of the weight . Its second derivative is at and at (a finite-difference check). A negative second derivative means the curve bends downward there, so the loss is not convex, while the cross-entropy has second derivative everywhere.
The gradient
For one example, write the loss as a function of the score. The chain rule (P1.C3) has three links: depends on , depends on , and depends on the weights.
The factors and cancel, leaving the same “prediction minus target” as in linear regression. Since and , the gradient of the average loss is
In matrix form this is . Read it as a vote: each example pushes the weights along its own , with a strength equal to its error, and an example that is already right () hardly pushes at all.
One step by hand on the six students. Start at , so every :
| 1 | 0 | 0.5 | 0.5 |
| 2 | 0 | 0.5 | 1.0 |
| 3 | 1 | −0.5 | −1.5 |
| 4 | 0 | 0.5 | 2.0 |
| 5 | 1 | −0.5 | −2.5 |
| 6 | 1 | −0.5 | −3.0 |
The column adds to , so , and (the column adds to ). With step size the weight becomes and , and the loss drops from to . Repeating this is gradient descent (P1.F3). The first code cell below checks the formula against a numerical difference quotient.
The widget: train a boundary
The widget trains exactly this model. The shading is , the thick line is the boundary and the readouts are the quantities above.
Things to try, one at a time:
- Overlapping, λ = 0. Press Play until the status says “Converged”. The line makes mistakes out of points and the loss stops near with and . Raise λ to and continue: the weights shrink to about , the line turns a little, the loss rises to about and one more of the points ends up on the wrong side ( of correct instead of ). That is the price of the penalty.
- Separable, λ = 0. Every point is on the correct side after the first step, yet the weights keep growing, and the chart of keeps climbing while the loss creeps toward . Press +10 000 twice. Then set λ to and train again: the weights settle at about and .
- Corners. No line separates the corners, and the accuracy stays near at a loss close to .
- Step size. The widget shows the safe step . Above the steps can overshoot, and a warning appears. On Corners, set η to and watch the loss bounce. On the other two data sets is above the slider’s maximum, so the loss keeps falling.
- Move a point. Drag one blue circle into the pink cloud. The boundary moves to accommodate it, and a point far from the rest pulls the line harder than a near one.
Why training works: the loss is convex
Gradient descent can get stuck in a local minimum on a bumpy landscape (P1.F2). The logistic loss has no such valleys. For one example the loss is a function of , and its second derivative with respect to is , which lies between and and is never negative. The score is an affine function of the weights, and a convex function of an affine function is convex (P1.F2). A sum of convex terms is convex, so the whole loss is convex in : every local minimum is a global minimum, and gradient descent with a small enough step size reaches it.
Two caveats. The minimum may not exist (next section). And “convex” does not mean “fast”: the speed of gradient descent depends on how the features are scaled (see below).
Go deeper Newton's method and iteratively reweighted least squares
The Hessian of the average loss is with (here has a column of ones for the bias). It is positive semidefinite, which is another proof of convexity, and it never exceeds , which gives the safe step size with the largest eigenvalue of that matrix (P1.B10). The widget shows this .
Newton’s method (P1.F6) solves at each step. Each solve has the form of a weighted least-squares problem whose weights change from step to step, which is why statistics software calls it iteratively reweighted least squares (IRLS). On the 200-point data set of P1.F6 (cell below) Newton’s method needs steps and gradient descent with needs to bring the gradient norm below . With weights and at least about examples, each Newton step costs about times more than a gradient step, so it wins for models with few weights, such as this one, and not for large networks.
When the classes can be separated
Suppose one line has all the class- points on its positive side and all the class- points on its negative side: the data are linearly separable. Take any such weights and multiply all of them by . Every score moves farther from on the correct side, every probability of the right answer moves closer to , and the loss falls. So the loss can always be lowered, by making the weights larger and larger. It gets closer to and never reaches it: there is no best finite answer. P1.F1 showed the smallest case: for one example with label and the loss is at , at and at .
Gradient descent shows it clearly. Take four made-up points with and labels , and . The weight after and steps is and , while the loss falls from to . Each tenfold increase in the number of steps adds about to near the end (the growth is logarithmic in the number of steps), so it is slow, but it does not stop. Two consequences:
- A huge weight is not a sign of a strong effect. It may only mean the classes can be separated, and the probabilities it outputs ( and to many digits) are not believable.
- Real data are often almost separable (many features, few examples), and then the weights are large for the same reason.
The fix is regularization (P3.A6). Add the L2 penalty to the loss, usually leaving the bias out. Now growing the weights has a price, the objective is strictly convex in , and there is exactly one best answer. On the four points, and give and . The larger the penalty, the smaller the weights and the closer the probabilities are to . Here multiplies the penalty next to the average loss. It is not the same number as the of the ridge formula in P3.A6, which sits next to a sum of squared errors. Stopping training early also limits how large the weights get (a form of regularization, P4.17), so a loss that is still falling is not always a reason to keep going.
scikit-learn. LogisticRegression in scikit-learn applies an L2 penalty by default, with strength set by C, the inverse of the penalty strength: a small C means a strong penalty. Its default is C=1.0. It minimizes , which is the same as the widget’s objective with (with examples). This holds for the default solver; liblinear also penalizes the intercept. On the six students, scikit-learn 1.8 gives the following (real output; the library is not available inside this page, so this block is not runnable here):
from sklearn.linear_model import LogisticRegression
import numpy as np
x = np.array([[1], [2], [3], [4], [5], [6]])
y = np.array([0, 0, 1, 0, 1, 1])
m = LogisticRegression().fit(x, y) # C = 1.0, L2 penalty
print(m.coef_, m.intercept_) # [[0.767]] [-2.685]
print(m.predict_proba([[4]])) # [[0.405 0.595]]
m = LogisticRegression(C=1e6).fit(x, y) # almost no penalty
print(m.coef_, m.intercept_) # [[1.214]] [-4.249]
The default penalty shrinks from to , so at hours falls from to , but the boundary does not move, because these data are symmetric. Whether the default is the right amount of penalty is a question for validation data (P3.A4).
Practical matters
Scale the features. The loss is convex whatever the scaling, but gradient descent is much faster when the features are on similar scales (P1.F5 shows the zig-zag in a narrow ravine; P3.A11 covers scaling). On the six students with , the raw hours need about steps to bring the gradient norm below , while the standardized hours (mean , population standard deviation ) need about . The L2 penalty also treats all weights alike, so it only makes sense if the features are on comparable scales.
Imbalance and more classes. When of the examples are class , always answering is accurate, so the metrics of P3.A9 and the repairs of P3.A10 are needed. For more than two classes the sigmoid is replaced by the softmax (P3.A8); with two classes the softmax is the sigmoid of the score difference, since .
Computing the loss. The formula breaks in floating point: for and , rounds to exactly and the loss is , although the true value is . The stable form works from the score: the loss for label is and for label it is , with evaluated as (P1.G2). PyTorch’s BCEWithLogitsLoss takes the score and does this; the gradient with respect to the score is still (P3.A8 and P4.6 use the same idea for many classes). Adding a tiny constant such as inside the logarithm hides the problem and caps the loss near when it should be larger (P1.G2).
Intuition
Each point votes on where the line should go. A point on the wrong side pushes the line toward itself with a force close to its full size; a point on the right side pushes only a little, and the farther it is the less it pushes. Training lets the votes settle until they balance.
The sigmoid is a dimmer switch: far from the line the probability is near or , near the line it is near , and the weights set how quickly it changes. On separable data nothing balances the votes: each point always wants the switch a little sharper, so the line stays put and the dimmer keeps turning. The analogy breaks in one way: the votes also include a vote on , and the “force” is a gradient, not a physical push.
Math
Model: , so and when rises by .
Boundary: . Signed distance to it: , so . Threshold : .
Likelihood: . Negative log, averaged:
Gradient and Hessian (with including a column of ones, ):
With an L2 penalty on : add to the gradient and (on the weight block) to the Hessian, so the Hessian is positive definite on the weights and the minimizer is unique. Separable data with : as , with no minimizer.
Code
NumPy: p = 1 / (1 + np.exp(-(X @ w + b))), grad_w = X.T @ (p - y) / N, grad_b = (p - y).mean(). A stable loss: np.logaddexp(0, z) - y * z, averaged.
scikit-learn: LogisticRegression(C=1.0).fit(X, y), then .predict_proba(X) and .coef_, .intercept_ (shown above).
PyTorch: torch.nn.Linear(d, 1) gives the score and torch.nn.BCEWithLogitsLoss() takes and the float labels; do not put a sigmoid before it. For several classes the same idea is CrossEntropyLoss on the class scores (P3.A8). The training loop around them is the one of P2.7.
Try it
The first cell fits the six students with gradient descent, checks the gradient formula against a numerical difference quotient and compares the two gradients of the confident mistake. It uses only NumPy.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
The second cell shows the weight growing on separable data and the effect of the penalty.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
The third cell computes the loss from the score and compares it with the naive formula.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
For the last row, the stable loss is (a confident, very wrong answer), the naive formula gives infinity and the patched one gives about . Here is the same comparison in PyTorch (real output from PyTorch 2.9; not runnable in this page):
import torch
z = torch.tensor([-1000.0, 40.0, 2.0])
y = torch.tensor([1.0, 0.0, 1.0])
print(torch.nn.BCEWithLogitsLoss()(z, y).item()) # 346.709
print(torch.nn.BCELoss()(torch.sigmoid(z), y).item()) # 66.709
The two numbers differ because BCELoss works from probabilities: for the first two scores, rounds to and to , and the documentation says it clamps each logarithm to be at least , so it reports and where the true losses are and . The version that takes the score reports .
The fourth cell uses the 200-point data set of P1.F6, so the numbers can be compared.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
Challenge. In the second cell, change the data to two points that are not separable (add a point with and label ) and rerun the case. What happens to the weight?
Check your understanding
A logistic regression gives the score for an email. What are the probability of spam and the odds of spam?
The score is the log-odds, so the odds are and . The value mixes up odds and probability. The number is the log of the odds, not the odds. The threshold is used to decide the class: this email is above it, but the probability itself is .
A feature has weight . What happens when that feature rises by and all other features stay the same?
The weight adds to the log-odds, so the odds are multiplied by . The change in the probability depends on where you start, because the sigmoid is steepest in the middle: from the probability rises to , and from it rises only to . Adding to the odds, instead of multiplying them, would be the effect of a different kind of model.
The classes in a training set can be separated by one line, and a logistic regression is trained with gradient descent with no penalty. What happens to the weights as training continues?
Multiplying all the weights of a separating line by a number above lowers the loss, so no finite weights are best. There is no oscillation, because the loss is convex. The weights do not shrink: sharper probabilities need larger scores. An L2 penalty is what produces one best answer.
For one training example with label , the model gives and the features are . What is the gradient of the loss with respect to for this example?
The gradient is . Descent subtracts it, so the first weight goes down and the second goes up, lowering the score of this wrongly-scored example. The opposite sign would be right for a label and . The vector would be the result if the error were .
A model gives the score for an example whose label is . Which statement about computing the loss is correct?
The loss is , which a stable formula computes. The sigmoid rounds to , so the naive logarithm gives infinity, but the loss is not : this is a confident, very wrong answer. Adding removes the infinity and gives only about . The loss is defined for every score.
Exercises
- A model has and . For the point find the score, the probability and the odds.
Show answer
The score is , so and the odds are (check: ). - For and , write the decision boundary as a line , and write the boundary for the threshold .
Show answer
The score is . For threshold the boundary is , i.e. . For threshold we need the score to be , i.e. : a parallel line shifted down by . - One example has and label . Starting from , compute the gradient, one step with , and the loss before and after.
Show answer
At the start , so . The gradient is for and for . After the step and . The score at is , so . The loss falls from to . - In a model of purchases, the weight of “number of earlier purchases” is . A customer with no earlier purchases has . What is with one earlier purchase, other features equal?
Show answer
The odds at are . They are multiplied by , so the new odds are and . The probability rises by , not by and not by a factor of . - You train with scikit-learn using
C=0.01and thenC=100. Which has the smaller weights, and which can fit the training data better?Show answer
C=0.01is a strong penalty, so its weights are smaller and it fits the training data less closely.C=100is a weak penalty, so its weights are larger and its training loss is lower or equal. Which generalizes better is a question for validation data (P3.A4). - Show that for the loss from the score is .
Show answer
For the loss is . Since , the loss is .
Next: P3.A8 replaces the sigmoid by the softmax to handle many classes and reuses the loss and the gradient almost unchanged. P3.A9 turns the probabilities into decisions and measures them with the confusion matrix, precision, recall and the ROC curve, and P3.A10 asks whether the probabilities can be trusted.