Build a GLM from Scratch: Family, Link, and Optimizer
Machine LearningModel answerLast updated
Design and implement a generalized linear model end-to-end, covering family and link selection, loss derivation, numerical stability, and prediction semantics.
Generalized Linear Models from First Principles
A generalized linear model extends ordinary linear regression by letting the response variable follow any distribution from the exponential family, and by connecting the linear predictor to the conditional mean through a link function. The result is a flexible framework that unifies logistic regression, Poisson regression, Gamma regression, and many other common models under one set of equations.
Your task
Explain how you would build a GLM trainer and predictor entirely from scratch. Your answer should cover:
- Model definition — state the distribution family and link function you will use as your working example, and write out the conditional mean as a function of the linear predictor.
- Objective function — derive the loss (typically negative log-likelihood) and explain why it is the right choice for your chosen family.
- Optimization — describe the algorithm you would use to minimize that loss, how you compute gradients or the update rule, and what numerical precautions are necessary.
- Prediction — clarify what the model outputs at inference time (linear predictor, conditional mean, or a thresholded decision) and under what circumstances each variant is appropriate.
- Implementation details — initialization strategy, stopping criterion, regularization hooks, and how to handle invalid inputs or boundary conditions.
Constraints and open decisions
The problem is intentionally under-specified. Before committing to a single implementation, call out which choices are open and how you would settle them in practice:
- The response distribution and link are not fixed. Pick one explicitly and justify it.
- Whether an intercept is included and whether regularization is applied are unspecified.
- Numerical tolerances and convergence criteria are left to you.
- Prediction semantics (raw score vs. probability vs. class label) depend on the use case.
Use your chosen family and link as a concrete illustration throughout; do not let the answer drift into discussing every possible GLM variant without grounding it in a specific example.
What a complete answer looks like
A strong response walks through the full pipeline — from the statistical model to runnable pseudocode or actual code — while clearly marking which decisions were made, why they were made, and what would change under different requirements.
Hints
Hint 1
Start by pinning down one specific family and link before writing a single line of math or code. Everything downstream — loss, gradient, inverse link — follows from that choice, so ambiguity here propagates into every subsequent step.
Hint 2
Numerical stability is not an afterthought. For the Bernoulli/logit example, compute log-likelihood using log-sum-exp or the numerically stable form log(1 + exp(−yη)) rather than evaluating σ(η) and then taking its log; for Poisson, clip the linear predictor before exponentiating to avoid overflow.
Hint 3
Prediction is not a single thing. The linear predictor η = Xβ, the conditional mean μ = g⁻¹(η), and a thresholded label are three distinct outputs. State which one your model returns by default and how a caller requests the others.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Clarifying the open decisions first
Before writing any math, pin down the choices the problem leaves open. I will use the Bernoulli family with the logit link (i.e., logistic regression) as my running example, because it is the most widely encountered GLM and has concrete numerical pitfalls worth discussing. Everything below generalises to other families by substituting the appropriate log-likelihood and inverse link.
Decisions I am making explicitly:
- Family / link: Bernoulli, logit. Conditional mean μ = σ(η), where η = Xβ and σ is the sigmoid.
- Intercept: included by prepending a column of ones to X.
- Regularisation: L2 (ridge) with strength λ, added to the loss. λ = 0 recovers unregularised MLE.
- Predictions: return conditional probabilities by default; expose a threshold parameter for binary labels.
Model definition
For observation i with features xᵢ ∈ ℝᵈ and label yᵢ ∈ {0, 1}:
η_i = x_i^T β (linear predictor)
μ_i = σ(η_i) (conditional mean = P(y=1 | x_i))
The logit link g(μ) = log(μ / (1 − μ)) maps (0, 1) → ℝ; its inverse is the sigmoid.
Objective function
Negative log-likelihood for n i.i.d. Bernoulli observations plus L2 penalty:
L(β) = −(1/n) Σ [ y_i log(μ_i) + (1 − y_i) log(1 − μ_i) ] + (λ/2) ‖β‖²
Why this loss? It is the exact negative log-likelihood under the assumed distribution, so minimising it is equivalent to maximum a-posteriori estimation (MAP) with a Gaussian prior when λ > 0, or MLE when λ = 0. Using a surrogate loss (e.g., squared error) would be inconsistent with the distributional assumption and would produce biased probability estimates.
Numerical stability. Never compute log(σ(η)) by first evaluating σ(η) and then taking the log — that path loses precision when η is large. Instead use the identity:
log σ(η) = −log(1 + exp(−η)) → implemented as −softplus(−η)
log(1 − σ(η)) = −log(1 + exp( η)) → implemented as −softplus( η)
Most frameworks expose a numerically stable binary_cross_entropy_with_logits; replicate that behaviour manually when writing from scratch.
Optimisation: mini-batch gradient descent (with Newton's method as an alternative)
Gradient of L with respect to β:
∇L(β) = (1/n) X^T (μ − y) + λ β
where μ is the n-vector of predicted probabilities and y is the label vector. This has a clean form because the logit link is the canonical link for the Bernoulli family — the gradient of the log-likelihood simplifies to the residual times the design matrix.
Training loop (pseudocode):
def fit(X, y, lr=0.1, lam=1e-4, max_iter=1000, tol=1e-6):
n, d = X.shape
beta = np.zeros(d) # zero initialisation is fine for logistic
prev_loss = float('inf')
for t in range(max_iter):
eta = X @ beta
mu = sigmoid(eta) # numerically stable sigmoid
loss = cross_entropy(y, mu) + (lam / 2) * np.dot(beta, beta)
grad = (X.T @ (mu - y)) / n + lam * beta
beta -= lr * grad
if abs(prev_loss - loss) < tol:
break
prev_loss = loss
return beta
def sigmoid(eta):
# avoids overflow for large |eta|
return np.where(eta >= 0,
1 / (1 + np.exp(-eta)),
np.exp(eta) / (1 + np.exp(eta)))
Alternative — IRLS (Iteratively Reweighted Least Squares): The canonical GLM optimiser. Each step forms a weighted least-squares problem using the diagonal weight matrix W = diag(μᵢ(1 − μᵢ)) and a working response z = η + (y − μ) / (μ(1 − μ)). IRLS converges in far fewer iterations than gradient descent but requires solving a d×d linear system per step — practical when d is small, expensive when d is large. For large-scale problems, L-BFGS or Adam are reasonable alternatives.
Prediction semantics
Three distinct outputs, each appropriate in different contexts:
| Output | How to compute | When to use |
|---|---|---|
| Linear predictor η | X @ beta | Ranking, downstream models that expect log-odds |
| Conditional mean μ | sigmoid(η) | Calibrated probability estimates, decision thresholds |
| Binary label ŷ | μ > threshold | Classification with explicit operating point |
The threshold defaults to 0.5 (Bayes-optimal under equal misclassification cost) but should be tuned on a held-out set when class imbalance or asymmetric costs are present.
Common mistakes
- Confusing the link with the inverse link. The link maps μ → η; the inverse link maps η → μ. Applying the sigmoid where the logit is expected (or vice versa) produces nonsensical predictions.
- Skipping input validation. Inputs containing NaN or Inf, or labels outside {0, 1}, should raise early rather than propagating silently into the loss.
- Regularising the intercept. The bias term should be excluded from the L2 penalty, otherwise the model is penalised for fitting the prior class probability.
- Declaring convergence on gradient norm alone. A small gradient can occur at a saddle point; checking the change in loss value is more robust.
Generalising to other families
Swapping to Poisson/log or Gamma/log follows the same skeleton: replace the log-likelihood term in L, replace the inverse link (exp for log link), and recompute the gradient — which again simplifies to X^T(μ − y)/n for canonical links. The numerical precaution for Poisson is clipping η before exponentiating to prevent overflow, e.g. np.clip(eta, -20, 20) before np.exp.