Skip to content
LeetQuant
QR04 Regression and Numerical Optimisation

QR04 · Regression and Numerical Optimisation · Lesson 5 of 6

Generalised Linear Models

The exponential-family idea behind GLMs, logistic regression and its log-odds and odds-ratio interpretation, Poisson regression for counts, link functions, and fitting by Newton's method (IRLS).

18 min

When the response is not continuous

Will an order fill (yes/no)? How many trades arrive in a minute (0, 1, 2, ...)? Fitting OLS to these predicts probabilities below 0 or above 1 and negative counts, and the error variance depends on the mean (a Bernoulli has variance p(1−p)p(1 - p)), so OLS standard errors are wrong too. A generalised linear model keeps the convenient linear predictor η=x⊤β\eta = x^\top\beta but connects it to the mean through a link function gg and uses a likelihood suited to the response:

g(E[y∣x])=x⊤β.g\big(\mathbb E[y \mid x]\big) = x^\top\beta .

Objective: know the three standard GLMs, interpret logistic and Poisson coefficients fluently, and understand how they are fitted.

The exponential-family idea

A GLM's response comes from an exponential family:

f(y;θ)=exp⁡ ⁣(yθ−b(θ)ϕ+c(y,ϕ)),E[y]=b′(θ),Var⁡(y)=ϕ b′′(θ).f(y; \theta) = \exp\!\Big(\frac{y\theta - b(\theta)}{\phi} + c(y, \phi)\Big), \qquad \mathbb E[y] = b'(\theta), \quad \operatorname{Var}(y) = \phi\, b''(\theta) .

The variance is a function of the mean, which is what makes each family distinct. The canonical link sets θ=x⊤β\theta = x^\top\beta; it gives the cleanest score equations and a concave log-likelihood.

ResponseFamilyθ\theta (canonical link)MeanVariance
continuousNormalμ\mu (identity)μ\muσ2\sigma^2
binaryBernoullilog⁡p1−p\log\frac{p}{1-p} (logit)ppp(1−p)p(1 - p)
countPoissonlog⁡μ\log\mu (log)μ\muμ\mu

OLS is the Normal GLM with identity link. Non-canonical links exist (probit, Φ−1(p)\Phi^{-1}(p), for binary data; log link for positive continuous data with a Gamma family), but the canonical ones are the default.

Logistic regression

log⁡p(x)1−p(x)=x⊤β⟺p(x)=σ(x⊤β)=11+e−x⊤β.\log\frac{p(x)}{1 - p(x)} = x^\top\beta \quad\Longleftrightarrow\quad p(x) = \sigma(x^\top\beta) = \frac{1}{1 + e^{-x^\top\beta}} .

Interpretation. βj\beta_j is the change in log-odds per unit of xjx_j, holding the others fixed; eβje^{\beta_j} is the odds ratio, the factor by which the odds p/(1−p)p/(1 - p) are multiplied. The effect on the probability itself is not constant:

∂p∂xj=βj p(1−p)≤βj4,\frac{\partial p}{\partial x_j} = \beta_j\,p(1 - p) \le \frac{\beta_j}{4},

with the maximum at p=12p = \tfrac12. The β/4\beta/4 rule is a quick upper bound on a coefficient's probability effect. Odds ratios approximate risk ratios only when pp is small.

Likelihood. For independent yi∈{0,1}y_i \in \{0, 1\} with pi=σ(xi⊤β)p_i = \sigma(x_i^\top\beta):

ℓ(β)=∑i[yilog⁡pi+(1−yi)log⁡(1−pi)],∇ℓ=X⊤(y−p),∇2ℓ=−X⊤WX,\ell(\beta) = \sum_i \big[y_i\log p_i + (1 - y_i)\log(1 - p_i)\big], \qquad \nabla\ell = X^\top(y - p), \qquad \nabla^2\ell = -X^\top W X,

where W=diag⁡(pi(1−pi))W = \operatorname{diag}\big(p_i(1 - p_i)\big). The Hessian is negative semi-definite, so ℓ\ell is concave and any stationary point is the global maximum. Minus ℓ\ell is the log loss (binary cross-entropy) used in machine learning. The score equations X⊤(y−p^)=0X^\top(y - \hat p) = 0 mirror OLS's X⊤(y−y^)=0X^\top(y - \hat y) = 0; with an intercept, the fitted probabilities average to the observed frequency.

Separation. If some combination of regressors perfectly separates the 0s from the 1s, the likelihood keeps rising as ∥β∥→∞\|\beta\| \to \infty and no finite MLE exists: Newton's iterations march off, and software reports huge coefficients and standard errors. Fix with a penalty (ridge-type) or by rethinking the regressor.

Worked example

reading a logistic fit

