Simple Algorithm
Machine Learning · Descent · 24 min

Logistic Regression & Linear Classifiers

From scores to probabilities: the sigmoid, cross-entropy and decision boundaries.

When the answer is yes or no, logistic regression is the model to try first: a linear score, a sigmoid, and a loss that turns out to be convex. This lesson derives it from maximum likelihood, computes its gradient, proves the convexity that makes training reliable, turns probabilities into decisions, and compares it with its ancestor, the perceptron.

What you’ll learn

  • Write logistic regression as a model of p(y=1∣x)p(y = 1 \mid \mathbf x) with labels y∈{0,1}y \in \{0, 1\}, and interpret its weights as changes in log-odds.
  • Derive the negative log-likelihood (binary cross-entropy) and its gradient ∑i(σ(w⊤xi)−yi) xi\sum_i(\sigma(\mathbf w^\top\mathbf x_i) - y_i)\,\mathbf x_i.
  • Prove that the loss is convex, and choose a decision threshold from misclassification costs.
  • Compare the perceptron rule with stochastic gradient descent on the logistic loss, prove Novikoff's mistake bound, and preview the softmax.

From scores to probabilities

Labels are y∈{0,1}y \in \{0, 1\} throughout this lesson. Logistic regression models the probability of class 1 by passing a linear score through the sigmoid:

p(y=1∣x)=σ(w⊤x+b),σ(s)=11+e−s.p(y = 1 \mid \mathbf x) = \sigma(\mathbf w^\top\mathbf x + b), \qquad \sigma(s) = \frac{1}{1 + e^{-s}}.

Three properties of σ\sigma do most of the work: it is symmetric, σ(−s)=1−σ(s)\sigma(-s) = 1 - \sigma(s); its derivative is σ′(s)=σ(s)(1−σ(s))\sigma'(s) = \sigma(s)\big(1 - \sigma(s)\big); and its inverse is the logit, log⁡p1−p\log\frac{p}{1-p}. Inverting the model shows what is really linear:

log⁡p(y=1∣x)p(y=0∣x)=w⊤x+b.\log\frac{p(y = 1 \mid \mathbf x)}{p(y = 0 \mid \mathbf x)} = \mathbf w^\top\mathbf x + b.

Reading the weights. wjw_j is the change in the log-odds of class 1 per unit increase of xjx_j, the other features held fixed; equivalently, the odds are multiplied by ewje^{w_j}. If a spam filter has weight 0.70.7 on the number of exclamation marks, each extra one multiplies the odds of spam by e0.7≈2.0e^{0.7} \approx 2.0.

Reading the geometry. The decision boundary p=1/2p = 1/2 is the hyperplane w⊤x+b=0\mathbf w^\top\mathbf x + b = 0, with normal vector w\mathbf w, and (w⊤x+b)/∥w∥(\mathbf w^\top\mathbf x + b)/\norm{\mathbf w} is the signed distance of x\mathbf x from it. Multiplying w\mathbf w and bb by c>1c > 1 leaves the boundary where it is but sharpens every probability: the direction of w\mathbf w sets where the model is unsure, and its length sets how unsure.

Maximum likelihood is cross-entropy

DerivationThe negative log-likelihood
  1. L(w,b)=∏i=1npi yi (1−pi)1−yiL(\mathbf w, b) = \prod_{i=1}^n p_i^{\,y_i}\,(1 - p_i)^{1 - y_i}

    Treat the labels as independent Bernoulli draws with pi=σ(si)p_i = \sigma(s_i) and si=w⊤xi+bs_i = \mathbf w^\top\mathbf x_i + b. The likelihood of the training labels is

  2. ℓ(w,b)=−∑i=1n[yilog⁡pi+(1−yi)log⁡(1−pi)]\ell(\mathbf w, b) = -\sum_{i=1}^n\Big[y_i\log p_i + (1 - y_i)\log(1 - p_i)\Big]

    Maximizing it is minimizing its negative logarithm, which is the binary cross-entropy between the labels and the predictions, also called the log loss:

  3. ℓ(w,b)=∑i=1n[log⁡(1+esi)−yi si]\ell(\mathbf w, b) = \sum_{i=1}^n\Big[\log\big(1 + e^{s_i}\big) - y_i\,s_i\Big]

    Substitute log⁡σ(s)=−log⁡(1+e−s)\log\sigma(s) = -\log(1 + e^{-s}) and log⁡(1−σ(s))=−s−log⁡(1+e−s)\log(1 - \sigma(s)) = -s - \log(1 + e^{-s}); the per-example loss simplifies to a smooth function of the score:

  4. log⁡(1+es)−y s=log⁡(1+e−y~s)\log\big(1 + e^{s}\big) - y\,s = \log\big(1 + e^{-\tilde y s}\big)

    With labels recoded as y~=2y−1∈{−1,+1}\tilde y = 2y - 1 \in \{-1, +1\} the same loss reads log⁡(1+e−y~s)\log(1 + e^{-\tilde y s}), a function of the margin y~s\tilde y s alone: near 0 for large positive margins, growing linearly for large negative ones.

