Print this page and work through it on paper. Revealed answers are never printed, so you can check one question and still print a clean sheet.
Statistics · Chapter test
Logistic Regression
Work this sheet on paper, showing every step — the method is what is being tested, and the solutions are written so you can check your route rather than just your answer. Name every result you use (“because ”, “by the score equations”, “by Wilks' theorem”) and check its hypotheses before invoking a likelihood-ratio or Wald test. No calculator is needed: every answer has an exact form such as or , and any critical value you need is printed with the question. Full worked solutions are on a separate page; each question also has its own reveal, so you can check one answer without seeing the rest.
- 1.Computation · 6 min
A linear probability model is fitted by least squares to whether a household owns a car () against household income in thousands, giving
- (a)Find the range of incomes over which the fitted value is a valid probability, and evaluate the fit at and at .
- (b)For a household with , write down the two values the error can take and the probability of each, and compute the error variance. Repeat for .
- (c)Say which of the three failures of the linear probability model each of (a) and (b) illustrates. Which of the three cannot be repaired by adjusting standard errors, and why not?
Show the solution to question 1
(a) Solve the two inequalities. requires , that is ; and requires , that is . The fit is a probability only for incomes between and .
At : , a negative probability. At : , a probability of . Both are statements that cannot be true of any household.
(b) The error is two-valued. At the model probability is . Since is Bernoulli, the error equals with probability , and equals with probability . Its variance is
Check directly: and . ✓
At : . The error is , each with probability , and the variance is .
(c) Rank the failures. Part (a) is the range failure: the fitted line leaves . Part (b) shows the other two at once. The variance is at one income and at another, so the errors are heteroscedastic; and at each income the error takes only two values, so it is not normal.
Heteroscedasticity and non-normality are the familiar complaints: by Gauss–Markov the least-squares estimates stay unbiased, only the standard errors are wrong, and weighted least squares or robust standard errors repair them. The range failure is different in kind. A fitted probability of is not an imprecise estimate of something — the quantity being estimated cannot exceed — so no confidence interval around it helps. That failure forces a new functional form, which is why the log-odds is modelled instead of the probability.
- 2.Proof · 7 min
Let . Prove each statement directly from this formula.
- (a) for every real , and consequently .
- (b) for every , with equality only at .
- (c). Deduce where is convex, where it is concave, and where its inflection point lies, and say what this means for the effect of a predictor on a probability.
Show the solution to question 2
(a) Symmetry, then the derivative. By the formula, . Multiply numerator and denominator by :
On the other side, , the same expression. So .
For the derivative, write and apply the chain rule:
using the expression for just found. Equivalently .
(b) Complete the square. Put . Since , the denominator exceeds , so . Then
with equality exactly when . Now means , so and . Both factors of are positive, so is strictly increasing and takes the value only once, at . Hence the bound is attained only there.
(c) Differentiate . By the product/chain rule,
Since everywhere, the sign of is the sign of . For we have (strictly increasing, ), so and is convex there; for , and is concave. The sign changes at , so the inflection point is — the same point at which, by (b), the slope is largest.
For a logistic model this says: a unit change in a predictor moves the probability most when the current probability is near , and the effect shrinks towards zero as the probability approaches or . The steepest possible probability change per unit of log-odds is , and it is only available at the centre.
- 3.Computation · 7 min
A logistic model for whether a seedling survives its first winter, in terms of its stem diameter in millimetres, is fitted as
Give every answer exactly.
- (a)Compute the fitted odds and the fitted probability of survival at .
- (b)State the odds ratio for a mm increase in diameter and for a mm increase, and explain why neither depends on the starting diameter.
- (c)Compute the change in fitted probability from to , from to , and from to , and reconcile the pattern you find with (b).
Show the solution to question 3
(a) Work on the odds scale first. The linear predictor is , so the odds are
At this gives odds . Converting with :
(For instance at : .)
(b) Coefficients are log odds ratios. A mm increase adds to the log-odds, so it multiplies the odds by ; a mm increase adds and multiplies them by . The reason it is independent of the starting point is that the odds are and : the ratio of new odds to old is whatever was. The table in (a) shows it — is a factor of at every step.
(c) The probability steps are not constant.
The first two steps are equal because they are mirror images about : places and symmetrically. The third step is smaller because the curve is flattening as the probability nears — the same on the log-odds scale buys less and less probability. There is no contradiction with (b): the odds ratio is exactly at each step, and it is the probability that has no fixed exchange rate against the coefficient.
- 4.Computation · 6 min
Write for the probability of an outcome in a treated group and for the probability in a control group.
- (a)In a trial, of control patients recover and of treated patients recover. Compute the relative risk and the odds ratio for treatment. Which of the two is the logistic regression coefficient for treatment built from, and what is that coefficient exactly?
- (b)Repeat for a rare outcome: a side effect occurs in of controls and of treated patients.
- (c)Prove that in general , and deduce that whenever treatment raises the probability, the odds ratio exceeds the relative risk, with the gap small exactly when both probabilities are small. Confirm the formula against (a) and (b).
Show the solution to question 4
(a) The relative risk is . The odds are for treated and for control, so . Treatment doubles the risk but triples the odds.
A logistic coefficient is a log odds ratio, never a log relative risk: with treatment coded , .
(b) again. The odds are and , so
For a rare outcome the two measures nearly agree; for the common outcome in (a) they did not.
(c) Rearrange the definition.
If then , so the correction factor exceeds and : an odds ratio reported in the language of risk always overstates a beneficial-looking effect. The factor tends to as , which is the rare-outcome case in which the two agree.
Checks: in (a) the factor is and ✓; in (b) it is and ✓.
- 5.Critique · 8 min
A logistic regression of loan default on years of employment reports with standard error . The analyst's report contains the three claims below. Each is wrong. For each, name the error precisely, then give the correct statement with exact numbers. Use as the two-sided critical value wherever one is needed.
- (a)“Each extra year of employment lowers the probability of default by , so five years of employment reduce it by — or to zero, whichever comes first.”
- (b)“The interval for is . Exponentiating the point estimate and the half-width gives the odds-ratio interval .”
- (c)“The odds ratio per year is , so a borrower with one more year of employment is about less likely to default.”
Show the solution to question 5
(a) A coefficient is a change in log-odds, not in probability. The correct multiplicative statement is: each extra year multiplies the odds of default by , and five years multiply them by . The probability change has no fixed value — it depends on where you start — and it can be bounded. By the mean value theorem, for some between and ,
since . So no single year can move the probability by more than , let alone . For instance from (where ) one more year gives , which exceeds because : a drop of less than . And the probability can never reach zero, since takes values in ; it only approaches it.
(b) The interval is built correctly and transformed incorrectly. On the log-odds scale is approximately normal, so is right. To move to the odds-ratio scale, apply to the two endpoints: because is strictly increasing, lies in the interval exactly when lies in , so the coverage is unchanged.
The proposed interval is not even a set of odds ratios: its lower end is , since , and an odds ratio is positive. The correct interval is not symmetric about ; rather , so is its geometric centre. Consistency check: the Wald statistic is , with ; the log-odds interval excludes and the odds-ratio interval excludes , as they must.
(c) An odds ratio is not a relative risk. “Less likely” is a statement about probabilities, and by the identity the two agree only when default is rare. The correct sentence is “one more year multiplies the odds of default by ”. To see the size of the discrepancy, take a borrower whose current probability is : after one more year the odds are , so the probability is and the relative risk is
because reduces to . The risk falls by less than ; the odds fall by . Only for a borrower whose default probability is already tiny would the two readings coincide.
- 6.Computation · 10 min
An intercept-only logistic model, for every , is fitted to binary observations of which are successes. You may use .
- (a)Write the log-likelihood in terms of , and , show that the score equation reduces to , and solve it exactly.
- (b)Starting from , take one Newton step. Does it overshoot or undershoot the exact maximiser? Justify without a calculator.
- (c)Evaluate the Hessian at the maximiser and deduce the standard error of . Write the Wald statistic for exactly and decide the test with as the critical value.
- (d)Compute the deviance of the fitted model exactly.
Show the solution to question 6
(a) Sum the Bernoulli contributions. With every linear predictor equal to ,
Differentiating, , which is the score equation with all equal. Setting it to zero gives , so . Because is strictly concave (its second derivative is negative), this stationary point is the unique global maximum.
(b) One Newton step. At every . The gradient is and the Hessian is . Newton's update is
The exact maximiser is , and because . So the step undershoots, landing at against the target — most of the way in a single step, as expected near the optimum of a concave function; a second step would close almost all of the remaining gap.
(c) Curvature at the maximiser. With ,
The observed information is , and the standard error is its inverse square root: . (In general , the familiar binomial standard error transported to the log-odds scale.)
The Wald statistic is . It exceeds exactly when , that is when , which is false. So and we do not reject at the level: nine successes in twelve trials is consistent with a fair coin.
(d) Deviance. At we have , so
Check by the other route: for an intercept-only fit ✓. Numerically .
- 7.Proof · 10 min
A logistic model contains an intercept and a single binary predictor : . Write for the number of observations with and for the number of successes among them; define likewise for . Assume and .
- (a)Write out the two score equations for this design, and deduce that at the maximum likelihood fit and .
- (b)Hence prove that the fitted probability in each group equals that group's observed success proportion, and that is exactly the logarithm of the sample odds ratio .
- (c)In a study of patients, received a new drug and of them recovered; of the controls, recovered. Write down , and the two fitted probabilities exactly. Then explain where the argument in (b) breaks if .
Show the solution to question 7
(a) Two columns, two equations. The design matrix has a column of ones and the indicator column . The score equations are therefore
The second says . Subtracting it from the first leaves , so . In words: with an intercept in the model, the fitted probabilities sum to the observed successes overall, and with an indicator in the model they do so within the indicated group as well.
(b) Same predictor, same fitted probability. Every observation with has the same linear predictor , hence the same fitted probability, call it ; every observation with has . The sums in (a) become and , so
Applying the logit, and . Subtracting,
the log of the sample odds ratio. This stationary point is the maximum: both groups are present, so has full rank, and the assumption places every fitted probability strictly inside , so the log-likelihood is strictly concave and its unique stationary point is the global maximiser.
(c) Numbers. with odds ; with odds . Hence
an odds ratio of for the drug. Check: ✓.
If — every treated patient recovers — then (a) demands , which no finite can deliver because never reaches . The score equations then have no solution: this is separation on the indicator, the likelihood increases without bound as , and the maximum likelihood estimate does not exist. The sample odds ratio is infinite for the same reason.
- 8.Computation · 8 min
Three nested models of the same binary response are fitted. Model A has only an intercept; Model B adds one predictor; Model C adds three further predictors to B. Their deviances are , and . Critical values at the level: , , .
- (a)Test B against A, C against B, and C against A. For each, state the statistic, its degrees of freedom, the theorem that justifies the reference distribution, and the conclusion.
- (b)Explain why had to hold whatever the data, and why the three statistics in (a) satisfy the identity you notice.
- (c)In Model B the predictor's coefficient is with standard error . Compute the Wald statistic and compare its square with the likelihood-ratio statistic for the same hypothesis. Should the two agree exactly?
- (d)Using as the critical value, give a confidence interval for the odds ratio per unit of the predictor, and show that it extends further above than below it, by an exact factor.
Show the solution to question 8
(a) Likelihood-ratio tests. For nested models differing by parameters, under the null that the extra coefficients are zero — Wilks' theorem, quoted for twice the log-likelihood ratio.
B against A: on degree of freedom; , reject — the first predictor carries information.
C against B: on degrees of freedom; , do not reject — the three extra predictors, taken together, add nothing detectable beyond B.
C against A: on degrees of freedom; , reject — C is better than the empty model, but (from the previous test) that is because it contains B's predictor.
(b) Nesting. Each model's parameter space contains the previous one's — set the new coefficients to zero and you recover the smaller model — so the maximised log-likelihood can only rise when parameters are added, and can only fall. The identity holds because all three statistics are differences of the same three deviances: . The degrees of freedom add in the same way, .
(c) Wald versus likelihood ratio. , so , against the likelihood-ratio statistic for the same hypothesis . Both are asymptotically under the null, but they are different functions of the data — one uses the curvature at the maximum, the other the height difference between two maxima — and they agree only in the limit. A gap of versus is unremarkable; both reject comfortably.
(d) Build on the log-odds scale, then exponentiate the endpoints. The interval for is , and because is increasing the odds-ratio interval is with the same coverage.
The gaps on either side of the point estimate are
so the upper gap is exactly times the lower one. The interval is symmetric on the log scale (the point estimate is its geometric centre, since ) and skewed to the right on the odds-ratio scale, because is convex. That skew is a feature, not an error: the sampling distribution of is itself right-skewed.
- 9.Sketch · 9 min
A continuous predictor is cut into five bins of observations each, with midpoints ; the success counts in the bins are . A second predictor, cut into four bins with midpoints , gives observed success proportions .
A sketch with no numbers beside it earns nothing here: every plotted point must carry its exact coordinates.
- (a)For the first predictor, compute the empirical odds and log-odds in each bin exactly, and sketch the log-odds against . Say what feature of the sketch supports linearity in the logit and what slope it suggests.
- (b)On a second set of axes, sketch the observed proportions against for the same predictor. Explain why this plot, which is visibly curved, is not evidence against the model.
- (c)Repeat (a) for the second predictor. Describe the curvature you find, identify its exact form, and say how the model should be amended.
Show the solution to question 9
(a) Odds first, then logs. The proportions are . The odds are
and the log-odds are . Every successive difference is exactly , so the five points are collinear.
The sketch: horizontal axis from to , vertical axis log-odds from to (mark as a tick). Plot the five points and draw the straight line through them; it crosses the axis at and has slope . The feature that supports linearity in the logit is the constant vertical spacing — equal steps in give equal steps in log-odds — and the common step estimates , with from the intercept of the line.
(b) The same data on the probability scale. The points are ; the successive rises are — increasing, then levelling — which is the lower half of an S. Draw the axes with from to , plot the five points, and draw through them the curve , which passes through all five exactly and flattens toward the ceiling (dashed) to the right.
This curvature is not evidence against anything: the model asserts linearity in the logit, and a linear logit produces exactly an S-shaped probability curve. Checking straightness on the probability scale tests a model nobody proposed. That is why the diagnostic is made on the log-odds scale, where (a) shows a perfect line.
(c) The second predictor is curved where it matters. Odds: . Log-odds: . The successive differences are — themselves increasing by a constant — so the log-odds are a quadratic in : indeed are at , so
Sketch the four points on axes with log-odds from to ; they bend upward, convex, with no straight line passing near all four (a line through the first two, slope , would predict at against the observed , and at against ). The remedy is the one ordinary regression would use: add an term, or a spline, so that the logit is linear in the transformed predictor. Here the quadratic term removes the curvature exactly.
- 10.Computation · 10 min
A fitted model is applied to seven cases. The three cases with receive fitted probabilities ; the four cases with receive . A case is classified positive when its fitted probability exceeds the threshold .
- (a)At write down , , , and compute sensitivity, specificity, precision and accuracy. Repeat at , and check the direction of every change against what the threshold trade-off requires.
- (b)Compute the AUC exactly, using its interpretation as a probability about a randomly chosen positive–negative pair.
- (c)List the point at every threshold at which the classification changes, as sweeps from down to ; join them into the ROC curve, and verify that the area under your polygon agrees with (b).
- (d)A second model returns exactly half of every fitted probability above. State its AUC and its confusion matrix at . What does the comparison show about what AUC does and does not measure?
Show the solution to question 10
(a) Count, then divide. At the positives and are called positive and is not, so , ; among the negatives only is called positive, so , . Then
At only and exceed the threshold: , , , , giving sensitivity , specificity , precision , accuracy .
Raising moved one positive case () from predicted-positive to predicted-negative and moved no negative case, so sensitivity fell and specificity stayed put — non-increasing and non-decreasing respectively, exactly as the trade-off allows. Accuracy fell from to ; note the do-nothing baseline of calling everything negative already scores .
(b) Count concordant pairs. There are positive–negative pairs. The positive scored beats all four negatives; beats (three); beats (two). Nine of twelve pairs are ordered correctly, so
There are no ties, so no half-credit is needed.
(c) Walk down the sorted scores. In decreasing order the scores are . Start at with nothing called positive: the point is . As drops past each score that case becomes positive; a positive case raises sensitivity by , a negative case raises by :
The ROC curve is this staircase: up, right, up, right, up, right, right. Draw it on the unit square with the chance diagonal dashed; the curve lies above the diagonal throughout.
Area: on the four columns of width the staircase sits at heights , so the area is ✓. Rule the square into a grid of cells of area : each cell corresponds to one (negative, positive) pair, and the cell lies under the curve exactly when the positive outscores the negative. Nine cells under the curve, nine concordant pairs — the two computations are the same count.
(d) Halving preserves order. The second model's scores are for the positives and for the negatives; every pairwise comparison is unchanged, so its AUC is still and its ROC curve is identical. But at nothing exceeds the threshold: , , , , sensitivity , specificity , accuracy , precision undefined (). It never finds a single case.
AUC measures ranking — whether positives tend to score above negatives — and is blind to the scale of the probabilities. Calibration, whether a case scored really has a chance, is a separate property, and the second model fails it at every case while matching the first model's AUC exactly. If the probabilities themselves will be used, or a threshold will be chosen from them, calibration must be checked separately.
- 11.Proof · 10 min
Four observations of the model are . Write and .
- (a)Show that completely separates the data.
- (b)Write explicitly as a function of and prove that it increases to as . Then prove that for every finite , and conclude that the maximum likelihood estimate does not exist.
- (c)A fifth observation is added. Prove that no vector now separates the data, and show that for every , so that the supremum in (b) is no longer approachable.
- (d)Describe what software fitting the original four observations by Newton's method would report, and explain why running more iterations is not the remedy.
Show the solution to question 11
(a) Check the sign at every observation. takes the values at : negative at both observations with and positive at both with . That is the definition of complete separation.
(b) Along the ray . The linear predictors are . An observation with contributes , and one with contributes . Substituting,
As increases, and decrease to , so each logarithm decreases to and increases. It is always negative, since each logarithm is of a number exceeding ; and using for ,
so from below.
For any finite every lies strictly inside , so every contribution or is strictly negative and . Combining: the supremum of is , it is approached along the ray, and it is attained nowhere. A maximiser would have to attain the supremum, so none exists.
(c) Two outcomes at one predictor value. Separation would need a with at and at , but both observations share , so the same number would have to be both negative and positive. No separating vector exists.
For the bound: the two observations at share a fitted probability , and together they contribute
since for . The other three contributions are negative, so for every . The likelihood can no longer be driven towards by any choice of coefficients: the conflicting pair at costs at least whatever the fit does elsewhere.
(d) What the output looks like. Each Newton iteration moves further out along a separating direction, so the reported coefficients grow with the number of iterations — a slope in the tens or twenties, an intercept of the opposite sign and comparable size — and the iteration halts only when the change in falls below the tolerance, since is flattening towards . The fitted probabilities are numerically and , and the weights are numerically , so is nearly singular and its inverse — the standard errors — is enormous. Software may add a warning about fitted probabilities of or .
More iterations cannot help because there is nothing to converge to: (b) shows the maximum does not exist, so any finite stopping point is arbitrary. The remedies are to change the problem — penalise the likelihood (Firth's correction or a ridge penalty, which make the penalised objective attain a finite maximum), drop or merge the offending predictor, or collect data that overlaps as in (c).
- 12.Critique · 9 min
Each of the three modelling decisions below contains an error. Identify it precisely, explain why it matters, and state what should have been done. Where a number is involved, correct it exactly.
- (a)“A Poisson regression of monthly complaints per store has coefficient on the number of checkouts. So each additional checkout adds complaints to the expected monthly count.”
- (b)“Across stores the variance of the monthly complaint count is about six times its mean. Since over-dispersion leaves the Poisson coefficients roughly unbiased, the reported standard errors and -values can be used as they are. In particular the checkout coefficient has , so it is significant.”
- (c)“Time spent on a web page, in minutes, is positive and right-skewed, so we fitted a Poisson regression with a log link: the log link guarantees positive predictions, and the skew is handled by the distribution.”
Show the solution to question 12
(a) The log link makes coefficients multiplicative. In the model the expected count is , and increasing the checkout count by one replaces by , so it multiplies the expected count by . The correct sentence is “each additional checkout doubles the expected number of complaints”. The additive change is not but itself: from an expected complaints the extra checkout adds , from it adds . This is the same misreading as treating a logistic coefficient as a change in probability — the coefficient lives on the scale of the link, and only there is its effect constant.
(b) Unbiased coefficients do not rescue the inference. A Poisson response has variance equal to its mean, and the standard errors are computed on that assumption. If the true variance is about times the mean, the actual sampling variance of is about times what the model claims, so every reported standard error is too small by a factor of about and every -statistic too large by the same factor. The corrected statistic is
well short of : the checkout effect is not significant at the level once the dispersion is honoured. This is the count-data twin of heteroscedasticity in the linear model — estimates fine, standard errors wrong. The remedy is a negative binomial regression, which estimates a dispersion parameter, or at least a quasi-Poisson or robust standard error that scales the Poisson ones by .
(c) The link is right and the distribution is wrong. The Poisson distribution lives on the counts ; time on a page is continuous, and a model for it that assigns probability only to whole minutes is not a model of the data. The mistake shows up concretely through the variance–mean relation, which is not invariant to the unit of measurement: a page with mean minutes and Poisson-consistent variance (min) has, in seconds, mean and variance , not . A model whose fit depends on whether you recorded seconds or minutes is measuring the units, not the behaviour.
The positive-predictions argument is correct as far as it goes — a log link does keep — but link and distribution are separate choices in a generalised linear model and the second was made badly. The right choices are ordinary regression on , or a gamma GLM with a log link, whose variance is proportional to the square of the mean: mean , variance in minutes becomes mean , variance in seconds — the same model in both units, as a model for a continuous quantity must be.
Solutions: calc-path.com/statistics/test/logistic-regression/answers