Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 3: Classical Machine LearningCore Concepts

Logistic regression

P3.A742 min●●○ IntermediateReviewed Dec 2, 2026

Why this matters for machine learning

Logistic regression is the simplest model that answers “yes or no” with a probability. Its pieces (a score, a sigmoid, the binary cross-entropy and its gradient p−yp-y) are the output layer of almost every neural-network classifier.

  • A neural-network classifier ends in a logistic regression on its last hidden layer: one score, a sigmoid, and the binary cross-entropy computed from the score. (P4.6: Loss functions)
  • Softmax regression, the multi-class version, replaces the sigmoid by the softmax and keeps the same loss and the same gradient form. (P3.A8: Softmax regression)
  • Metrics such as precision and recall depend on the threshold you put on the probability, which moves the decision boundary. (P3.A9: Evaluation metrics)
  • Whether the probability can be trusted (calibration), and what to do when one class is rare, build on this model. (P3.A10: Calibration and class imbalance)

Before this: Linear regression, The sigmoid, tanh and other squashing functions, Maximum Likelihood Estimation

After this lesson you can

  • Compute a probability from a score with the sigmoid, and read the weights as changes in the log-odds
  • Find and draw the decision boundary of a logistic regression, and say how a threshold other than 0.5 moves it
  • Derive the binary cross-entropy from the Bernoulli likelihood and its gradient (p−y) x(p-y)\,\mathbf{x}, and take one gradient-descent step by hand
  • Explain why the loss is convex, why the weights grow without bound on separable data, and how an L2 penalty stops that

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: “85%85\% likely to pass”.

Linear regression (P3.A2) draws a line through numbers, and its output can be any number. A probability must stay between 00 and 11. Logistic regression fixes this with one extra step: compute a score exactly as linear regression does, then squeeze it into (0,1)(0,1) 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 p−yp-y, 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 (11) or failed (00).

hours xx123456
passed yy001011

More hours tend to mean more passes, but not always (the student with 44 hours failed). A straight line fitted by least squares to these labels is y^=0.2x−0.2\hat y=0.2x-0.2. It is 00 at x=1x=1 and 1.21.2 at x=7x=7: it cannot be read as a probability.

Logistic regression keeps the linear score (also called the logit) and passes it through the sigmoid σ(z)=11+e−z\sigma(z)=\dfrac{1}{1+\mathrm{e}^{-z}} from P1.A5:

z=w⋅x+b,p=σ(z)=11+e−z.\begin{aligned} z&=\mathbf{w}\cdot\mathbf{x}+b,\\ p&=\sigma(z)=\frac{1}{1+\mathrm{e}^{-z}}. \end{aligned}

The number pp is the model’s probability that the label is 11. A score of 00 gives p=0.5p=0.5; the scores −2,−1,1,2-2,-1,1,2 give 0.1192, 0.2689, 0.7311, 0.88080.1192,\ 0.2689,\ 0.7311,\ 0.8808. A very large score gives a pp close to 11 and a very negative one a pp close to 00, never outside.

The best weights for the six students (found below) are w=1.214w=1.214 and b=−4.249b=-4.249. For 44 hours the score is 1.214×4−4.249=0.6071.214\times4-4.249=0.607 and p=σ(0.607)=0.647p=\sigma(0.607)=0.647; for 22 hours it is 0.1390.139; for 55 hours, 0.8610.861.

The score is the log-odds

The odds of an event with probability pp are p1−p\frac{p}{1-p}: p=0.8p=0.8 means odds of 44 to 11. The natural logarithm of the odds is the log-odds, or logit. Solving p=σ(z)p=\sigma(z) for zz gives

z=ln⁡p1−p.z=\ln\frac{p}{1-p}.

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 xjx_j by 11 and keep every other feature fixed: the score rises by wjw_j, so the odds are multiplied by ewj\mathrm{e}^{w_j}. For the students, e1.214=3.367\mathrm{e}^{1.214}=3.367: every extra hour multiplies the odds of passing by about 3.43.4. At 33 hours the odds are 0.5450.545 and at 44 hours they are 1.8351.835 (1.835/0.545=3.3671.835/0.545=3.367).