DerivationThe gradient
  1. ∂∂s[log⁡(1+es)−y s]=σ(s)−y=p−y\frac{\partial}{\partial s}\Big[\log\big(1 + e^{s}\big) - y\,s\Big] = \sigma(s) - y = p - y

    Differentiate one term with respect to its score, using ddslog⁡(1+es)=σ(s)\frac{d}{ds}\log(1 + e^s) = \sigma(s):

  2. ∇w ℓ=∑i=1n(σ(w⊤xi)−yi) xi=X⊤(p−y)\nabla_{\mathbf w}\,\ell = \sum_{i=1}^n\big(\sigma(\mathbf w^\top\mathbf x_i) - y_i\big)\,\mathbf x_i = X^\top(\mathbf p - \mathbf y)

    By the chain rule, with ∂si/∂w=xi\partial s_i/\partial\mathbf w = \mathbf x_i (absorb the bias into x\mathbf x as a constant feature):

  3. least squares: X⊤(y^−y)=0logistic: X⊤(p−y)=0\text{least squares: } X^\top(\hat{\mathbf y} - \mathbf y) = \mathbf 0 \qquad \text{logistic: } X^\top(\mathbf p - \mathbf y) = \mathbf 0

    Compare least squares, ∇=X⊤(Xw−y)\nabla = X^\top(X\mathbf w - \mathbf y): prediction minus target, times input, in both cases. The difference is that p\mathbf p depends nonlinearly on w\mathbf w, so X⊤(p−y)=0X^\top(\mathbf p - \mathbf y) = \mathbf 0 has no closed-form solution. Its intercept component does say something exact: at the optimum, ∑ipi=∑iyi\sum_i p_i = \sum_i y_i, so the average predicted probability equals the observed frequency of class 1.

Why not squared error on the probabilities? Two reasons. With the sigmoid inside, ∑i(σ(si)−yi)2\sum_i(\sigma(s_i) - y_i)^2 is not convex in w\mathbf w. And its gradient with respect to a score, 2(σ−y) σ(1−σ)2(\sigma - y)\,\sigma(1 - \sigma), vanishes for a confidently wrong prediction (s→−∞s \to -\infty with y=1y = 1), so a badly misclassified point barely pushes back. The log loss keeps a gradient of σ(s)−y→−1\sigma(s) - y \to -1 there. It is also a proper scoring rule: its expected value over yy is minimized by predicting the true probability, which is why logistic regression's probabilities tend to be well calibrated when the model is right.

Predict before you look

A classifier assigns probability 0.1 to the class that actually occurs. What is its log loss on this example (natural logarithm)?

Show the answer

2.3

−ln⁡0.1≈2.30-\ln 0.1 \approx 2.30. Had it given the true class probability 0.9, the loss would be −ln⁡0.9≈0.105-\ln 0.9 \approx 0.105, about 22 times smaller. As the probability of the true class goes to 0, the loss goes to infinity: confident mistakes are what the log loss punishes most.

Convexity, fitting and regularization