A model for whether a passive order fills within a minute is logit⁡p=−2+0.5x\operatorname{logit} p = -2 + 0.5x, where xx is order-book imbalance in standardised units. Find the fill probability at x=2x = 2 and x=4x = 4, the odds ratio per unit of xx, and the marginal effect of xx on pp at x=2x = 2.

Show solution

At x=2x = 2: logit⁡p=−1\operatorname{logit} p = -1, so p=1/(1+e)≈0.269p = 1/(1 + e) \approx 0.269. At x=4x = 4: logit⁡p=0\operatorname{logit} p = 0, so p=0.5p = 0.5.

Odds ratio: e0.5≈1.649e^{0.5} \approx 1.649. Each unit of imbalance multiplies the odds of filling by 1.65. Check: odds at x=2x = 2 are e−1≈0.368e^{-1} \approx 0.368, at x=4x = 4 they are 1=0.368×1.64921 = 0.368 \times 1.649^2.

Marginal effect at x=2x = 2: 0.5×0.269×0.731≈0.0980.5 \times 0.269 \times 0.731 \approx 0.098, i.e. about 10 percentage points per unit. The β/4\beta/4 bound gives 0.1250.125, attained at x=4x = 4 where p=0.5p = 0.5. Saying "a unit of imbalance raises fill probability by 0.5" would be wrong on two counts: 0.5 is on the log-odds scale, and the probability effect depends on where you start.

Fitting: Newton's method is IRLS

The Newton step for maximising ℓ\ell is βnew=β+(X⊤WX)−1X⊤(y−p)\beta_{\text{new}} = \beta + (X^\top WX)^{-1}X^\top(y - p). Rearranged,

βnew=(X⊤WX)−1X⊤Wz,z=Xβ+W−1(y−p),\beta_{\text{new}} = (X^\top WX)^{-1}X^\top W z, \qquad z = X\beta + W^{-1}(y - p),

which is a weighted least-squares regression of a "working response" zz on XX with weights WW. Because WW and zz change every iteration, the algorithm is called iteratively reweighted least squares. Intuition: linearise the link around the current fit, then run WLS where each observation is weighted by the inverse of its variance on that linearised scale. Observations with pp near 0 or 1 carry little weight; points near p=12p = \tfrac12 are the informative ones.

Newton converges quadratically near the optimum and typically needs 5–10 iterations. At the optimum, (X⊤W^X)−1(X^\top \hat WX)^{-1} is the inverse Fisher information: the estimated covariance of β^\hat\beta, giving the standard errors software reports. For very large data, the same gradient X⊤(y−p)X^\top(y - p) is used in (stochastic) gradient descent instead, which is the next lesson.

Worked example

Newton iterations by hand and in code

(a) An intercept-only logistic model is fitted to 10 observations with 8 ones. Run Newton's method from β0=0\beta_0 = 0.

(b) Fit logit⁡p=a+bx\operatorname{logit} p = a + bx to x=0,1,…,7x = 0, 1, \dots, 7 with y=(0,0,1,0,1,0,1,1)y = (0, 0, 1, 0, 1, 0, 1, 1).

Show solution

(a) The gradient is ∑(yi−p)=8−10p\sum(y_i - p) = 8 - 10p and the information is 10p(1−p)10p(1 - p). At β=0\beta = 0, p=0.5p = 0.5: the step is 3/2.5=1.23/2.5 = 1.2. At β=1.2\beta = 1.2, p=σ(1.2)≈0.7685p = \sigma(1.2) \approx 0.7685: gradient 0.3150.315, information 1.7791.779, step 0.1770.177, so β≈1.3769\beta \approx 1.3769. One more step gives 1.3862681.386268. The answer is logit⁡(0.8)=ln⁡4≈1.386294\operatorname{logit}(0.8) = \ln 4 \approx 1.386294; the errors 0.19,0.0094,2.6×10−5,2×10−100.19, 0.0094, 2.6 \times 10^{-5}, 2 \times 10^{-10} show quadratic convergence.

(b) The same Newton step with a 2×22 \times 2 information matrix:

import math

def logistic_newton(x, y, steps=8):
    a, b = 0.0, 0.0  # intercept, slope
    for k in range(steps):
        p = [1 / (1 + math.exp(-(a + b * xi))) for xi in x]
        w = [pi * (1 - pi) for pi in p]
        # gradient X'(y - p) and information X'WX for columns (1, x)
        g0 = sum(yi - pi for yi, pi in zip(y, p))
        g1 = sum(xi * (yi - pi) for xi, yi, pi in zip(x, y, p))
        h00 = sum(w)
        h01 = sum(wi * xi for wi, xi in zip(w, x))
        h11 = sum(wi * xi * xi for wi, xi in zip(w, x))
        det = h00 * h11 - h01 * h01
        a += (h11 * g0 - h01 * g1) / det  # solve the 2x2 system
        b += (h00 * g1 - h01 * g0) / det
        print(k + 1, f"{a:.6f}", f"{b:.6f}")
    return a, b