Careful with two points. The odds are multiplied, but the probability is not: going from 11 to 22 hours moves pp from 0.0460.046 to 0.1390.139, while going from 33 to 44 moves it from 0.3530.353 to 0.6470.647. 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 0.50.5: predict class 11 when p>0.5p>0.5. Because σ(0)=0.5\sigma(0)=0.5 and the sigmoid only increases, p>0.5p>0.5 exactly when z>0z>0. So the model predicts class 11 when

w⋅x+b>0,\mathbf{w}\cdot\mathbf{x}+b>0 ,

and the decision boundary is the set of points where w⋅x+b=0\mathbf{w}\cdot\mathbf{x}+b=0. 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: w=(1,2)\mathbf{w}=(1,2) and b=−3b=-3. The boundary x1+2x2=3x_1+2x_2=3 is the line through (1,1)(1,1) and (3,0)(3,0). The point (2,2)(2,2) has score 2+4−3=32+4-3=3 and p=0.9526p=0.9526; the point (0,0)(0,0) has score −3-3 and p=0.0474p=0.0474.

The vector w\mathbf{w} is perpendicular to the boundary and points toward the class-11 side (P1.B3). The score is the signed distance to the line times the length of w\mathbf{w}: the point (2,2)(2,2) is 3/5=1.3423/\sqrt{5}=1.342 units from the line, and ∥w∥×1.342=5×1.342=3\lVert\mathbf{w}\rVert\times1.342=\sqrt5\times1.342=3. So p=σ(∥w∥ d)p=\sigma(\lVert\mathbf{w}\rVert\,d) with dd the signed distance, and the probability depends only on how far you are from the boundary. A large ∥w∥\lVert\mathbf{w}\rVert makes the sigmoid change quickly across the boundary (a sharp, confident model); a small one changes slowly.