DerivationThe Hessian is positive semidefinite
  1. ∇2ℓ=∑i=1nσ(si)(1−σ(si)) xixi⊤=X⊤SX,S=diag⁡(pi(1−pi))\nabla^2\ell = \sum_{i=1}^n \sigma(s_i)\big(1 - \sigma(s_i)\big)\,\mathbf x_i\mathbf x_i^\top = X^\top S X, \qquad S = \diag\big(p_i(1 - p_i)\big)

    Differentiate the gradient once more, using σ′=σ(1−σ)\sigma' = \sigma(1-\sigma):

  2. v⊤∇2ℓ v=∑i=1npi(1−pi) (xi⊤v)2 ≥ 0\mathbf v^\top\nabla^2\ell\,\mathbf v = \sum_{i=1}^n p_i(1 - p_i)\,(\mathbf x_i^\top\mathbf v)^2 \ \ge\ 0

    For any direction v\mathbf v, the curvature is a weighted sum of squares with nonnegative weights, so ℓ\ell is a convex function: every local minimum is global. If XX has full column rank, every weight pi(1−pi)p_i(1-p_i) is positive at finite w\mathbf w and the curvature is strictly positive.

  3. 0⪯∇2ℓ⪯14 X⊤X0 \preceq \nabla^2\ell \preceq \tfrac14\,X^\top X

    The curvature is also bounded: p(1−p)≤1/4p(1-p) \le 1/4. So the loss is smooth with constant λmax⁡(X⊤X)/4\lambda_{\max}(X^\top X)/4, and gradient descent with any step η≤4/λmax⁡(X⊤X)\eta \le 4/\lambda_{\max}(X^\top X) decreases it steadily.

Training is therefore a smooth convex problem. Gradient descent and its stochastic version, which updates on one example at a time with w←w−η (pi−yi) xi\mathbf w \leftarrow \mathbf w - \eta\,(p_i - y_i)\,\mathbf x_i, scale to huge data. Newton's method uses X⊤SXX^\top SX and converges in a handful of steps on moderate problems; it turns out to be iteratively reweighted least squares (Convergence lesson Logistic Regression in Depth). Quasi-Newton L-BFGS is a common default in libraries.

One case needs care. If some hyperplane separates the two classes perfectly, scaling up its weights drives every margin, and so the loss, toward zero without ever reaching it: the maximum-likelihood estimate does not exist and ∥w∥→∞\norm{\mathbf w} \to \infty. Adding an L2L_2 penalty, ℓ(w)+λ∥w∥2\ell(\mathbf w) + \lambda\norm{\mathbf w}^2, makes the objective strictly convex with a unique finite minimizer; it is the MAP estimate under a Gaussian prior on the weights.

python
import numpy as np
from scipy.special import expit                # numerically safe sigmoid
from sklearn.linear_model import LogisticRegression

# by hand: gradient descent on the mean log loss (X has a column of ones)
w = np.zeros(X.shape[1])
for t in range(2000):
    p = expit(X @ w)
    w -= eta * X.T @ (p - y) / len(y)

# in practice: L2-penalized fit; C is the INVERSE penalty strength
clf = LogisticRegression(C=1.0).fit(X_train, y_train)   # y in {0, 1}
p_test = clf.predict_proba(X_test)[:, 1]                # estimates of P(y = 1 | x)

With its default solver, scikit-learn fits the intercept separately and leaves it unpenalized, so do not add a column of ones there. Smaller CC means stronger regularization.

From probabilities to decisions

A probability is not yet a decision. Predicting class 1 when p≥1/2p \ge 1/2 minimizes the expected number of mistakes if the probabilities are calibrated, but mistakes rarely cost the same. Let a false positive cost cFPc_{\mathrm{FP}} and a false negative cFNc_{\mathrm{FN}}.

