Deriving Logistic Regression (ML #3)
Linear regression predicts a number. Your problem predicts a yes/no — “will this user churn?” — and you try it anyway. You get MSE 0.18, so you show it to the product team. They ask a question that exposes the whole flaw: “what does your model predict for a user who is 50% likely to churn?”
The answer is a number that isn’t 0 or 1, and it doesn’t mean anything. Squared error was never built for this. The fix isn’t a trick or a threshold — it’s recognizing that a binary label is the outcome of a random trial, and modeling that trial’s probability directly.
This chapter derives logistic regression from the Bernoulli likelihood. Along the way you’ll see cross-entropy appear as a consequence rather than a choice, understand why the model is a maximum-a-likelihood estimate, and learn why perfectly separable data makes logistic regression’s weights explode.
The problem with squared error on a label
Chapter 1’s objective \(\sum (y_i - \theta^\top x_i)^2\) implicitly assumes \(y_i\) is a noisy measurement of a continuous quantity. But \(y_i \in \{0,1\}\) is not noisy — it’s a sample from a distribution over two values. The right object to model is \(\Pr(Y = 1 \mid x)\), the probability the label is 1. Squared error doesn’t estimate that; it estimates a conditional mean and then pretends it’s a probability.
The deeper problem shows up in the gradient. For squared error, the update is \(\theta \leftarrow \theta - \eta X^\top(y - \hat y)\), which vanishes when the prediction is already close to the label. With a binary target, “close” is never achievable: to make a prediction move toward 0 you must keep pushing it past 0, and the model oscillates around the label rather than settling. Probabilities need a loss whose gradient keeps shrinking as the prediction approaches a boundary without ever overshooting past the valid range.
Step one: the sigmoid, and why it
We want \(\sigma(\theta^\top x) \in (0,1)\). Start with a linear score \(\theta^\top x\) — we need a squashing function \(\sigma\). Requirements: output in \((0,1)\), monotone increasing, and smooth so gradient descent works.
The logistic function satisfies all three:
\[ \sigma(z) = \frac{1}{1 + e^{-z}} \]
Two algebraic facts do all the work later. First, the symmetry \(\sigma(-z) = 1 - \sigma(z)\) — useful for computing probabilities from logits cheaply. Second, and this is the one that matters for optimization:
\[ \frac{d\sigma}{dz} = \sigma(z)\left(1 - \sigma(z)\right) \]
Note what this says: the derivative of the activation is expressed purely in terms of the activation itself. No exponentials, no chain rule mess. Every sigmoid derivative computation in every library reduces to \(p(1-p)\), and that fact is what will make the gradient collapse to a clean matrix product.
The model is \(\hat{p}_i = \sigma(\theta^\top x_i)\).
import numpy as np
def sigmoid(z):
return 1.0 / (1.0 + np.exp(-z))
# numerically stable in practice: split on sign to avoid overflow
def sigmoid_stable(z):
out = np.empty_like(z, dtype=float)
pos = z >= 0
out[pos] = 1.0 / (1.0 + np.exp(-z[pos]))
ez = np.exp(z[~pos])
out[~pos] = ez / (1.0 + ez)
return out
np.exp(-z) overflows for large negative \(z\); the stable version keeps the exponentials in range. Worth having when logits get large — which, as we’ll see, they do.
Step two: the likelihood
Now write down the probability of the observed labels. Assuming the \(y_i\) are conditionally independent given the \(\theta\)-shared features (the standard i.i.d. assumption), the joint probability is a product:
\[ P(y \mid X, \theta) = \prod_{i=1}^{n} \hat{p}_i^{y_i} (1 - \hat{p}_i)^{1-y_i} \]
Read this carefully: for a sample with \(y_i = 1\) the factor is \(\hat{p}_i\) (probability of observing the positive class); for \(y_i = 0\) it’s \((1-\hat{p}_i)\). One formula covers both cases — an idiom worth memorizing, because it will appear in every likelihood you derive.
Multiplying many numbers below 1 drives the product toward zero, so take logs (monotone, so the maximizer is unchanged):
\[ \log P(y \mid X, \theta) = \sum_{i=1}^{n} \left[ y_i \log \hat{p}_i + (1-y_i)\log(1-\hat{p}_i) \right] \]
Maximize this log-likelihood, which is equivalent to minimizing its negation, normalized:
\[ L(\theta) = -\frac{1}{n}\sum_{i=1}^{n} \left[ y_i \log \hat{p}_i + (1-y_i)\log(1-\hat{p}_i) \right] \]
This is binary cross-entropy. Nothing was chosen — it fell out of taking the negative log-likelihood of a Bernoulli trial. That’s the whole reason the name is incidental: the loss is “cross-entropy” because you’re measuring surprise between the predicted and observed distributions, but the derivation that produces it is probabilistic, not information-theoretic.
Step three: derive the gradient
This is where the sigmoid’s self-referential derivative pays off. Write \(z = \theta^\top x\), \(\hat{p} = \sigma(z)\), and take the derivative of one sample’s loss:
\[ \frac{\partial L_i}{\partial z} = -y\frac{\sigma'(z)}{\sigma(z)} + (1-y)\frac{-\sigma'(z)}{1-\sigma(z)} \]
Substitute \(\sigma'(z) = \sigma(z)(1-\sigma(z))\) and the terms collapse — \(\sigma\) cancels in both fractions:
\[ \frac{\partial L_i}{\partial z} = -y(1-\hat{p}) - (1-y)\hat{p} = \hat{p} - y \]
The gradient of cross-entropy with respect to the logit is just the prediction minus the label. No \(\sigma(1-\sigma)\) factor survives. Now chain through the logit with \(\frac{\partial z_i}{\partial \theta} = x_i\) and sum over samples:
\[ \nabla_\theta L = \frac{1}{n}\tilde{X}^\top (\hat{y} - y) \]
The identical form as Chapter 1’s squared-error gradient, with \(\hat{y}\) now meaning probability rather than prediction. That structural similarity is the reason logistic regression trains with the same optimizer — and the reason sigmoid is absent from the gradient code entirely.
Verified against central finite differences on random data: the analytic gradient matches to floating-point exactness.
import numpy as np
def fit_logistic(X, y, lr=0.5, iters=5000):
"""Maximize the log-likelihood by gradient ascent on the negated loss."""
n, d = X.shape
Xb = np.c_[X, np.ones(n)]
theta = np.zeros(d + 1)
for _ in range(iters):
p = 1.0 / (1.0 + np.exp(-(Xb @ theta)))
theta += lr * (Xb.T @ (y - p)) / n # gradient ASCENT on log-likelihood
return theta
def nll(X, y, theta):
z = np.c_[X, np.ones(len(X))] @ theta
return np.mean(np.logaddexp(0, z) - y * z) # stable: no log(0)
rng = np.random.default_rng(0)
X = rng.normal(size=(200, 2))
truth = np.array([2.0, -1.0])
y = (rng.random(200) < 1 / (1 + np.exp(-(X @ truth)))).astype(float)
theta = fit_logistic(X, y)
print(np.round(theta, 4)) # [ 2.5728 -1.1545 -0.0785]
print("nll:", round(nll(X, y, theta), 6)) # 0.380987
On genuinely non-separable data (labels drawn from the true sigmoid), the fit recovers the generating direction (\(\theta_1 \approx 2.57\) against a true 2.0, \(\theta_2 \approx -1.15\) against a true \(-1.0\) — the intercept is the noisy one, as expected) and stops: the loss settles at 0.3810 and further iterations change nothing. That’s not underfitting; it’s the optimum, and the reason is convexity. The Hessian is
\[ \nabla^2_\theta L = \frac{1}{n}\tilde{X}^\top \text{diag}\!\left(\hat{p}(1-\hat{p})\right) \tilde{X} \]
which is positive semidefinite because \(\hat{p}(1-\hat{p}) > 0\) and the diagonal matrix is PSD, so the whole product is PSD. Convexity guarantees a unique global optimum. Verified: all eigenvalues of that Hessian are strictly positive.
Why this loss and not squared error
Compare the two gradients, since both reduce to \(\tilde{X}^\top(\text{prediction} - \text{label})\):
| squared error | logistic | |
|---|---|---|
| prediction | any real number | constrained to \((0,1)\) |
| gradient | \(\tilde{X}^\top(\hat{y}-y)/n\) | \(\tilde{X}^\top(\hat{p}-y)/n\) |
| \(\hat{y} \in (0,1)\)? | no | yes, by construction |
| valid for classification | no | yes |
The gradient forms are nearly identical, but only one of them has a prediction in the right range. Squared error lets the model output \(-3\) for a certain positive; the sigmoid cannot. That constraint is the difference between the two losses, and it’s why logistic regression is the default for binary targets.
The decision boundary is linear
Set \(P(Y=1 \mid x) = 0.5\). Since \(\sigma\) is monotone and \(\sigma(0) = 0.5\), this is just \(\theta^\top x = 0\) — a hyperplane. The boundary’s orientation is linear even though the probability isn’t:
\begin{tikzpicture}[font=\rmfamily, >=stealth,
b/.style={draw, thick, rounded corners=4pt, minimum width=1.75cm, minimum height=0.62cm, align=center, font=\rmfamily\scriptsize}]
\fill[blue!10] (-4.4,0.05) -- (0.4,-3.4) -- (0.4,3.4) -- (-4.4,3.4) -- cycle;
\fill[orange!16] (0.4,0.05) -- (4.6,-3.4) -- (4.6,3.4) -- (0.4,3.4) -- cycle;
\foreach \x in {-3.6,-2.6,-1.6} \foreach \y in {-2.6,-1.6,-0.6,0.6,1.6,2.6}
\fill[blue!70!black] (\x,\y) circle (1.6pt);
\foreach \x in {1.2,2.2,3.2,4.0} \foreach \y in {-2.6,-1.6,-0.6,0.6,1.6,2.6}
\fill[orange!90!black] (\x,\y) circle (1.6pt);
\draw[very thick] (0.4,-3.4) -- (0.4,3.4) node[above right, font=\rmfamily\scriptsize] {$\theta^\top x = 0$};
\node[b, fill=blue!10] at (-2.6,-3.0) {$\hat p \approx 0$};
\node[b, fill=orange!16] at (2.8,-3.0) {$\hat p \approx 1$};
\node[font=\rmfamily\scriptsize, text=black!60] at (0,-4.0) {boundary linear; probabilities curved};
\end{tikzpicture}
This is the limitation to internalize: logistic regression cannot carve out a circular or diagonal boundary in the raw feature space. When the classes form concentric rings, no \(\theta\) works. The fixes are engineered interaction features, an explicit polynomial basis, or a kernel (Chapter 9’s SVM makes this boundary non-linear in the original space).
The separation trap: weights that diverge
Here’s a failure mode unique to this model. Take data that’s perfectly separable — every positive example strictly on one side of some line. Then there exists a \(\theta\) making \(\hat{p}_i\) arbitrarily close to the correct hard label for every \(i\):
\[ L(\theta) \to 0 \quad \text{as} \quad \|\theta\| \to \infty \]
The maximum-likelihood estimate does not exist: the loss has an infimum of zero that is never attained. Verified on separable data — the loss keeps falling and the weights keep growing:
| iterations | \(\lVert\theta\rVert\) | loss | accuracy |
|---|---|---|---|
| 50 | 3.02 | 0.1772 | 0.950 |
| 500 | 7.55 | 0.0663 | 0.975 |
| 5000 | 16.86 | 0.0189 | 1.000 |
Compare that with the non-separable case, where training stops at \(\|\theta\| \approx 2.9\) and stays. Two practical consequences:
- L2 regularization is mandatory, not optional. The penalty \(\lambda\lVert\theta\rVert^2/2\) makes the objective coercive, guaranteeing the weights stay bounded and the MLE exists. This is the single most common fix.
- Accuracy saturates long before the loss does. At \(\lVert\theta\rVert = 3\) you already predict every label correctly. Training the last ten iterations to reduce loss from 0.066 to 0.019 changes no prediction and only inflates the weights — which is why logistic coefficients from separable data are huge, and why
coef_values in the hundreds should alarm you.
theta_reg = fit_logistic(X, y) # unseparable example above: safe
print("bounded:", np.abs(theta_reg).max() < 10) # True
# on separable data, add L2 and watch weights stop diverging:
def fit_logistic_l2(X, y, lam=1.0, lr=0.5, iters=5000):
n, d = X.shape
Xb = np.c_[X, np.ones(n)]
w = np.zeros(d + 1)
for _ in range(iters):
p = 1.0 / (1.0 + np.exp(-(Xb @ w)))
w += lr * (Xb.T @ (y - p) / n - lam * w)
return w
Pitfalls
- Skipping regularization on separable data. The MLE doesn’t exist; unregularized weights blow up and coefficients become meaningless. Always pass
C/alpha. - Over-interpreting coefficient magnitudes. Large weights can mean separation, not importance. Compare signs and relative magnitudes, not absolute scale.
- Threshold 0.5 by reflex. The 0.5 boundary is only correct when classes are balanced and error costs are symmetric. Tune the threshold on validation data for your actual costs (Chapter 14).
- Computing
log(1-p)naively.np.log(1 - p)gives-infwhen \(p\) rounds to 1. Usenp.logaddexp(0, z) - y*z. - Assuming linear boundaries means linear data. The boundary is linear in the given features; interaction terms make it non-linear without changing the model class.
- Reporting accuracy alone on imbalanced data. 99% accuracy on 1% positives means nothing. Check precision/recall and AUC (Chapter 14).
Derive \(\frac{\partial L_i}{\partial z}\) for binary cross-entropy and show why the \(\sigma'\) terms cancel. Why does the Hessian being PSD matter — what does it guarantee that squared-error regression doesn’t need? Your logistic model reaches 100% training accuracy but \(\lVert\theta\rVert = 60\). What’s happening, and what is the minimal fix?
ASolution
\(\frac{\partial L_i}{\partial z} = -y\frac{\sigma'}{\sigma} + (1-y)\frac{-\sigma'}{1-\sigma}\); substituting \(\sigma' = \sigma(1-\sigma)\) cancels \(\sigma\) in both terms, giving \(-y(1-\hat p) - (1-y)\hat p = \hat p - y\). PSD-ness of the Hessian means \(L\) is convex, so any stationary point is a global minimum and the optimum is unique (verified: all eigenvalues strictly positive) — no initialization dependence, no local minima to fall into, unlike neural networks (Chapter 4). On the diverging weights: the data is perfectly separable, so pushing \(\theta\) along the separating direction drives \(\hat p\) toward the hard labels and \(L \to 0\) while \(\lVert\theta\rVert \to \infty\) — the maximum-likelihood estimate does not exist. Accuracy saturates around \(\lVert\theta\rVert \approx 3\) and the remaining loss reduction buys zero extra correct predictions. The minimal fix is L2 regularization, \(\lambda\lVert\theta\rVert^2/2\), which makes the objective coercive so the optimum is attained at finite weights; with it, training stops at a bounded norm.
Next: Deriving Gradient Descent (ML #4) — the optimizers themselves: convexity, stochasticity, and why Newton’s method uses the Hessian.