Other thresholds. The threshold 0.50.5 is a choice, not a law. Requiring p>tp>t means requiring z>ln⁡t1−tz>\ln\frac{t}{1-t}, a line parallel to the first one and shifted. For t=0.8t=0.8 the score must exceed ln⁡4=1.386\ln4=1.386; for t=0.2t=0.2, −1.386-1.386. For the students, the boundary at t=0.5t=0.5 is x=3.5x=3.5 hours, at t=0.8t=0.8 it moves to 4.644.64 hours and at t=0.2t=0.2 to 2.362.36 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 x12x_1^2 or x1x2x_1x_2 (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 11 is pp”. The Bernoulli distribution gives the label the probability p y(1−p)1−yp^{\,y}(1-p)^{1-y}: it is pp if y=1y=1 and 1−p1-p if y=0y=0. 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

L=−[ yln⁡p+(1−y)ln⁡(1−p) ],L=-\bigl[\,y\ln p+(1-y)\ln(1-p)\,\bigr],

and L\mathcal{L}, its average over the NN training examples, is the binary cross-entropy (BCE), the cross-entropy of P1.E3 for two classes. With p=σ(z)p=\sigma(z), it is the negative log of the probability the model gave to the right answer.

A small check, from P1.D10: for labels (1,0,1)(1,0,1) and predictions (0.8,0.3,0.6)(0.8,0.3,0.6) the right answers got 0.8, 0.7, 0.60.8,\ 0.7,\ 0.6, so the losses are 0.2231, 0.3567, 0.51080.2231,\ 0.3567,\ 0.5108 and the average is 0.36350.3635. A confident mistake is costly: p=0.8p=0.8 for a true 00 costs −ln⁡0.2=1.609-\ln0.2=1.609, and p=0.99p=0.99 costs −ln⁡0.01=4.605-\ln0.01=4.605. A model that always says 0.50.5 has loss ln⁡2=0.6931\ln2=0.6931, a useful number to compare with when training starts.

Why not squared error on the probability? One could minimize (p−y)2(p-y)^2. Two things go wrong. First, the slope is almost zero exactly when the model is most wrong. For a label 11 and a score z=−5z=-5 (so p=0.0067p=0.0067), the slope of the cross-entropy with respect to zz is p−1=−0.9933p-1=-0.9933 (P1.C3), but the slope of (p−1)2(p-1)^2 is only −0.0132-0.0132 because it is multiplied by the flat sigmoid tail p(1−p)p(1-p). 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 x=1x=1 and label y=1y=1, so the loss is (σ(w)−1)2(\sigma(w)-1)^2 as a function of the weight ww. Its second derivative is 0.1250.125 at w=0w=0 and −0.0129-0.0129 at w=−5w=-5 (a finite-difference check). A negative second derivative means the curve bends downward there, so the loss is not convex, while the cross-entropy −ln⁡σ(w)-\ln\sigma(w) has second derivative σ(w)(1−σ(w))≥0\sigma(w)(1-\sigma(w))\ge0 everywhere.

The gradient

For one example, write the loss as a function of the score. The chain rule (P1.C3) has three links: LL depends on pp, p=σ(z)p=\sigma(z) depends on zz, and z=w⋅x+bz=\mathbf{w}\cdot\mathbf{x}+b depends on the weights.

∂L∂p=−yp+1−y1−p,∂p∂z=p(1−p),∂L∂z=(−yp+1−y1−p)p(1−p)=p−y.\begin{aligned} \frac{\partial L}{\partial p}&=-\frac{y}{p}+\frac{1-y}{1-p},\\ \frac{\partial p}{\partial z}&=p(1-p),\\ \frac{\partial L}{\partial z}&=\Bigl(-\frac{y}{p}+\frac{1-y}{1-p}\Bigr)p(1-p)\\ &=p-y. \end{aligned}

The factors pp and 1−p1-p cancel, leaving the same “prediction minus target” as in linear regression. Since ∂z/∂w=x\partial z/\partial\mathbf{w}=\mathbf{x} and ∂z/∂b=1\partial z/\partial b=1, the gradient of the average loss is

∇wL=1N∑i=1N(pi−yi) xi,∂L∂b=1N∑i=1N(pi−yi).\begin{aligned} \nabla_{\mathbf{w}}\mathcal{L}&=\frac1N\sum_{i=1}^{N}(p_i-y_i)\,\mathbf{x}_i,\\ \frac{\partial\mathcal{L}}{\partial b}&=\frac1N\sum_{i=1}^{N}(p_i-y_i). \end{aligned}

In matrix form this is 1NX⊤(p−y)\frac1N\mathbf{X}^\top(\mathbf{p}-\mathbf{y}). Read it as a vote: each example pushes the weights along its own x\mathbf{x}, with a strength equal to its error, and an example that is already right (p≈yp\approx y) hardly pushes at all.

One step by hand on the six students. Start at w=0, b=0w=0,\ b=0, so every p=0.5p=0.5:

xxyyp−yp-y(p−y) x(p-y)\,x
100.50.5
200.51.0
31−0.5−1.5
400.52.0
51−0.5−2.5
61−0.5−3.0

The (p−y) x(p-y)\,x column adds to −3.5-3.5, so ∂L/∂w=−3.5/6=−0.5833\partial\mathcal{L}/\partial w=-3.5/6=-0.5833, and ∂L/∂b=0\partial\mathcal{L}/\partial b=0 (the p−yp-y column adds to 00). With step size η=0.5\eta=0.5 the weight becomes w=0.2917w=0.2917 and b=0b=0, and the loss drops from 0.69310.6931 to 0.67200.6720. 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 σ(w1x1+w2x2+b)\sigma(w_1x_1+w_2x_2+b), the thick line is the boundary and the readouts are the quantities above.

Train a logistic regression on 2-D points

Two clouds that overlap a little: no line is perfect, so the best line still makes a few mistakes. These points are made up.

● class 1   ■ class 0   thick line: p = 0.5 (z = 0); thin lines: p = 0.25 and 0.75; red ring: wrong side; arrow: direction of w.

Safe step size from the curvature bound: 1/L = 2.31.

step 0
accuracy 12/24
w₁ = 0
w₂ = 0
b = 0
‖w‖ = 0
BCE loss = 0.6931
‖gradient‖ = 0.4542

The weights are all 0, so every probability is 0.5. Press Play, or step by hand.

0.750BCE losssteps, log scale0110100 10‖w‖0110100steps, log scale

The objective is the mean binary cross-entropy plus (λ/2)‖w‖², and the bias b is not penalised. The shading is σ(w₁x₁ + w₂x₂ + b): darker means more sure. Keyboard: Tab to a point, arrow keys move it (Shift for bigger steps), C flips its class, Delete removes it, Page Up and Page Down choose another point.

Logistic regression on made-up 2-D points. Blue circles are class 1 and pink squares are class 0. The shading is the model's probability of class 1; the thick line is the decision boundary (p = 0.5) and the thin dashed lines are p = 0.25 and p = 0.75. Pick a data set, press Play (or Step), and watch the line move while the loss falls. Drag the points, or use the keyboard, or add and remove points. The step size η and the penalty λ are sliders. The readouts show the weights, the loss and the number of points on the correct side, and two charts show the loss and the length of the weight vector against the step count on a log scale. In Lite Mode there is no animation: the button trains to the end at once.

Things to try, one at a time:

  • Overlapping, λ = 0. Press Play until the status says “Converged”. The line makes 44 mistakes out of 2424 points and the loss stops near 0.3900.390 with w≈(1.54, 1.10)w\approx(1.54,\,1.10) and b≈0.21b\approx0.21. Raise λ to 0.10.1 and continue: the weights shrink to about (0.79, 0.67)(0.79,\,0.67), the line turns a little, the loss rises to about 0.4260.426 and one more of the 2424 points ends up on the wrong side (1919 of 2424 correct instead of 2020). 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 ∥w∥\lVert\mathbf{w}\rVert keeps climbing while the loss creeps toward 00. Press +10 000 twice. Then set λ to 0.10.1 and train again: the weights settle at about (1.21, 0.87)(1.21,\,0.87) and b≈0.48b\approx0.48.
  • Corners. No line separates the corners, and the accuracy stays near 50%50\% at a loss close to ln⁡2=0.693\ln2=0.693.
  • Step size. The widget shows the safe step 1/L1/L. Above 2/L2/L the steps can overshoot, and a warning appears. On Corners, set η to 33 and watch the loss bounce. On the other two data sets 2/L2/L 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 zz, and its second derivative with respect to zz is p(1−p)p(1-p), which lies between 00 and 0.250.25 and is never negative. The score zz 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 (w,b)(\mathbf{w},b): 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 1NX⊤SX\frac1N\mathbf{X}^\top\mathbf{S}\mathbf{X} with S=diag(pi(1−pi))\mathbf{S}=\mathrm{diag}\bigl(p_i(1-p_i)\bigr) (here X\mathbf{X} has a column of ones for the bias). It is positive semidefinite, which is another proof of convexity, and it never exceeds 14NX⊤X\frac{1}{4N}\mathbf{X}^\top\mathbf{X}, which gives the safe step size 1/L1/L with LL the largest eigenvalue of that matrix (P1.B10). The widget shows this 1/L1/L.

Newton’s method (P1.F6) solves HΔ=−g\mathbf{H}\boldsymbol{\Delta}=-\mathbf{g} at each step. Each solve has the form of a weighted least-squares problem whose weights pi(1−pi)p_i(1-p_i) 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 77 steps and gradient descent with η=1/L\eta=1/L needs 302302 to bring the gradient norm below 10−810^{-8}. With dd weights and at least about dd examples, each Newton step costs about dd 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-11 points on its positive side and all the class-00 points on its negative side: the data are linearly separable. Take any such weights (w,b)(\mathbf{w},b) and multiply all of them by s>1s>1. Every score moves farther from 00 on the correct side, every probability of the right answer moves closer to 11, and the loss falls. So the loss can always be lowered, by making the weights larger and larger. It gets closer to 00 and never reaches it: there is no best finite answer. P1.F1 showed the smallest case: for one example with label 11 and x=1x=1 the loss −ln⁡σ(w)-\ln\sigma(w) is 0.6930.693 at w=0w=0, 0.1270.127 at w=2w=2 and 0.00670.0067 at w=5w=5.

Gradient descent shows it clearly. Take four made-up points with x=−2,−1,1,2x=-2,-1,1,2 and labels 0,0,1,10,0,1,1, and η=0.5\eta=0.5. The weight ww after 1, 10, 100, 1 0001,\ 10,\ 100,\ 1\,000 and 10 00010\,000 steps is 0.375, 1.557, 3.376, 5.5480.375,\ 1.557,\ 3.376,\ 5.548 and 7.8287.828, while the loss falls from 0.4550.455 to 0.00020.0002. Each tenfold increase in the number of steps adds about 2.32.3 to ww 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 (00 and 11 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 λ2∥w∥2\frac{\lambda}{2}\lVert\mathbf{w}\rVert^2 to the loss, usually leaving the bias bb out. Now growing the weights has a price, the objective is strictly convex in w\mathbf{w}, and there is exactly one best answer. On the four points, λ=0.01, 0.1\lambda=0.01,\ 0.1 and 11 give w=2.902, 1.458w=2.902,\ 1.458 and 0.4720.472. The larger the penalty, the smaller the weights and the closer the probabilities are to 0.50.5. Here λ\lambda multiplies the penalty next to the average loss. It is not the same number as the λ\lambda 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 C∑iLi+12∥w∥2C\sum_i L_i+\frac12\lVert\mathbf{w}\rVert^2, which is the same as the widget’s objective with λ=1CN\lambda=\frac{1}{CN} (with NN 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 ww from 1.2141.214 to 0.7670.767, so pp at 44 hours falls from 0.6470.647 to 0.5950.595, but the boundary −b/w=3.5-b/w=3.5 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 η=1/L\eta=1/L, the raw hours need about 3 0003\,000 steps to bring the gradient norm below 10−610^{-6}, while the standardized hours (mean 00, population standard deviation 11) need about 3535. 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 99%99\% of the examples are class 00, always answering 00 is 99%99\% 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 σ(1.2)=0.7685=e1.2e1.2+e0\sigma(1.2)=0.7685=\frac{\mathrm{e}^{1.2}}{\mathrm{e}^{1.2}+\mathrm{e}^{0}}.

Computing the loss. The formula −[yln⁡σ(z)+(1−y)ln⁡(1−σ(z))]-\bigl[y\ln\sigma(z)+(1-y)\ln(1-\sigma(z))\bigr] breaks in floating point: for z=40z=40 and y=0y=0, σ(z)\sigma(z) rounds to exactly 1.01.0 and the loss is −ln⁡0=∞-\ln0=\infty, although the true value is 4040. The stable form works from the score: the loss for label 11 is softplus(−z)\mathrm{softplus}(-z) and for label 00 it is softplus(z)\mathrm{softplus}(z), with softplus(u)=ln⁡(1+eu)\mathrm{softplus}(u)=\ln(1+\mathrm{e}^{u}) evaluated as max⁡(u,0)+ln⁡(1+e−∣u∣)\max(u,0)+\ln(1+\mathrm{e}^{-|u|}) (P1.G2). PyTorch’s BCEWithLogitsLoss takes the score and does this; the gradient with respect to the score is still p−yp-y (P3.A8 and P4.6 use the same idea for many classes). Adding a tiny constant such as 10−810^{-8} inside the logarithm hides the problem and caps the loss near 18.418.4 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 00 or 11, near the line it is near 0.50.5, 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 bb, and the “force” is a gradient, not a physical push.

Math

Model: p(y=1∣x)=σ(w⋅x+b)p(y=1\mid\mathbf{x})=\sigma(\mathbf{w}\cdot\mathbf{x}+b), so ln⁡p1−p=w⋅x+b\ln\frac{p}{1-p}=\mathbf{w}\cdot\mathbf{x}+b and odds→odds⋅ewj\mathrm{odds}\to\mathrm{odds}\cdot\mathrm{e}^{w_j} when xjx_j rises by 11.

Boundary: {x:w⋅x+b=0}\{\mathbf{x}:\mathbf{w}\cdot\mathbf{x}+b=0\}. Signed distance to it: d=w⋅x+b∥w∥d=\dfrac{\mathbf{w}\cdot\mathbf{x}+b}{\lVert\mathbf{w}\rVert}, so p=σ(∥w∥d)p=\sigma(\lVert\mathbf{w}\rVert d). Threshold tt: z>ln⁡t1−tz>\ln\frac{t}{1-t}.

Likelihood: ∏ipi yi(1−pi)1−yi\prod_i p_i^{\,y_i}(1-p_i)^{1-y_i}. Negative log, averaged:

L=−1N∑i[yiln⁡pi+(1−yi)ln⁡(1−pi)]=1N∑i[softplus(zi)−yizi].\begin{aligned} \mathcal{L}&=-\frac1N\sum_i\bigl[y_i\ln p_i\\ &\qquad\qquad+(1-y_i)\ln(1-p_i)\bigr]\\ &=\frac1N\sum_i\bigl[\mathrm{softplus}(z_i)-y_iz_i\bigr]. \end{aligned}

Gradient and Hessian (with X\mathbf{X} including a column of ones, S=diag(pi(1−pi))\mathbf{S}=\mathrm{diag}(p_i(1-p_i))):

∇L=1NX⊤(p−y),∇2L=1NX⊤SX⪰0.\begin{aligned} \nabla\mathcal{L}&=\frac1N\mathbf{X}^\top(\mathbf{p}-\mathbf{y}),\\ \nabla^2\mathcal{L}&=\frac1N\mathbf{X}^\top\mathbf{S}\mathbf{X}\succeq0. \end{aligned}

With an L2 penalty on w\mathbf{w}: add λw\lambda\mathbf{w} to the gradient and λI\lambda\mathbf{I} (on the weight block) to the Hessian, so the Hessian is positive definite on the weights and the minimizer is unique. Separable data with λ=0\lambda=0: L(sw,sb)→0\mathcal{L}(s\mathbf{w},sb)\to0 as s→∞s\to\infty, 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 zz and torch.nn.BCEWithLogitsLoss() takes zz 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.

Try it: fit the six students and check the gradient

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.

Try it: separable data and the L2 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.

Try it: the loss from the score, and 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 10001000 (a confident, very wrong answer), the naive formula gives infinity and the patched one gives about 18.418.4. 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, σ(z)\sigma(z) rounds to 00 and to 11, and the documentation says it clamps each logarithm to be at least −100-100, so it reports 100100 and 100100 where the true losses are 10001000 and 4040. The version that takes the score reports 346.709=(1000+40+0.127)/3346.709=(1000+40+0.127)/3.

The fourth cell uses the 200-point data set of P1.F6, so the numbers can be compared.

Try it: Newton's method against gradient descent

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 x=1.5x=1.5 and label 00) and rerun the λ=0\lambda=0 case. What happens to the weight?

Check your understanding

  1. A logistic regression gives the score z=ln⁡3=1.099z=\ln3=1.099 for an email. What are the probability of spam and the odds of spam?

  2. A feature has weight wj=0.5w_j=0.5. What happens when that feature rises by 11 and all other features stay the same?

  3. 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?

  4. For one training example with label 00, the model gives p=0.9p=0.9 and the features are x=(2,−1)\mathbf{x}=(2,-1). What is the gradient of the loss with respect to w\mathbf{w} for this example?

  5. A model gives the score z=−1000z=-1000 for an example whose label is 11. Which statement about computing the loss is correct?

Exercises

  1. A model has w=(1,2)\mathbf{w}=(1,2) and b=−3b=-3. For the point (3,1)(3,1) find the score, the probability and the odds.
    Show answerThe score is 3+2−3=23+2-3=2, so p=σ(2)=0.8808p=\sigma(2)=0.8808 and the odds are e2=7.389\mathrm{e}^{2}=7.389 (check: 0.8808/0.1192=7.390.8808/0.1192=7.39).
  2. For w=(2,−1)\mathbf{w}=(2,-1) and b=1b=1, write the decision boundary as a line x2=…x_2=\dots, and write the boundary for the threshold 0.90.9.
    Show answerThe score is 2x1−x2+12x_1-x_2+1. For threshold 0.50.5 the boundary is 2x1−x2+1=02x_1-x_2+1=0, i.e. x2=2x1+1x_2=2x_1+1. For threshold 0.90.9 we need the score to be ln⁡9=2.197\ln9=2.197, i.e. x2=2x1+1−2.197=2x1−1.197x_2=2x_1+1-2.197=2x_1-1.197: a parallel line shifted down by 2.1972.197.
  3. One example has x=(1,2)\mathbf{x}=(1,2) and label 11. Starting from w=(0,0), b=0\mathbf{w}=(0,0),\ b=0, compute the gradient, one step with η=1\eta=1, and the loss before and after.
    Show answerAt the start p=0.5p=0.5, so p−y=−0.5p-y=-0.5. The gradient is (−0.5,−1)(-0.5,-1) for w\mathbf{w} and −0.5-0.5 for bb. After the step w=(0.5,1)\mathbf{w}=(0.5,1) and b=0.5b=0.5. The score at x\mathbf{x} is 0.5+2+0.5=30.5+2+0.5=3, so p=0.9526p=0.9526. The loss falls from ln⁡2=0.6931\ln2=0.6931 to −ln⁡0.9526=0.0486-\ln0.9526=0.0486.
  4. In a model of purchases, the weight of “number of earlier purchases” is 0.70.7. A customer with no earlier purchases has p=0.2p=0.2. What is pp with one earlier purchase, other features equal?
    Show answerThe odds at p=0.2p=0.2 are 0.250.25. They are multiplied by e0.7=2.014\mathrm{e}^{0.7}=2.014, so the new odds are 0.50340.5034 and p=0.5034/1.5034=0.3349p=0.5034/1.5034=0.3349. The probability rises by 0.1350.135, not by 0.70.7 and not by a factor of 2.0142.014.
  5. You train with scikit-learn using C=0.01 and then C=100. Which has the smaller weights, and which can fit the training data better?
    Show answerC=0.01 is a strong penalty, so its weights are smaller and it fits the training data less closely. C=100 is 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).
  6. Show that for y=0y=0 the loss from the score is softplus(z)\mathrm{softplus}(z).
    Show answerFor y=0y=0 the loss is −ln⁡(1−σ(z))-\ln(1-\sigma(z)). Since 1−σ(z)=e−z1+e−z=11+ez1-\sigma(z)=\frac{\mathrm{e}^{-z}}{1+\mathrm{e}^{-z}}=\frac{1}{1+\mathrm{e}^{z}}, the loss is ln⁡(1+ez)=softplus(z)\ln(1+\mathrm{e}^{z})=\mathrm{softplus}(z).

Next: P3.A8 replaces the sigmoid by the softmax to handle many classes and reuses the loss and the gradient p−yp-y 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.

Key takeaways

  • A logistic regression computes a score z=w⋅x+bz=\mathbf{w}\cdot\mathbf{x}+b and turns it into a probability p=σ(z)p=\sigma(z). The score is the log-odds: z=ln⁡p1−pz=\ln\frac{p}{1-p}.
  • Raising one feature by 1 while the others are held fixed adds wjw_j to the log-odds, so it multiplies the odds by ewj\mathrm{e}^{w_j}. It does not add wjw_j to the probability.
  • The decision boundary w⋅x+b=0\mathbf{w}\cdot\mathbf{x}+b=0 is a straight line (a flat hyperplane in more dimensions). The threshold 0.50.5 is the score 00; a threshold tt moves the line to the score ln⁡t1−t\ln\frac{t}{1-t}, parallel to the first one.
  • The loss is the binary cross-entropy −[yln⁡p+(1−y)ln⁡(1−p)]-[y\ln p+(1-y)\ln(1-p)], the negative log-likelihood of Bernoulli labels. Its gradient with respect to the weights is the average of (p−y) x(p-y)\,\mathbf{x}, and it is convex, so gradient descent cannot get stuck in a local minimum.
  • If one line separates the classes, the loss can be lowered forever by growing the weights, so unregularized training never stops by itself. An L2 penalty λ2∥w∥2\frac{\lambda}{2}\lVert\mathbf{w}\rVert^2 gives a finite answer.
  • Compute the loss from the score (the softplus form), not from σ(z)\sigma(z) followed by a logarithm: that is what BCEWithLogitsLoss does. The output is a probability only in the sense of the model; whether it matches real frequencies is a separate check (P3.A10).
Found a mistake? Tell us