x = [0, 1, 2, 3, 4, 5, 6, 7]
y = [0, 0, 1, 0, 1, 0, 1, 1]
logistic_newton(x, y, steps=5)
1 -1.666667 0.476190
2 -2.038937 0.582554
3 -2.078860 0.593960
4 -2.079295 0.594084
5 -2.079295 0.594084

So b^≈0.594\hat b \approx 0.594 (odds ratio e0.594≈1.81e^{0.594} \approx 1.81 per unit of xx) and p=12p = \tfrac12 at x=−a^/b^=3.5x = -\hat a/\hat b = 3.5, the midpoint, as the symmetric data suggest. statsmodels gives the same estimates with a slope standard error of 0.432, so z≈1.37z \approx 1.37: with 8 points the slope is not significant.

Poisson regression for counts

log⁡μ(x)=x⊤β,y∣x∼Poisson(μ(x)).\log\mu(x) = x^\top\beta, \qquad y \mid x \sim \text{Poisson}(\mu(x)) .

eβje^{\beta_j} is a rate ratio: each unit of xjx_j multiplies the expected count by eβje^{\beta_j} (a coefficient of 0.2 means +22%+22\%, since e0.2≈1.221e^{0.2} \approx 1.221; −0.3-0.3 means ×0.741\times 0.741, about −26%-26\%). The score is again X⊤(y−μ)X^\top(y - \mu) and the weights in IRLS are W=diag⁡(μi)W = \operatorname{diag}(\mu_i).

Exposure. When counts are over windows of different length tit_i (trades per interval when intervals differ, defaults per number of loans), model the rate: log⁡μi=log⁡ti+xi⊤β\log\mu_i = \log t_i + x_i^\top\beta, where log⁡ti\log t_i is an offset, a regressor with its coefficient fixed at 1.

Overdispersion. Poisson forces variance = mean. Real counts (trade arrivals cluster) usually have variance well above the mean. The coefficient estimates remain consistent if the mean is right, but the standard errors are too small. Use quasi-Poisson (scale the variance by an estimated ϕ\phi), robust standard errors, or a negative binomial model. Many zeros beyond what Poisson predicts suggest a zero-inflated model.

Assumptions and failure modes

  • The link is a modelling choice: a logistic fit assumes log-odds linear in xx. Check with binned calibration plots (predicted vs observed frequency by decile).
  • Observations are assumed independent given xx; clustered or time-dependent data need robust or clustered standard errors, exactly as in OLS.
  • Coefficient interpretations are conditional on the other regressors, and omitted-variable problems carry over (in logistic regression, omitting even an uncorrelated regressor shrinks the others towards zero).
  • Class imbalance (rare events) does not bias the slopes much, but the intercept reflects the sample's base rate; if you subsample the majority class, adjust the intercept before reading probabilities.

Interview angle

Typical questions: "interpret a logistic coefficient of 0.7" (log-odds up 0.7; odds ×e0.7≈2.01\times e^{0.7} \approx 2.01; probability effect at most 0.7/4=0.1750.7/4 = 0.175 per unit, largest near p=0.5p = 0.5), "why not OLS on a binary outcome", "what happens with perfect separation", and "derive the gradient of the log loss" (X⊤(y−p)X^\top(y - p), using σ′=σ(1−σ)\sigma' = \sigma(1 - \sigma)).

Knowledge check

In a logistic regression, a regressor has coefficient 0.7. What does a one-unit increase in that regressor do, holding the others fixed?

Knowledge check

A logistic slope is β=0.8\beta = 0.8. What is the largest possible change in the predicted probability per unit change in that regressor (as a derivative)?

Knowledge check

Fitting a logistic regression, Newton's method never settles: the slope estimate keeps growing each iteration and its standard error explodes. What is the most likely cause?

Knowledge check

You fit a Poisson regression to trade counts per minute and find the residual variance is about four times the fitted mean. What is the main consequence?

Key takeaways

  • A GLM is g(E[y∣x])=x⊤βg(\mathbb E[y \mid x]) = x^\top\beta with an exponential-family likelihood; the canonical links are identity (Normal), logit (Bernoulli) and log (Poisson).
  • Logistic coefficients are log-odds; eβe^\beta is an odds ratio; the probability effect is βp(1−p)≤β/4\beta p(1 - p) \le \beta/4.
  • Poisson coefficients are log rate ratios; use an offset for exposure and fix standard errors for overdispersion.
  • The log-likelihood has gradient X⊤(y−μ)X^\top(y - \mu) and, for canonical links, Hessian −X⊤WX-X^\top WX: concave, solved by Newton = IRLS in a handful of steps. Perfect separation means no finite MLE.

Finished reading?

Answer the 4 knowledge checks to complete this lesson (0 done).