DerivationThe cost-optimal threshold
  1. E[cost∣predict 1]=(1−p) cFP,E[cost∣predict 0]=p cFN\E[\text{cost} \mid \text{predict }1] = (1 - p)\,c_{\mathrm{FP}}, \qquad \E[\text{cost} \mid \text{predict }0] = p\,c_{\mathrm{FN}}

    Given p=p(y=1∣x)p = p(y = 1 \mid \mathbf x), predicting 1 risks a false positive with probability 1−p1 - p; predicting 0 risks a false negative with probability pp:

  2. (1−p) cFP≤p cFN  ⟺  p ≥ t⋆=cFPcFP+cFN(1 - p)\,c_{\mathrm{FP}} \le p\,c_{\mathrm{FN}} \iff p \ \ge\ t^\star = \frac{c_{\mathrm{FP}}}{c_{\mathrm{FP}} + c_{\mathrm{FN}}}

    Predict 1 exactly when that is cheaper:

  3. σ(w⊤x+b)≥t⋆  ⟺  w⊤x+b ≥ log⁡t⋆1−t⋆\sigma(\mathbf w^\top\mathbf x + b) \ge t^\star \iff \mathbf w^\top\mathbf x + b \ \ge\ \log\frac{t^\star}{1 - t^\star}

    In feature space, the new threshold is the hyperplane w⊤x+b=log⁡t⋆1−t⋆\mathbf w^\top\mathbf x + b = \log\frac{t^\star}{1 - t^\star}: a parallel shift of the old boundary, not a rotation. Changing costs never requires refitting.

Predict before you look

For a fraud detector, missing a fraud costs 9 times as much as a false alarm. Above what predicted probability of fraud should a transaction be flagged?

Show the answer

10 %

t⋆=cFP/(cFP+cFN)=1/(1+9)=0.1t^\star = c_{\mathrm{FP}}/(c_{\mathrm{FP}} + c_{\mathrm{FN}}) = 1/(1 + 9) = 0.1. Flag everything above 10%: a false alarm is cheap enough to be worth paying nine times for every fraud caught. The boundary moves to score log⁡(0.1/0.9)≈−2.2\log(0.1/0.9) \approx -2.2.

Two related shifts. If the class balance at deployment differs from training while p(x∣y)p(\mathbf x \mid y) stays the same (label shift), the correct log-odds change by a constant: add log⁡π1′/π0′π1/π0\log\frac{\pi_1'/\pi_0'}{\pi_1/\pi_0} to bb, where π\pi and π′\pi' are the old and new class proportions. And if the probabilities themselves are miscalibrated, no threshold rule is reliable until they are repaired (Convergence lesson Calibration & Proper Scoring Rules; for skewed classes, Imbalanced Data & Cost-Sensitive Learning).

The perceptron, and more than two classes

Rosenblatt's perceptron (1958) uses the same linear score but outputs a hard class, y^=1{w⊤x+b≥0}\hat y = \mathbf 1\{\mathbf w^\top\mathbf x + b \ge 0\}, and learns from mistakes only. With targets t∈{0,1}t \in \{0, 1\}, as in the widget below, its rule is

w←w+η (t−y^) x,b←b+η (t−y^).\mathbf w \leftarrow \mathbf w + \eta\,(t - \hat y)\,\mathbf x, \qquad b \leftarrow b + \eta\,(t - \hat y).

Set it beside stochastic gradient descent on the log loss, w←w+η (y−σ(w⊤x+b)) x\mathbf w \leftarrow \mathbf w + \eta\,\big(y - \sigma(\mathbf w^\top\mathbf x + b)\big)\,\mathbf x: the same update with the hard prediction replaced by a probability. Logistic regression nudges on every example, in proportion to how far its probability is from the label; the perceptron moves only when it is wrong, and then by a fixed amount.

DerivationProof
  1. u⊤(w+η y~ x)=u⊤w+η y~ u⊤x ≥ u⊤w+ηγ\mathbf u^\top(\mathbf w + \eta\,\tilde y\,\mathbf x) = \mathbf u^\top\mathbf w + \eta\,\tilde y\,\mathbf u^\top\mathbf x \ \ge\ \mathbf u^\top\mathbf w + \eta\gamma

    On a mistake, y~ w⊤x≤0\tilde y\,\mathbf w^\top\mathbf x \le 0 and the update is w←w+η y~ x\mathbf w \leftarrow \mathbf w + \eta\,\tilde y\,\mathbf x. Its component along u\mathbf u grows by at least ηγ\eta\gamma:

  2. ∥w+η y~ x∥2=∥w∥2+2η y~ w⊤x+η2∥x∥2 ≤ ∥w∥2+η2R2\norm{\mathbf w + \eta\,\tilde y\,\mathbf x}^2 = \norm{\mathbf w}^2 + 2\eta\,\tilde y\,\mathbf w^\top\mathbf x + \eta^2\norm{\mathbf x}^2 \ \le\ \norm{\mathbf w}^2 + \eta^2R^2

    Its squared length grows by at most η2R2\eta^2R^2, because the cross term is not positive on a mistake:

  3. Mηγ≤u⊤w≤∥w∥≤ηRM⟹M≤(Rγ)2M\eta\gamma \le \mathbf u^\top\mathbf w \le \norm{\mathbf w} \le \eta R\sqrt M \quad\Longrightarrow\quad M \le \Big(\frac R\gamma\Big)^2

    After MM mistakes, Cauchy–Schwarz ties the two together, and η\eta cancels:

PropertyPerceptronLogistic regression
Outputa classa probability
Loss minimizedmax⁡(0,−y~s)\max(0, -\tilde y s) (the perceptron criterion)log⁡(1+e−y~s)\log(1 + e^{-\tilde y s})
Separable datastops at the first separator it finds∥w∥→∞\norm{\mathbf w} \to \infty; gradient descent drifts toward the maximum-margin direction
Overlapping (non-separable) classesnever settles: the weights keep cyclingconverges to the unique maximum-likelihood fit (full-rank XX)

More than two classes. Give each class kk its own score sk=wk⊤x+bks_k = \mathbf w_k^\top\mathbf x + b_k and normalize with the softmax:

p(y=k∣x)=esk∑j=1Kesj.p(y = k \mid \mathbf x) = \frac{e^{s_k}}{\sum_{j=1}^K e^{s_j}}.

With K=2K = 2 this is σ(s1−s0)\sigma(s_1 - s_0), logistic regression again. Its gradient has the same "probability minus target" form, (pk−1{y=k}) x(p_k - \mathbf 1\{y = k\})\,\mathbf x, as the next lessons show.

Key takeaways

  • Logistic regression models p(y=1∣x)=σ(w⊤x+b)p(y = 1 \mid \mathbf x) = \sigma(\mathbf w^\top\mathbf x + b) with y∈{0,1}y \in \{0,1\}: linear in the log-odds, so ewje^{w_j} is an odds ratio and the boundary p=1/2p = 1/2 is a hyperplane.
  • Its negative log-likelihood is the binary cross-entropy, ∑i[log⁡(1+esi)−yisi]\sum_i[\log(1 + e^{s_i}) - y_is_i], with gradient X⊤(p−y)X^\top(\mathbf p - \mathbf y): prediction minus target, times input, but with no closed-form zero.
  • The Hessian X⊤SXX^\top SX, S=diag⁡(pi(1−pi))⪯I/4S = \diag(p_i(1-p_i)) \preceq I/4, makes the loss convex and smooth. On separable data the MLE does not exist; an L2L_2 penalty restores a unique finite solution.
  • The cost-optimal threshold is cFP/(cFP+cFN)c_{\mathrm{FP}}/(c_{\mathrm{FP}} + c_{\mathrm{FN}}), a parallel shift of the boundary.
  • The perceptron replaces the probability by a hard output and learns only from mistakes: on separable data with margin γ\gamma and radius RR it makes at most (R/γ)2(R/\gamma)^2 of them, and on non-separable data it never settles. The softmax extends logistic regression to KK classes.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

In a logistic regression for loan default, the weight on "number of missed payments" is 0.70.7. What does it mean?

  1. Each missed payment raises the probability of default by 0.7
  2. Each missed payment raises the probability of default by 70%
  3. Each missed payment multiplies the odds of default by about e0.7≈2e^{0.7} \approx 2, other features held fixed
  4. The model is 70% accurate
Show the answer

C. Each missed payment multiplies the odds of default by about e0.7≈2e^{0.7} \approx 2, other features held fixed

Weights are additive on the log-odds scale: one more missed payment adds 0.70.7 to log⁡p1−p\log\frac{p}{1-p}, multiplying the odds by e0.7≈2.01e^{0.7} \approx 2.01. The change in the probability itself depends on where you start; it is largest near p=1/2p = 1/2.

Question 2

