Contents / Statistics / Logistic Regression
Chapter 8
Logistic Regression
Why a linear model fails for a binary response; the logistic function and the logit link; coefficients as log odds ratios and why they are not probability changes; maximum likelihood with a concave log-likelihood, the score equations and iteratively reweighted least squares; deviance and likelihood ratio tests; separation, sample size and linearity in the logit; assessing a classifier by confusion matrix, ROC and calibration; and generalised linear models including Poisson, multinomial and ordinal regression.
Introduction
The previous chapter modelled a quantitative response. A great many responses are not quantitative: a patient recovers or does not, a customer buys or does not, an email is spam or is not. The natural target is then a probability, and probabilities are awkward in a way that forces a change of model rather than a patch on the old one.
The awkwardness is that probabilities live in and a linear function does not. Fit a straight line to a binary response and it will predict negative probabilities at one end and probabilities above one at the other, not as a rare pathology but as a certainty for extreme enough predictors. Two further problems come with it, and the first section sets out all three before proposing anything, because the shape of the fix is determined by the shape of the failure.
The fix is to model a transformed version of the probability — the log-odds — linearly, which maps onto the whole real line and so removes the range problem at a stroke. What that buys, and what it costs in interpretability, is the business of the second section: coefficients become log odds ratios, which is less immediate than "units of per unit of " and is exactly as precise.
Estimation changes too. Least squares no longer applies, and there is no closed-form solution at all; the coefficients are found by maximum likelihood, iteratively. That sounds like a loss and is largely a gain, because the likelihood machinery of the estimation chapter comes with it — the log-likelihood turns out to be concave, so the iteration cannot get stuck, and likelihood-ratio tests replace the -tests of the linear model.
The final section places logistic regression in the larger family it belongs to. It is one generalised linear model among several, differing from ordinary regression only in two choices — a distribution for the response and a link function — and once that is seen, Poisson regression for counts and the ordinal and multinomial extensions require no new theory.
Notation follows the regression chapter: is the design matrix, the coefficient vector, and the -th row. The response , and . Maximum likelihood facts are from Statistical Inference: Estimation.
8.1Why a straight line will not do
Suppose we fit by least squares with binary. This is the linear probability model, and since for a binary variable, it is a model for the probability. Three things go wrong, of increasing seriousness.
Proposition 8.1 (Three failures of the linear probability model). For a binary response modelled as with :
- the fitted probability leaves for all sufficiently large or small ;
- the error variance is , which depends on , so the errors are heteroscedastic;
- the errors are not normal — for given the error takes only the two values and .
Proof.
- The fitted value is an unbounded linear function of ; with it exceeds once and falls below once (with the inequalities reversed for ).
- is Bernoulli, so , and inherits it. Since varies with , so does the variance.
- takes the value with probability and with probability . A two-point distribution is not normal.
Example 8.2 (Watching the linear probability model fail). A linear probability model of purchase on income (in thousands) is fitted as . Find the income range over which it produces valid probabilities, and evaluate it at and .
Solution.
- Valid range. requires ; requires . So the model is only usable for incomes between and .
- At : , just inside the range and plausible.
- At : — a probability of .
- The problem is not that the estimate is imprecise; no confidence interval around can help, because the quantity being estimated cannot exceed . This is failure (1) of the proposition, and it is why a new functional form is needed rather than a correction.
- Sanity check on the variance failure too: at the fitted gives error variance , while at the fitted gives — a twenty-five-fold difference across the data, so a single describes neither.
- A logistic fit to the same data cannot produce either pathology: its predictions approach and asymptotically and never cross them.
The three failures are not equally damaging, and ranking them is what determines the remedy. Heteroscedasticity and non-normality are familiar complaints from the regression chapter: by Gauss-Markov the estimates stay unbiased, and only the standard errors are wrong, which weighted least squares or robust standard errors could repair.
The first failure is different in kind. A model that predicts a probability of is not imprecise; it is making a statement that cannot be true, and no adjustment of standard errors helps. That is the failure that forces a new model, and the fix is to choose a functional form that cannot leave in the first place.
Definition 8.3 (The logistic function and the logit). The logistic (sigmoid) function and its inverse, the logit, are
Proposition 8.4 (Properties of the logistic function). maps onto , is strictly increasing, satisfies and , and has derivative
It is the inverse of the logit: .
Proof. Since always, the denominator exceeds , so ; as the denominator tends to and as it grows without bound, giving the limits and .
For the derivative, differentiate by the chain rule:
the last step because . Positivity of gives strict monotonicity.
For the inverse, with we have , so and .∎
The identity is not a curiosity — it is the Bernoulli variance , and it will reappear as the weight in the estimation section. That the derivative of the mean function equals the variance function is characteristic of the exponential family and is what makes these models tractable.
8.2The model, and what its coefficients mean
Definition 8.6 (The logistic regression model). With , the model is linear on the log-odds scale:
with the independent Bernoulli given the predictors.
The linearity is on the logit scale, not on the probability scale, and everything that is initially confusing about logistic regression follows from that. A one-unit change in changes the log-odds by exactly regardless of where you start; it changes the probability by an amount that depends on where you start, being largest near and vanishing near and .
Definition 8.7 (Odds and odds ratio). The odds of an event of probability are . For two groups with probabilities , the odds ratio is
Theorem 8.8 (Coefficients are log odds ratios). In the logistic model, increasing by one unit with all other predictors held fixed multiplies the odds by . That is, is the odds ratio associated with a one-unit increase in , and .
Proof. Write for the linear predictor. By the definition of the logit, the odds are
Increasing by one with the others fixed replaces by , so the odds become . The ratio of the new odds to the old is therefore , independent of the starting value of .∎
The independence of the starting point is the whole reason the logit scale was chosen. On the probability scale no such constant statement exists — which is why "increases the probability by " is never a correct reading of a logistic coefficient.
Pitfall. An odds ratio is not a relative risk, and the two diverge badly for common outcomes. If a treatment moves a probability from to , the relative risk is while the odds ratio is . Reporting the odds ratio in the language of risk overstates the effect by half again.
The two agree only when the outcome is rare, since then and the odds . For an outcome with probability the two differ by about ; for one with probability they differ enormously.
Example 8.9 (Reading a fitted logistic model). A model of loan default gives . Compute the probability of default at months, the odds ratio per month, and per year.
Solution.
- Linear predictor at : .
- Probability: .
- Odds ratio per month: , so each extra month multiplies the odds of default by about — a increase in the odds.
- Per year: twelve months multiply the log-odds by , so the odds ratio is — the odds nearly double over a year.
- Sanity check on the non-linearity: at , and ; at , and . The same -month increase raises the probability by in the first step and by in the second — symmetric about , as requires ✓ — but a further months to gives , a rise of only . The probability effect shrinks as the curve flattens while the odds effect stays exactly constant.
Intuition. Why odds rather than probabilities? Because odds multiply cleanly and probabilities do not.
Probabilities are bounded above, so "doubling" one is not always possible — you cannot double . Odds range over with no upper bound, so multiplying them is always meaningful, and taking logarithms turns that multiplication into addition. A model that is additive in log-odds is therefore multiplicative in odds, and can never produce an impossible value however extreme the predictors.
The price is that the natural summary is a ratio of odds, which most people do not have an intuition for. That is a real cost, and it is why reporting predicted probabilities at a few representative predictor values is usually more informative to a reader than the coefficient table.
Example 8.11 (The same coefficient, three different probability effects). For a model with , compute the change in probability produced by a one-unit increase in starting from a linear predictor of , and .
Solution.
- From : and , a rise of .
- From : and , a rise of .
- From : and , a rise of .
- The same coefficient produces probability changes of , and — differing by a factor of three depending only on the starting point.
- What is constant: the odds ratio at all three. Check the middle case directly: odds go from to ✓.
- Sanity check on the pattern: the largest effect is at , where the logistic curve is steepest (, its maximum), and it falls away symmetrically. That is the derivative of the proposition Properties of the logistic function, visible as a rate of change.
8.3Fitting by maximum likelihood
Least squares does not apply: there is no constant-variance normal error to minimise squares of. Maximum likelihood does, and the model was in fact constructed so that it would.
Theorem 8.12 (The log-likelihood and the score equations). With , the log-likelihood is
and its gradient is
Proof. Each is Bernoulli, so its contribution to the likelihood is and to the log-likelihood
The first term is by the definition of the model. For the second, , so . Summing gives .
For the gradient, differentiate with respect to using :
since .∎
The score equations are worth comparing with the normal equations of the linear model. They have exactly the same form: the residuals are orthogonal to the predictors. The difference is that depends on non-linearly, so the equations cannot be solved in closed form.
Theorem 8.13 (The log-likelihood is concave). The Hessian of the log-likelihood is
which is negative semidefinite. Hence is concave, and if has full rank and the lie strictly in it is strictly concave, so any stationary point is the unique global maximum.
Proof. Differentiate the gradient. Since by the proposition Properties of the logistic function,
For any vector , writing ,
every weight being non-negative. So is positive semidefinite and is concave. Under full rank and the weights are strictly positive and forces , giving strict concavity.∎
Concavity is the guarantee that makes the iterative fit trustworthy: there are no local maxima to get trapped in, and Newton's method converges from essentially any starting point. The standard algorithm, iteratively reweighted least squares, is Newton's method written suggestively — each step solves a weighted least-squares problem with weights and an adjusted response, so a logistic fit is a sequence of linear fits.
Example 8.14 (One Newton step by hand). A single-parameter logistic model (intercept only) is fitted to observations of which are successes. Starting from , take one Newton step and compare with the exact maximiser.
Solution.
- At , every .
- The gradient is .
- The Hessian is .
- Newton's step is .
- Exact answer. For an intercept-only model the MLE of is the sample proportion — the Bernoulli MLE from the estimation chapter, transported through invariance — so .
- Sanity check: one step moved from to , most of the way to . A second step would land within about ; Newton's method converges quadratically near the optimum, and by the theorem The log-likelihood is concave there is nowhere else for it to go.
Definition 8.15 (Deviance). The deviance of a fitted model is
for binary data, measuring lack of fit; smaller is better. It plays the role plays in the linear model.
Theorem 8.16 (Likelihood ratio test for nested models). For a reduced model nested in a full model differing by parameters, under the null that the extra coefficients are all zero,
rejecting for large values.
Proof. This is Wilks' theorem, which we quote: twice the log-likelihood ratio between nested models converges in distribution to with degrees of freedom equal to the difference in the number of free parameters. The equality of the two expressions is immediate from the definition of deviance, the factors of cancelling.∎
This is the exact analogue of the nested -test of the regression chapter, with deviance in place of and a reference in place of . Individual coefficients can also be tested by the Wald statistic , referred to a standard normal, with standard errors from the diagonal of — the observed information, exactly as the Cramér–Rao discussion of the estimation chapter would predict.
Example 8.17 (Testing a fitted model). A model of default with two predictors has deviance ; dropping both gives deviance . Test at using . Separately, one coefficient is with standard error — test it.
Solution.
- Likelihood ratio test. The difference is on degrees of freedom.
- Since , reject: the two predictors jointly carry information about default.
- Wald test. , and , so that coefficient is significant at the level.
- Confidence interval for the coefficient: .
- On the odds-ratio scale, exponentiate the endpoints — legitimate because is increasing, so the coverage is unchanged: .
- Sanity check on the interval: it excludes , agreeing with the significant Wald test ✓. Note that the interval is computed on the log-odds scale and then transformed, never the reverse — the sampling distribution is approximately normal for , not for , which is skewed.
8.4Assumptions, and the failure modes peculiar to this model
Definition 8.18 (Assumptions of logistic regression).
- Independence of the observations.
- Linearity in the logit — the log-odds is linear in the predictors.
- No perfect multicollinearity, so has full rank.
- Adequate sample size relative to the number of predictors and the rarity of the outcome.
Note what is absent: there is no normality assumption and no equal-variance assumption, because the response distribution is Bernoulli by construction and its variance is determined by the mean rather than being a free parameter. Two of the four LINE conditions simply do not arise.
Theorem 8.19 (Separation destroys the maximum likelihood estimate). If there is a vector such that whenever and whenever — the data are completely separated — then the likelihood has no maximum: from below as , and the maximum likelihood estimate does not exist.
Proof. Consider for . For an observation with the linear predictor is , so and its log-likelihood contribution . For an observation with the predictor tends to , so and the contribution .
Every term therefore increases toward its supremum of , so increases to as — the supremum of the log-likelihood is , and is not attained by any finite since that would require some to equal exactly or . Hence no maximiser exists, and the fitted coefficients diverge.∎
Pitfall. Separation is easy to create accidentally and is reported confusingly by software: coefficients of magnitude or more with standard errors in the hundreds, or a warning about fitted probabilities numerically or . It is not a convergence failure to be fixed by more iterations — the estimate genuinely does not exist.
It happens most often with a categorical predictor having a category in which every outcome is the same, and it becomes more likely with small samples or many predictors. The usual remedies are to merge categories, drop the offending predictor, or use a penalised fit — Firth's correction, or a ridge-style penalty, both of which make the penalised likelihood attain a finite maximum.
Remark (Checking linearity in the logit, and how much data is needed). Linearity in the logit is checked by grouping the data on a continuous predictor, computing the empirical log-odds within each group, and plotting them against the predictor: the plot should be roughly straight. Curvature is repaired as it would be in ordinary regression, by adding a quadratic term or splines.
For sample size, the binding constraint is not but the number of observations in the rarer outcome class. A common working rule asks for at least ten such observations per predictor, so a model with five predictors and a event rate wants at least events, hence about observations. Below that, coefficients are biased away from zero and the Wald standard errors are unreliable.
Example 8.20 (Checking linearity in the logit). A continuous predictor is grouped into five bins, giving success counts , , , , at bin midpoints . Assess linearity in the logit.
Solution.
- Compute the empirical proportions: , , , , .
- Convert to log-odds, :
- The successive differences are , , , — close to constant across the middle and tailing off slightly at the top.
- A straight line is a good description, so linearity in the logit is supported, and the common difference of about estimates the slope.
- Sanity check on the raw proportions: their successive differences are — markedly not constant, rising then falling. That is exactly the S-shape the logit transform is there to straighten, and it confirms that linearity should be assessed on the logit scale rather than the probability scale.
- What would have indicated a problem: log-odds differences that changed systematically, say , which would call for a quadratic term or a spline.
Example 8.21 (Diagnosing an implausible fit). A model predicting loan default from twelve predictors on loans, of which defaulted, reports one coefficient of with standard error . What has happened?
Solution.
- A coefficient of means an odds ratio of per unit — not a finding, an artefact.
- The enormous standard error is the tell. Recall that comes from with weights ; as fitted probabilities approach or the weights approach zero, the information matrix becomes near-singular, and its inverse blows up.
- This is separation, by the theorem Separation destroys the maximum likelihood estimate: some predictor (or combination) perfectly divides the defaulters from the rest, and the likelihood is being maximised by pushing that coefficient toward infinity. The iteration simply stopped at whatever the convergence tolerance allowed.
- The sample size makes it likely. With events and predictors, the events-per-predictor ratio is , far below the working rule of — with that many dimensions and that few events, a perfect divider almost always exists.
- Sanity check on the direction of the fix: more iterations will not help, since there is no finite maximum to converge to. Reduce the predictors to at most one or two, or fit with Firth's penalty, which guarantees finite estimates.
Assessing a fitted classifier
A logistic model returns probabilities. Turning those into decisions requires a threshold, and judging the result requires more than one number.
Definition 8.22 (Confusion matrix and its rates). Classifying as positive when produces counts of true positives , false positives , true negatives and false negatives . Define
Proposition 8.23 (The threshold trades the two error rates). Sensitivity is non-increasing in the threshold and specificity is non-decreasing. At sensitivity is and specificity ; at the reverse.
Proof. Raising can only move cases from predicted-positive to predicted-negative, never the other way. So cannot rise and cannot fall, making sensitivity non-increasing; simultaneously cannot fall and cannot rise, making specificity non-decreasing. At every case is called positive, so and , giving sensitivity and specificity ; at every case is called negative.∎
Because the two rates move against each other, no threshold is "correct" without a statement of what the two errors cost. A screening test where a missed case is fatal and a false alarm means one more test should use a low threshold; a test triggering an invasive procedure should not.
Definition 8.24 (ROC curve and AUC). The ROC curve plots sensitivity against specificity as the threshold sweeps from to . The area under the curve (AUC) summarises it in one number, and equals the probability that a randomly chosen positive case receives a higher fitted probability than a randomly chosen negative one.
Example 8.26 (Reading a confusion matrix). At threshold , a model applied to cases gives , , , . Compute the rates, and say what changes if the threshold is raised to giving , , , .
Solution.
- At : sensitivity ; specificity ; precision ; accuracy .
- At : sensitivity ; specificity ; precision ; accuracy .
- Raising the threshold cut sensitivity by and raised specificity by — the trade of the proposition The threshold trades the two error rates, in both required directions ✓.
- Accuracy rose slightly, from to , which illustrates why accuracy is a poor summary: it improved while the model became much worse at finding the cases it exists to find.
- Sanity check on the prevalence: only of cases are positive, so predicting "negative" for everything would score accuracy while detecting nothing at all. Any accuracy figure must be read against that baseline.
Pitfall. Accuracy is the wrong metric for an imbalanced outcome. With a event rate, a model that never predicts the event is accurate and worthless. Report sensitivity and specificity, or precision and recall, and choose the threshold from the relative cost of the two errors.
A second caution. AUC and calibration are different properties. A model whose fitted probabilities are all half their correct values ranks cases perfectly — so its AUC is unchanged — while every probability it reports is wrong. If the probabilities themselves will be used, check calibration by grouping cases into bins of predicted probability and comparing the mean prediction in each bin with the observed proportion; the pairs should lie near the diagonal.
8.5Generalised linear models
Logistic regression is not a special technique but an instance of a pattern, and naming the pattern makes several other models immediate.
Definition 8.27 (Generalised linear model). A generalised linear model specifies three things: a distribution for the response from the exponential family, a linear predictor , and a link function connecting them through
Ordinary linear regression is the choice (normal, identity link); logistic regression is (Bernoulli, logit link). Two more choices cover most of what remains.
| Response | Distribution | Link | Model |
|---|---|---|---|
| continuous | normal | identity | linear regression |
| binary | Bernoulli | logit | logistic regression |
| count | Poisson | log | Poisson regression |
| count, over-dispersed | negative binomial | log | negative binomial regression |
Proposition 8.28 (Poisson regression coefficients are log rate ratios). In the model with Poisson, increasing by one multiplies the expected count by .
Proof. , so replacing by multiplies the mean by , independently of the starting value — the same argument as the theorem Coefficients are log odds ratios, with the log link in place of the logit.∎
Remark (Why the log link for counts, and what over-dispersion means). The log link is chosen for counts for the same reason the logit was chosen for probabilities: it maps the constrained range of the mean — here — onto the whole real line, so no combination of predictors can produce an impossible negative expected count.
The Poisson model carries a strong implication: by the properties of the Poisson distribution the variance equals the mean. Real count data frequently has variance well above the mean, a condition called over-dispersion, which leaves the coefficients roughly unbiased but makes the standard errors too small — the same pattern as heteroscedasticity in the linear model. The negative binomial distribution adds a dispersion parameter and is the standard remedy.
Remark (More than two categories). Two extensions handle responses with categories.
Multinomial logistic regression picks a reference category and fits separate logit equations, each comparing one category against the reference — exactly the indicator coding of the ANOVA chapter, applied to the response instead of a predictor. It makes no assumption about ordering, and costs coefficients per predictor.
Ordinal logistic regression exploits an ordering when there is one (a rating from "poor" to "excellent"). The usual form, the proportional odds model, fits intercepts but a single slope per predictor, assuming the effect on the log-odds of being above any threshold is the same at every threshold. That assumption buys a great deal of parsimony and should be checked rather than assumed.
Example 8.29 (Choosing a model). For each response, name the appropriate GLM: (a) number of customer complaints per store per month; (b) whether a subscriber renews; (c) a satisfaction rating from 1 to 5; (d) time in minutes spent on a page.
Solution.
- (a) A count with no fixed upper bound: Poisson regression with a log link. Check for over-dispersion; if the variance much exceeds the mean, use negative binomial.
- (b) Binary: logistic regression.
- (c) Ordered categories: ordinal logistic regression, which respects the ordering and spends one slope per predictor rather than four. Multinomial would also fit but discards the ordering and estimates four times as many coefficients.
- (d) Continuous and positive, and likely right-skewed: ordinary regression on the log of the time is the simplest option, or a gamma GLM with a log link if the skew is severe.
- Sanity check on the pattern: in every case the link is chosen so that the linear predictor, which ranges over all of , maps onto the range the mean is allowed to occupy. That single requirement determines the identity link for an unconstrained mean, the log link for a positive one, and the logit for one confined to .
- Reading a coefficient as a change in probability. It is a change in log-odds; the probability effect depends on where you start and is largest near .
- Reporting an odds ratio as a relative risk. They agree only for rare outcomes; at the odds ratio is against a relative risk of .
- Exponentiating a confidence interval the wrong way round. Build the interval on the log-odds scale, where the estimate is approximately normal, then transform the endpoints.
- Fitting a linear probability model and ignoring predictions outside . Heteroscedasticity can be patched; an impossible probability cannot.
- Treating separation as a convergence problem. The maximum likelihood estimate does not exist; more iterations cannot find it. Use a penalised fit or fewer predictors.
- Counting rather than events. The binding constraint is the number of observations in the rarer class, with about ten per predictor as a working minimum.
- Assuming Poisson regression fits any count. It forces the variance to equal the mean; over-dispersed data needs a negative binomial or a robust standard error.
- Using multinomial regression for an ordered response. It works, but discards the ordering and multiplies the number of coefficients.