From-Scratch GLM Training and Prediction
Hard · Machine Learning · Data Scientist · Online Assessment
Problem Statement
A generalized linear model (GLM) pairs three explicit building blocks: a linear score over input features, an invertible link function mapping expected responses to that linear scale, and an exponential-family probability distribution for the target. Because a generic GLM prompt is underspecified until a concrete family, link, regularization rule, and convergence contract are fixed, implement PoissonGLM—from-scratch Poisson regression with the canonical log link—in NumPy.
For row $i \in {1, \dots, n}$ with feature vector $x_i \in \mathbb{R}^d$ and non-negative target $y_i \ge 0$:
1. Linear predictor: $\eta_i = \text{intercept} + x_i \cdot \text{coef}$ (with $\text{intercept} = 0$ when fit_intercept=False).
2. Canonical log link: $\ln(\mu_i) = \eta_i$, giving strictly positive conditional mean $\mu_i = \mathbb{E}[y_i \mid x_i] = \exp(\eta_i)$.
3. Response family & objective: Assuming $y_i \sim \text{Poisson}(\mu_i)$ and omitting the data-only $\ln(y_i!)$ constant, fit(X, y) minimizes the L2-penalized mean negative log-likelihood:
$$\frac{1}{n} \sum_{i=1}^{n} \bigl(\exp(\eta_i) - y_i \eta_i\bigr) + \frac{\text{l2}}{2} |\text{coef}|_2^2$$
Notice that the ridge penalty l2 applies only to coef and never penalizes intercept.
Implement PoissonGLM with the following interface:
- __init__(self, l2: float = 0.0, fit_intercept: bool = True, max_iter: int = 100, tol: float = 1e-8) — Store hyperparameters and raise ValueError if l2 < 0.
- fit(self, X, y) -> PoissonGLM — Optimize parameters (e.g., via damped Newton's method / iteratively reweighted least squares), store intercept_ (float, 0.0 when fit_intercept=False), coef_ (1-D np.ndarray of length $d$), n_iter_ (int, number of Newton steps executed), and converged_ (bool, True once the largest absolute entry of a full Newton step $H^{-1} g$ is strictly below tol), and return self.
- linear_predictor(self, X) -> np.ndarray — Return the 1-D float array $\eta = \text{intercept_} + X @ \text{coef_}$.
- predict(self, X) -> np.ndarray — Return the 1-D float array of conditional expectations $\mu = \exp(\eta)$ without rounding to integers.
Examples
Example 1
Input:
X = [[0.0], [0.0], [1.0], [1.0], [1.0]]
y = [2, 4, 5, 9, 13]
model = PoissonGLM().fit(X, y)
eta = model.linear_predictor([[0.0], [1.0], [0.5]])
preds = model.predict([[0.0], [1.0], [0.5]])
Output:
model.intercept_ ≈ 1.098612 (ln(3))
model.coef_ ≈ [1.098612] ([ln(3)])
model.converged_ = True
eta ≈ [1.098612, 2.197225, 1.647918]
preds ≈ [3.0, 9.0, 5.196152]
Walk-through: Rows with x = 0 have mean count (2 + 4) / 2 = 3.0, so exp(intercept_) = 3.0 (intercept_ = ln(3)). Rows with x = 1 have mean count (5 + 9 + 13) / 3 = 9.0, so exp(intercept_ + coef_[0]) = 9.0 (coef_[0] = ln(9 / 3) = ln(3)). At x = 0.5, predict outputs the continuous conditional mean exp(1.5 * ln(3)) = 3 ** 1.5 ≈ 5.196152.
Example 2
Input:
X = [[1.0], [2.0], [3.0]]
y = [3, 9, 27]
model = PoissonGLM(fit_intercept=False).fit(X, y)
preds = model.predict([[0.0], [2.0]])
Output:
model.intercept_ = 0.0
model.coef_ ≈ [1.098612] ([ln(3)])
model.converged_ = True
preds ≈ [1.0, 9.0]
Walk-through: With fit_intercept=False, intercept_ stays fixed at 0.0 and exp(x * ln(3)) = 3^x matches [3, 9, 27] exactly at x = 1, 2, 3, predicting 3^0 = 1.0 at x = 0 and 3^2 = 9.0 at x = 2.
Example 3
Input:
X = [[0.0], [0.0], [1.0], [1.0]]
y = [3, 5, 0, 0]
unreg = PoissonGLM(max_iter=30).fit(X, y)
reg = PoissonGLM(l2=0.5).fit(X, y)
Output:
unreg.converged_ = False
unreg.predict([[0.0]]) ≈ [4.0]
reg.converged_ = True
reg.intercept_ ≈ 1.084312
reg.coef_ ≈ [-1.042597]
reg.predict([[0.0], [1.0]]) ≈ [2.957403, 1.042597]
Walk-through: Without regularization (l2 = 0), every x = 1 row has count 0, sending the optimal coef_[0] toward $-\infty$; fit avoids overflow, predicts the exact [4.0] mean on x = 0, and honestly sets converged_ = False. Adding l2 = 0.5 anchors coef_[0] at a unique finite optimum where converged_ = True and the unpenalized intercept still preserves total mean calibration (2.957403 + 1.042597 = 4.0).
Constraints
Xmust convert to a 2-D float array of shape(n, d)with $n \ge 1$, $d \ge 0$, and all finite entries; otherwise raiseValueError.ymust convert to a 1-D float array of length $n$ with all finite entries $y_i \ge 0$; otherwise raiseValueError.- Raise
ValueErrorinfit(X, y)when:- there are zero parameters to fit (
fit_intercept=Falseand $d = 0$); fit_intercept=Trueand $\sum_{i=1}^{n} y_i = 0$ (unbounded intercept $-\infty$);l2 == 0and the design matrix columns are linearly dependent (rank $< p$).
- there are zero parameters to fit (
- Calling
linear_predictor(X)orpredict(X)beforefit()must raiseRuntimeError, and passing anXwhose column count differs fromlen(coef_)must raiseValueError. - Solver updates must handle steep initial steps without emitting
expoverflow warnings or crashing on singular Hessians.
Step-by-step walkthrough
Choose the GLM family, link, and contract
Note: the prompt leaves the response distribution, link, regularization, and tolerances open. This solution implements Poisson regression with the canonical log link as a concrete, end-to-end worked example, and shows in the follow-ups how swapping one family/link pair changes only two formulas.
Ordinary linear regression predicts a straight line
y_hat = intercept + x . coef, which fails on event counts (such as insurance claims per policy or clicks per session) because a straight line can predict negative counts like-2.4and treats noise aroundmu = 1the same as noise aroundmu = 1000. A generalized linear model (GLM) fixes both problems by connecting three explicit pieces:Features x_i ---> [1. Linear predictor] eta_i = intercept + x_i . coef (any real number) ---> [2. Inverse link] mu_i = exp(eta_i) [log(mu)=eta] (strictly > 0) ---> [3. Response family] y_i ~ Poisson(mu_i) (count >= 0, Var = mu)- Random family:
y_i ~ Poisson(mu_i), modeling non-negative counts where both the expected valueE[y_i | x_i]and varianceVar(y_i | x_i)equalmu_i. - Linear predictor:
eta_i = intercept + x_i . coef, a standard weighted sum of features taking any value in(-inf, +inf). - Link function:
g(mu_i) = log(mu_i) = eta_i, whose inversemu_i = exp(eta_i)guarantees strictly positive expected counts. The log link is the canonical link for the Poisson family (meaningeta_imatches the natural parameter insideexp(...)when the Poisson probability is written in exponential-family form), which makes the gradient and curvature formulas remarkably clean. Adding1to featurex_jmultiplies the predicted mean count byexp(coef_j).
Before coding, we lock down every clarifying question so our API has zero ambiguity: - Valid targets: finite values
>= 0(typically non-negative integer counts; non-negative rates also work). - Intercept & regularization:fit_intercept=Trueby default, plus an optional ridge penalty(l2 / 2) * ||coef||^2(l2 >= 0) applied only tocoef— never tointercept(penalizing the intercept would artificially pull average predictions towardexp(0) = 1.0). - Prediction output:predict(X)returns the conditional meanE[y | x] = exp(eta), a positive floating-point number (never rounded to an integer). - Convergence & invalid inputs: Optimize via damped Newton's method, settingconverged_ = Trueonce the largest magnitude entry of a full Newton step falls belowtol. Bad shapes,NaN/inf, negative targets, all-zero targets with an intercept, or unregularized collinear columns raiseValueError.- Random family:
Derive the loss, gradient, and Hessian from zero
For a single observation with mean
mu, the Poisson probability mass function isP(y | mu) = (mu^y * exp(-mu)) / y!. Taking the negative natural logarithm turns products into sums:-log P(y | mu) = -y * log(mu) + mu + log(y!)Substitute
log(mu) = etaandmu = exp(eta), and droplog(y!)because it depends only on the datay(never on our parametersbeta). Averaging overnrows (so the strength ofl2does not change when dataset sizendoubles) and adding the L2 penalty gives our objectiveJ(beta):Let A = [1, X] (shape n x p) and beta = [intercept, coef_1, ..., coef_k] (shape p): eta_i = (A @ beta)_i mu_i = exp(eta_i) J(beta) = (1 / n) * sum_{i=1..n} (exp(eta_i) - y_i * eta_i) + 0.5 * sum_j (penalty_j * beta_j^2) where penalty = [0, l2, l2, ..., l2]Now differentiate one row's loss
ell_i(eta_i) = exp(eta_i) - y_i * eta_iwith respect toeta_i: - First derivative:d(ell_i) / d(eta_i) = exp(eta_i) - y_i = mu_i - y_i(predicted mean minus observed count!). - Second derivative:d^2(ell_i) / d(eta_i)^2 = exp(eta_i) = mu_i > 0.Because
mu_i > 0everywhere, every row's loss is curved strictly upward (convex). Applying the chain rule througheta = A @ betastacks allnrows into matrix form:gradient = (1 / n) * A^T @ (mu - y) + penalty * beta (shape: p) hessian = (1 / n) * A^T @ diag(mu) @ A + diag(penalty) (shape: p x p)When
Ahas linearly independent columns (orl2 > 0),hessianis strictly positive definite, soJ(beta)has a single global minimum with no local traps. In code, if a trialbetais huge enough to overflowexp(eta)toinf,objectivesuppresses NumPy's warning and returnsfloat("inf")so our line search knows that candidate step went too far:def objective(beta: np.ndarray, A: np.ndarray, y: np.ndarray, penalty: np.ndarray) -> float: """Mean Poisson negative log-likelihood (dropping log(y!)) plus L2 penalty.""" # Suppress exp() overflow warnings during line search; map overflowed loss to +inf with np.errstate(over="ignore", invalid="ignore"): eta = A @ beta mu = np.exp(eta) loss = np.mean(mu - y * eta) + 0.5 * np.sum(penalty * beta * beta) if not np.isfinite(loss): return float("inf") return float(loss)Compute one Newton (IRLS) step without an n x n matrix
First-order gradient descent takes tiny steps using only the slope
gradient. Newton's method also uses the curvature matrixhessian: at the currentbeta, it approximatesJwith a second-order quadratic bowl and jumps straight to the bottom of that bowl by solving thep x plinear systemhessian @ step = gradient, updatingbeta_new = beta - step. (In statistics, Newton's method on a canonical-link GLM is also called iteratively reweighted least squares (IRLS) because each step is algebraically identical to a weighted linear least-squares fit with per-row weightsw_i = mu_i.)Notice how we build
A^T @ diag(mu) @ A: explicitly callingnp.diag(mu)would allocate ann x nmatrix (forn = 20,000rows,20,000^2 * 8bytes = 3.2 GB of RAM!). Instead,diag(mu) @ Asimply multiplies rowiofAby scalarmu[i], which NumPy broadcasting (A * mu[:, np.newaxis]) does inO(n * p)memory:A (n x p) * mu[:, newaxis] (n x 1) --> weighted_A (n x p), where row i is mu_i * A[i, :] A.T (p x n) @ weighted_A (n x p) --> A^T @ diag(mu) @ A (p x p) in O(n * p^2) time!If extreme separation causes some
mu_ito underflow to0.0and makeshessiannumerically singular,np.linalg.solveraisesLinAlgError; returningNonelets the outer loop stop cleanly rather than crashing:def newton_step(beta: np.ndarray, A: np.ndarray, y: np.ndarray, penalty: np.ndarray) -> Optional[np.ndarray]: """Compute full Newton step H^-1 @ gradient, or return None if H is singular.""" n_rows = A.shape[0] with np.errstate(over="ignore", divide="ignore", invalid="ignore"): # mu: predicted mean counts exp(eta) of shape (n_rows,) mu = np.exp(A @ beta) # gradient: shape (p,), averaging per-row score A_i * (mu_i - y_i) plus L2 derivative gradient = (A.T @ (mu - y)) / n_rows + penalty * beta # Scale row i of A by mu[i] (shape (n_rows, p)) to form A^T @ diag(mu) @ A without an n x n matrix weighted_A = A * mu[:, np.newaxis] hessian = (A.T @ weighted_A) / n_rows + np.diag(penalty) try: step = np.linalg.solve(hessian, gradient) except np.linalg.LinAlgError: return None if not np.all(np.isfinite(step)): return None return stepValidate inputs and warm-start at the constant model
Before running a single iteration, catch data problems that guarantee failure or undefined math: -
Xmust be 2-D, non-empty, and finite;ymust be 1-D withlen(y) == X.shape[0], finite, and>= 0. - All-zero targets (sum(y) == 0) with an intercept: When everyy_i = 0, the unpenalized loss ismean(exp(intercept)), which shrinks toward0asintercept -> -infand never reaches a finite minimum. RaiseValueErrorright away. - Collinear columns (matrix_rank(A) < p) whenl2 == 0: If column 2 equals2 * column 1, infinitely manycoefpairs give the exact same predictions andhessianis singular everywhere. RaiseValueErroradvising the caller to drop the redundant column or setl2 > 0.Where should
betastart? Settingcoef = 0andintercept = log(mean(y))starts at the exact optimal intercept-only model (exp(intercept) = mean(y)), so row predictions immediately match the dataset's average count before Newton even touches the features:def check_features(X) -> np.ndarray: """Validate X as a 2-D float array with finite entries, else raise ValueError.""" X_arr = np.asarray(X, dtype=float) if X_arr.ndim != 2: raise ValueError("X must be 2-D: one row per observation") if not np.all(np.isfinite(X_arr)): raise ValueError("X contains NaN or infinity") return X_arr def check_target(y, n_rows: int) -> np.ndarray: """Validate y as a 1-D float array of finite counts >= 0 matching n_rows.""" y_arr = np.asarray(y, dtype=float) if y_arr.ndim != 1 or len(y_arr) != n_rows: raise ValueError("y must be 1-D with one value per row of X") if not np.all(np.isfinite(y_arr)) or np.any(y_arr < 0): raise ValueError("a Poisson target must be finite and >= 0") return y_arr def design_matrix(X: np.ndarray, fit_intercept: bool) -> np.ndarray: """Return X with a leading column of ones (shape (n, p)) when fitting an intercept.""" if not fit_intercept: return X ones_col = np.ones((X.shape[0], 1)) return np.hstack([ones_col, X])Guard Newton updates with step halving and a truthful convergence flag
Near the optimum, Newton's method converges quadratically (the number of accurate digits roughly doubles on every step!). Far from the optimum, however, an undamped full Newton step can overshoot into
exp(...)overflow. Look atX = [[1], [2]],y = [1000, 1000000]without an intercept starting atcoef = 0(mu = [1, 1]):gradient = (1 * (1 - 1000) + 2 * (1 - 1000000)) / 2 = -1,000,498.5 hessian = (1^2 * 1 + 2^2 * 1) / 2 = 2.5 full step = -1,000,498.5 / 2.5 = -400,199.4 candidate = 0 - (-400,199.4) = +400,199.4 --> exp(2 * 400,199.4) overflows to +inf!The true answer is
coef = log(1000) ≈ 6.908. Backtracking line search fixes the overshoot simply: start withstep_scale = 1.0, and wheneverobjective(beta - step_scale * step)exceeds the current loss (including+infon overflow!), halvestep_scale /= 2.0until the loss drops.Two subtle numerical details separate a fragile solver from a rock-solid one: 1. Tiny rounding slack in line search (
allowed_loss): Whenbetais already1e-8away from the minimum, the true loss improvement(1/2) * gradient . stepis around1e-16— smaller than 64-bit floating-point rounding noise (~1e-15)! A strict testcandidate_loss > current_lossrandomly rejects valid final steps and stallsconverged_ = False. Allowing1e-12 * (1.0 + abs(current_loss))absorbs float noise while still rejecting any genuine uphill jump. 2. Stop on step sizemax(|step|) < tol, NOT gradient size: SupposeX = [[0.0], [0.0], [1.0], [1.0]]andy = [3, 5, 0, 0]withl2 = 0(Example 3). For thex = 1group, every count is0, so the model wantsmu_1 = exp(intercept + coef) = 0, pushingcoef -> -infforever! Asmu_1 -> 0, the gradient(mu_1 - 0)shrinks toward0even thoughcoefhas not converged; meanwhile, the Newton stepH^-1 @ gstays near1.0per iteration, so checkingnp.max(np.abs(step)) < self.tolhonestly leavesconverged_ = False.# Phase 2: build per-parameter L2 vector (0 on intercept) and warm-start at log(mean(y)) penalty = np.full(n_params, float(self.l2)) beta = np.zeros(n_params) if self.fit_intercept: penalty[0] = 0.0 beta[0] = np.log(np.mean(y_arr)) current_loss = objective(beta, A, y_arr, penalty) # Phase 3: run damped Newton updates (step halving) until max(|step|) < tol self.converged_ = False self.n_iter_ = 0 for _ in range(self.max_iter): self.n_iter_ += 1 step = newton_step(beta, A, y_arr, penalty) if step is None: # Some mu_i underflowed to 0, making H singular (unbounded separation) break # Allow tiny 1e-12 relative slack so float rounding near the optimum does not reject t=1 allowed_loss = current_loss + 1e-12 * (1.0 + abs(current_loss)) step_scale = 1.0 candidate_beta = beta - step candidate_loss = objective(candidate_beta, A, y_arr, penalty) while candidate_loss > allowed_loss and step_scale > 1e-10: step_scale /= 2.0 candidate_beta = beta - step_scale * step candidate_loss = objective(candidate_beta, A, y_arr, penalty) if candidate_loss > allowed_loss: break beta = candidate_beta current_loss = candidate_loss # Check step size (not gradient norm, which vanishes even when beta drifts to -inf) if np.max(np.abs(step)) < self.tol: self.converged_ = True breakPredict conditional means rather than rounded counts
At inference time,
linear_predictor(X)computeseta = intercept_ + X @ coef_(checking first thatfit()has run andXhas the expected column count), andpredict(X)applies the inverse linkexp(eta)to return the conditional meanE[y | x].Why never round
predict(X)to an integer? Suppose 1,000 insurance policies each have an expected claim count of0.12claims per year. Summing the unrounded expectations predicts120total claims across the portfolio, whereas rounding every policy to0predicts0claims! If a caller ever needs the probability of an exact integer countk, they can plugmu = model.predict(X)directly intomu^k * exp(-mu) / k!.def linear_predictor(self, X) -> np.ndarray: """Return eta = intercept + X @ coef, the log of the predicted mean.""" if self.coef_ is None: raise RuntimeError("call fit() first") X_arr = check_features(X) if X_arr.shape[1] != len(self.coef_): raise ValueError(f"X has {X_arr.shape[1]} columns; the model was fitted with {len(self.coef_)}") return self.intercept_ + X_arr @ self.coef_ def predict(self, X) -> np.ndarray: """Return conditional mean E[y | x] = exp(eta) (positive real number, never rounded).""" return np.exp(self.linear_predictor(X))Trace Newton's method by hand on Example 1
Let's verify every formula by hand on Example 1:
X = [[0.0], [0.0], [1.0], [1.0], [1.0]]andy = [2, 4, 5, 9, 13](n = 5,l2 = 0,fit_intercept = True). Notice the closed-form target first: thex = 0group has mean(2 + 4) / 2 = 3, and thex = 1group has mean(5 + 9 + 13) / 3 = 9. Soexp(intercept) = 3(intercept = ln(3) ≈ 1.098612) andexp(intercept + coef) = 9(coef = ln(9 / 3) = ln(3) ≈ 1.098612).Watch Newton jump from the warm start
beta_0 = [ln(6.6), 0.0](mean(y) = 33 / 5 = 6.6) to 15-digit accuracy in 6 steps:Start: beta_0 = [1.887070, 0.000000], mu = [6.6, 6.6, 6.6, 6.6, 6.6] Iteration 1 algebra: gradient[0] = ((6.6-2) + (6.6-4) + (6.6-5) + (6.6-9) + (6.6-13)) / 5 = 0.0 / 5 = 0.00 gradient[1] = (0 + 0 + (6.6-5) + (6.6-9) + (6.6-13)) / 5 = -7.2 / 5 = -1.44 hessian = [[5 * 6.6, 3 * 6.6], [3 * 6.6, 3 * 6.6]] / 5 = [[6.60, 3.96], [3.96, 3.96]] Solve H @ step = [0.00, -1.44] --> step = [6/11, -10/11] ≈ [0.545455, -0.909091] beta_1 = [1.887070 - 0.545455, 0.0 - (-0.909091)] = [1.341615, 0.909091] Full convergence table: iter intercept coef objective max(|step|) 0 1.887070 0.000000 -5.854660 -- 1 1.341615 0.909091 -6.537002 0.909091 2 1.125884 1.072745 -6.582892 0.215731 3 1.098981 1.098245 -6.583347 0.026904 4 1.098612 1.098612 -6.583347 0.000369 5 1.098612 1.098612 -6.583347 6.79e-08 6 1.098612 1.098612 -6.583347 2.37e-15 (< tol = 1e-8 -> converged_ = True!)Look at the
max(|step|)column (0.909 -> 0.216 -> 0.0269 -> 3.69e-4 -> 6.79e-8 -> 2.37e-15): each step roughly squares the remaining error, which is the signature of exact gradients and Hessians!Complete solution
Putting input validation,
objective,newton_step, andPoissonGLMtogether gives the complete implementation:from typing import Optional import numpy as np def check_features(X) -> np.ndarray: """Validate X as a 2-D float array with finite entries, else raise ValueError.""" X_arr = np.asarray(X, dtype=float) if X_arr.ndim != 2: raise ValueError("X must be 2-D: one row per observation") if not np.all(np.isfinite(X_arr)): raise ValueError("X contains NaN or infinity") return X_arr def check_target(y, n_rows: int) -> np.ndarray: """Validate y as a 1-D float array of finite counts >= 0 matching n_rows.""" y_arr = np.asarray(y, dtype=float) if y_arr.ndim != 1 or len(y_arr) != n_rows: raise ValueError("y must be 1-D with one value per row of X") if not np.all(np.isfinite(y_arr)) or np.any(y_arr < 0): raise ValueError("a Poisson target must be finite and >= 0") return y_arr def design_matrix(X: np.ndarray, fit_intercept: bool) -> np.ndarray: """Return X with a leading column of ones (shape (n, p)) when fitting an intercept.""" if not fit_intercept: return X ones_col = np.ones((X.shape[0], 1)) return np.hstack([ones_col, X]) def objective(beta: np.ndarray, A: np.ndarray, y: np.ndarray, penalty: np.ndarray) -> float: """Mean Poisson negative log-likelihood (dropping log(y!)) plus L2 penalty.""" # Suppress exp() overflow warnings during line search; map overflowed loss to +inf with np.errstate(over="ignore", invalid="ignore"): eta = A @ beta mu = np.exp(eta) loss = np.mean(mu - y * eta) + 0.5 * np.sum(penalty * beta * beta) if not np.isfinite(loss): return float("inf") return float(loss) def newton_step(beta: np.ndarray, A: np.ndarray, y: np.ndarray, penalty: np.ndarray) -> Optional[np.ndarray]: """Compute full Newton step H^-1 @ gradient, or return None if H is singular.""" n_rows = A.shape[0] with np.errstate(over="ignore", divide="ignore", invalid="ignore"): # mu: predicted mean counts exp(eta) of shape (n_rows,) mu = np.exp(A @ beta) # gradient: shape (p,), averaging per-row score A_i * (mu_i - y_i) plus L2 derivative gradient = (A.T @ (mu - y)) / n_rows + penalty * beta # Scale row i of A by mu[i] (shape (n_rows, p)) to form A^T @ diag(mu) @ A without an n x n matrix weighted_A = A * mu[:, np.newaxis] hessian = (A.T @ weighted_A) / n_rows + np.diag(penalty) try: step = np.linalg.solve(hessian, gradient) except np.linalg.LinAlgError: return None if not np.all(np.isfinite(step)): return None return step class PoissonGLM: """Poisson regression with the canonical log link, fitted via damped Newton / IRLS. Model: y_i ~ Poisson(mu_i), log(mu_i) = eta_i = intercept + x_i . coef. Minimizes mean(mu_i - y_i * eta_i) + (l2 / 2) * ||coef||^2 (intercept unpenalized). """ def __init__(self, l2: float = 0.0, fit_intercept: bool = True, max_iter: int = 100, tol: float = 1e-8): if l2 < 0: raise ValueError("l2 must be >= 0") self.l2 = l2 self.fit_intercept = fit_intercept self.max_iter = max_iter self.tol = tol self.intercept_: float = 0.0 self.coef_: Optional[np.ndarray] = None self.n_iter_: int = 0 self.converged_: bool = False def fit(self, X, y) -> "PoissonGLM": # Phase 1: validate input arrays and check parameter identifiability X_arr = check_features(X) y_arr = check_target(y, X_arr.shape[0]) if X_arr.shape[0] == 0: raise ValueError("need at least one row") # When every count is 0, sending intercept -> -inf drives loss -> 0 with no finite minimum if self.fit_intercept and np.sum(y_arr) == 0: raise ValueError("all targets are 0: the best intercept is minus infinity") # A: design matrix of shape (n_rows, p), where column 0 is ones if fit_intercept=True A = design_matrix(X_arr, self.fit_intercept) n_params = A.shape[1] if n_params == 0: raise ValueError("no intercept and no features: nothing to fit") # Without L2 regularization, collinear columns make the Hessian singular everywhere if self.l2 == 0 and np.linalg.matrix_rank(A) < n_params: raise ValueError("the columns are linearly dependent; drop one or use l2 > 0") # Phase 2: build per-parameter L2 vector (0 on intercept) and warm-start at log(mean(y)) penalty = np.full(n_params, float(self.l2)) beta = np.zeros(n_params) if self.fit_intercept: penalty[0] = 0.0 beta[0] = np.log(np.mean(y_arr)) current_loss = objective(beta, A, y_arr, penalty) # Phase 3: run damped Newton updates (step halving) until max(|step|) < tol self.converged_ = False self.n_iter_ = 0 for _ in range(self.max_iter): self.n_iter_ += 1 step = newton_step(beta, A, y_arr, penalty) if step is None: # Some mu_i underflowed to 0, making H singular (unbounded separation) break # Allow tiny 1e-12 relative slack so float rounding near the optimum does not reject t=1 allowed_loss = current_loss + 1e-12 * (1.0 + abs(current_loss)) step_scale = 1.0 candidate_beta = beta - step candidate_loss = objective(candidate_beta, A, y_arr, penalty) while candidate_loss > allowed_loss and step_scale > 1e-10: step_scale /= 2.0 candidate_beta = beta - step_scale * step candidate_loss = objective(candidate_beta, A, y_arr, penalty) if candidate_loss > allowed_loss: break beta = candidate_beta current_loss = candidate_loss # Check step size (not gradient norm, which vanishes even when beta drifts to -inf) if np.max(np.abs(step)) < self.tol: self.converged_ = True break # Phase 4: unpack beta back into intercept_ and coef_ if self.fit_intercept: self.intercept_ = float(beta[0]) self.coef_ = beta[1:].copy() else: self.intercept_ = 0.0 self.coef_ = beta.copy() return self def linear_predictor(self, X) -> np.ndarray: """Return eta = intercept + X @ coef, the log of the predicted mean.""" if self.coef_ is None: raise RuntimeError("call fit() first") X_arr = check_features(X) if X_arr.shape[1] != len(self.coef_): raise ValueError(f"X has {X_arr.shape[1]} columns; the model was fitted with {len(self.coef_)}") return self.intercept_ + X_arr @ self.coef_ def predict(self, X) -> np.ndarray: """Return conditional mean E[y | x] = exp(eta) (positive real number, never rounded).""" return np.exp(self.linear_predictor(X))✅ Submit now — all tests should pass.
Intuition & how it works
Think of a generalized linear model (GLM) as a straight-line model fitted with a domain-appropriate output adapter and scoring rule. Ordinary linear regression outputs eta = intercept + x . coef directly from -inf to +inf, which makes no sense when predicting event counts (like support tickets per customer or hospital visits per year) that can never be negative. In Poisson regression with the log link, the linear score eta passes through mu = exp(eta) so every predicted average count is strictly positive, and parameters are chosen to maximize the Poisson log-likelihood (equivalently minimizing mean(exp(eta) - y * eta) + (l2 / 2) * ||coef||^2).
Naive shortcuts fail quickly here. Taking log(y) and running ordinary linear regression crashes immediately whenever y = 0 (log(0) is undefined) and systematically underpredicts averages even on positive counts. Meanwhile, running plain undamped Newton's method (an optimizer that jumps to the minimum of a local quadratic approximation built from the first derivative gradient and second-derivative matrix hessian) can jump straight to exp(400000) = inf on steep counts, or falsely declare victory when an all-zero subgroup pushes a coefficient toward -inf.
Our implementation pairs exact second-order Newton updates with backtracking line search (halving any step that overflows or raises the loss) from a smart warm start intercept = log(mean(y)), coef = 0. For example, on Example 1 (x = [0, 0, 1, 1, 1] with counts y = [2, 4, 5, 9, 13]):
1. Warm start sets intercept = ln(6.6) ≈ 1.887, coef = 0, predicting mu = 6.6 for all 5 rows.
2. Iteration 1 computes gradient = [0.0, -1.44] and hessian = [[6.60, 3.96], [3.96, 3.96]], stepping to [1.342, 0.909].
3. Five more fast quadratic steps (max(|step|) shrinking 0.909 -> 0.216 -> 0.0269 -> 3.69e-4 -> 6.79e-8 -> 2.37e-15) land on intercept = ln(3) ≈ 1.0986 and coef = ln(3) ≈ 1.0986, predicting exact group means 3.0 at x = 0, 9.0 at x = 1, and 3 ** 1.5 ≈ 5.1962 at x = 0.5.
Complexity
- Time per Newton iteration — O(n * p^2 + p^3): With
nrows andpparameters (kfeatures plus optional intercept), scalingAbymutakesO(n * p)operations, multiplyingA.T @ weighted_Ato build thep x pHessian doesp^2dot products of lengthninO(n * p^2)time, and solving thep x plinear systemhessian @ step = gradientvia Gaussian elimination takesO(p^3)time. Any backtracking step-halving evaluation computesA @ betainO(n * p)time. - Total training time — O((I + 1) * n * p^2 + I * p^3): When
l2 == 0, the one-timenp.linalg.matrix_rank(A)check runs a singular value decomposition (SVD) (a matrix factorization that reveals exact column rank) inO(n * p^2)time (assumingn >= p), followed byI <= max_iterNewton iterations (typicallyI = 5to8iterations on well-posed data thanks to quadratic convergence). - Space — O(n * p + p^2): Storing the
n x pdesign matrixAandweighted_AusesO(n * p)memory (explicitly avoiding ann x ndiagonal weight matrix!), while storing the Hessian usesO(p^2)memory. - Prediction (
linear_predictorandpredict) — O(m * p) time and O(m) output space: Scoringmnew rows performs one matrix-vector productX @ coef_of costO(m * p)followed bymscalarexpevaluations.
Edge cases
- Intercept-only model (
Xhas shape(n, 0)): Works seamlessly (p = 1), converging immediately on the warm startintercept_ = log(mean(y))andcoef_ = []. - All targets equal to
0with an intercept: No finite optimum exists becausemean(exp(intercept))decreases forever asintercept -> -inf;fitdetectsnp.sum(y) == 0up front and raisesValueError. - Subgroup with all zeros (data separation): On Example 3 (
x = [0, 0, 1, 1],y = [3, 5, 0, 0]) withl2 = 0, thex = 1group wantsmu = 0(coef -> -inf).coefsteps downward by ~1per iteration without overflowing or crashing, andfithonestly setsconverged_ = Falseatmax_iter. Adding anyl2 > 0(such asl2 = 0.5) restores a unique finite minimum. - Collinear (linearly dependent) features: When
l2 == 0, redundant columns leave infinitely many optimalbetavectors and a singular Hessian, sofitraisesValueError; whenl2 > 0, the+ l2 * Ipenalty makes the objective strictly convex and solvable. - Huge counts causing
expoverflow on step 1:objectivecatches non-finiteexp(eta)values asfloat("inf")without emitting runtime warnings, and backtracking halvesstep_scaleuntiletare-enters floating-point range. - Non-integer non-negative targets (e.g.,
y = 0.5events/day): Valid and consistent — solvingA^T @ (mu - y) = 0depends only onE[y | x] = exp(eta)(Poisson quasi-likelihood, where mean parameters remain consistent even when observations are continuous rates or overdispersed counts). - Different observation durations (exposure): If row
iwas observed fort_imonths rather than 1 unit of time, expected counts aret_i * exp(eta_i) = exp(eta_i + log(t_i)), handled in GLMs by addinglog(t_i)as a fixed offset (a known per-row shift added toeta_iwith weight fixed to1.0).
Common mistakes
- Fitting ordinary least squares on
log(y)orlog(y + 1)instead of a Poisson GLM.log(0)blows up, adding+1distorts small counts arbitrarily, and by Jensen's inequality (for a concave function likelog, the average of the logsE[log(y)]is strictly smaller than the log of the averagelog(E[y])wheneveryvaries),expof alog(y)fit systematically underpredicts mean counts. - Penalizing
intercept_in the L2 term. Shrinkingintercept_toward0pulls baseline predictions towardexp(0) = 1.0even when average counts are0.01or500, breaking calibration (mean(mu)no longer equalsmean(y)). - Building
np.diag(mu)explicitly as ann x narray. That turns linearO(n * p)memory into quadraticO(n^2)memory and crashes RAM on tens of thousands of rows. - Mixing summed gradients with a mean objective (or vice versa). If
objectivedivides bynwhilegradientforgets/ n, the L2 penalty weightl2is mismatched by a factor ofn, breaking line search and optimization! - Requiring strict
candidate_loss < current_losswith zero floating-point slack. One step beforetol = 1e-8, the true Newton improvement (~1e-16) is smaller than float64 rounding noise (~1e-15), causing strict comparisons to reject valid final steps and fail convergence. - Stopping when
max(|gradient|) < tolon separated data. When an all-zero subgroup sendscoef -> -inf,mu -> 0makesmu - y -> 0, so the gradient approaches0even thoughcoefis running away to-inf! Checking Newton step lengthmax(|step|) < tolavoids that false positive. - Rounding
predict(X)to integers. A GLM predicts the conditional expectationE[y | x]; rounding destroys portfolio sums and ranking resolution.
Alternative approaches
- Quasi-Newton (
L-BFGS) or stochastic gradient descent: L-BFGS (a memory-light optimizer that approximates the inverse Hessian from the last few gradient differences inO(n * p)time per step) avoids theO(n * p^2 + p^3)matrix build/solve when feature countpis in the thousands, while mini-batch gradient methods handle tens of millions of rowsn. - Coordinate descent (as in
glmnet): Updates one parameterbeta_jat a time on a quadratic approximation, which is the standard choice when adding an L1 (Lasso) penaltyl1 * sum(|coef_j|)whose absolute-value corner at0is non-differentiable for plain Newton's method. - Modular
Family+LinkFisher scoring: Factor outinverse_link(eta),variance(mu), anddeviance(y, mu)into pluggable objects and run Fisher scoring (Newton's method using the expected Hessian weightsw = (dmu / deta)^2 / Var(mu)), which reduces to our exact IRLS solver whenever a canonical link is used.
Follow-up questions
- How do the objective function, inverse link, and valid output range change if you switch to a different exponential-family distribution? Each exponential-family distribution brings its own valid target domain, natural link, negative log-likelihood loss, variance function
Var(y | mu), and valid prediction range:
```text Family Link Valid y Per-row loss (constants dropped) Predictions mu Var(y | mu)
Gaussian identity any real 0.5 * (y - eta)^2 (-inf, +inf) sigma^2 Bernoulli logit {0, 1} log(1 + exp(eta)) - y * eta (0, 1) mu * (1 - mu) Poisson log >= 0 exp(eta) - y * eta (0, +inf) mu Gamma log > 0 y * exp(-eta) + eta (0, +inf) phi * mu^2 ```
Notice how unified the canonical-link families (Gaussian/identity, Bernoulli/logit, Poisson/log) are: in all three, the unpenalized gradient is literally `(1 / n) * A^T @ (mu - y)`, and only `mu = g^-1(eta)` plus the per-row Hessian weight (`1`, `mu * (1 - mu)`, or `mu`) changes! By contrast, Gamma with a `log` link is a *non-canonical* pair (`-1/mu` is canonical for Gamma), so its per-row score is `1 - y / mu` and its observed Hessian (`y / mu`) differs from its expected Fisher weight (`1`). Input validation (`check_target`) and prediction meaning also shift accordingly — for instance, Bernoulli requires `y` in `{0, 1}` and predicts class-1 probabilities `1 / (1 + exp(-eta))` strictly inside `(0, 1)`.
- What happens during optimization when you fit unpenalized logistic regression on linearly separable classes? When a hyperplane
wseparates ally = 1rows (x_i . w > 0) from ally = 0rows (x_i . w < 0) — a condition called complete separation — multiplyingwby any larger scalarc -> +infpushes predicted probabilitiessigmoid(c * x_i . w)ever closer to1and0and drives the cross-entropy log loss ever closer to0without ever reaching a minimum at any finitew. For example, onx = [-2, -1, 1, 2]andy = [0, 0, 1, 1]with no penalty, Newton's method pushes the slopewthrough1.20 -> 2.02 -> 2.91 -> ..., growing by roughly+1on every single iteration (9.8at step 10,19.8at step 20) untilexpsaturates, standard errors blow up to huge numbers, and predicted probabilities pin hard at0.0and1.0(while first-order gradient descent diverges much more slowly at rateO(log t)along the maximum-margin direction). Standard remedies are adding an L2 ridge penalty (l2 > 0, which makes the objective strictly coercive with a unique finite solution), using Firth's penalized likelihood in small statistical studies, or detecting separation and reportingconverged_ = Falsejust as our Poisson solver does on an all-zero subgroup.
Follow-up questions
- How do the objective function, inverse link, and valid output range change if you switch to a different exponential-family distribution?
- What happens during optimization when you fit unpenalized logistic regression on linearly separable classes?
Similar questions
- Leakage-Free Data Cleaning and ML Pipeline Design
- Low-Latency Tree Ensemble Inference
- Select Score Cutoff for Target Precision
- Payment Fraud Detection Under Class Imbalance and Drift
- Diagnosing and Fixing Overfitting in Supervised Learning
- Correlation Bounds, Equicorrelated Variables, and Box-Muller Sampling