For logistic regression with labels yi∈{0,1}y_i \in \{0, 1\} and the bias absorbed into x\mathbf x, what is the gradient of the negative log-likelihood?

  1. ∑i(σ(w⊤xi)−yi) xi\sum_i\big(\sigma(\mathbf w^\top\mathbf x_i) - y_i\big)\,\mathbf x_i
  2. ∑i(w⊤xi−yi) xi\sum_i\big(\mathbf w^\top\mathbf x_i - y_i\big)\,\mathbf x_i
  3. ∑i(σ(w⊤xi)−yi) σ′(w⊤xi) xi\sum_i\big(\sigma(\mathbf w^\top\mathbf x_i) - y_i\big)\,\sigma'(\mathbf w^\top\mathbf x_i)\,\mathbf x_i
  4. ∑iyi xi\sum_i y_i\,\mathbf x_i
Show the answer

A. ∑i(σ(w⊤xi)−yi) xi\sum_i\big(\sigma(\mathbf w^\top\mathbf x_i) - y_i\big)\,\mathbf x_i

The derivative of log⁡(1+es)−ys\log(1 + e^s) - ys with respect to ss is σ(s)−y\sigma(s) - y, and the chain rule multiplies by xi\mathbf x_i. The factor σ′\sigma' cancels: that is the magic of pairing the sigmoid with the log loss.

Question 3

Why is logistic regression trained with the log loss rather than squared error on the predicted probabilities?

  1. Squared error cannot be computed for probabilities
  2. The log loss is convex in w\mathbf w and keeps a strong gradient on confident mistakes; squared error on σ(w⊤x)\sigma(\mathbf w^\top\mathbf x) is neither
  3. The log loss always gives higher accuracy
  4. Squared error requires labels in {−1,+1}\{-1, +1\}
Show the answer

B. The log loss is convex in w\mathbf w and keeps a strong gradient on confident mistakes; squared error on σ(w⊤x)\sigma(\mathbf w^\top\mathbf x) is neither

With the sigmoid inside, squared error is non-convex in w\mathbf w, and its gradient 2(σ−y)σ(1−σ)2(\sigma - y)\sigma(1-\sigma) vanishes when σ\sigma saturates on the wrong side. The log loss is convex (Hessian X⊤SXX^\top SX), and its gradient σ−y\sigma - y stays near ±1\pm1 for confident mistakes. It is also the maximum-likelihood loss and a proper scoring rule.

Question 4

A false negative costs 4 times as much as a false positive. With calibrated probabilities, where should the threshold be?

  1. 0.8
  2. 0.5
  3. 0.25
  4. 0.2
Show the answer

D. 0.2

t⋆=cFP/(cFP+cFN)=1/(1+4)=0.2t^\star = c_{\mathrm{FP}}/(c_{\mathrm{FP}} + c_{\mathrm{FN}}) = 1/(1 + 4) = 0.2: flag whenever p≥0.2p \ge 0.2, because the expected cost of a false alarm, 0.80.8, then no longer exceeds that of a miss, 4×0.24 \times 0.2.

Question 5

You run the perceptron and logistic regression (plain gradient descent, no penalty) on data that are not linearly separable. What happens?

  1. Both converge to the same line
  2. The perceptron never settles, while logistic regression converges to its unique maximum-likelihood fit
  3. The perceptron converges, while the weights of logistic regression grow without bound
  4. Neither can be run on such data
Show the answer

B. The perceptron never settles, while logistic regression converges to its unique maximum-likelihood fit

The perceptron updates whenever it errs, and on non-separable data some point is always misclassified, so the weights cycle forever (averaging the iterates helps in practice). The logistic loss with full-rank XX is strictly convex and attains its minimum when the classes overlap, so gradient descent converges. Unbounded weights are what logistic regression suffers on separable data.

Go deeper

Further reading

  • D. R. Cox, "The regression analysis of binary sequences," Journal of the Royal Statistical Society B 20(2), 215–242 (1958).
  • F. Rosenblatt, "The perceptron: a probabilistic model for information storage and organization in the brain," Psychological Review 65(6), 386–408 (1958).
  • C. M. Bishop, Pattern Recognition and Machine Learning (Springer, 2006), chapter 4.
  • T. Hastie, R. Tibshirani & J. Friedman, The Elements of Statistical Learning, 2nd ed. (Springer, 2009), chapter 4.