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

  • X must convert to a 2-D float array of shape (n, d) with $n \ge 1$, $d \ge 0$, and all finite entries; otherwise raise ValueError.
  • y must convert to a 1-D float array of length $n$ with all finite entries $y_i \ge 0$; otherwise raise ValueError.
  • Raise ValueError in fit(X, y) when:
    • there are zero parameters to fit (fit_intercept=False and $d = 0$);
    • fit_intercept=True and $\sum_{i=1}^{n} y_i = 0$ (unbounded intercept $-\infty$);
    • l2 == 0 and the design matrix columns are linearly dependent (rank $< p$).
  • Calling linear_predictor(X) or predict(X) before fit() must raise RuntimeError, and passing an X whose column count differs from len(coef_) must raise ValueError.
  • Solver updates must handle steep initial steps without emitting exp overflow warnings or crashing on singular Hessians.

Step-by-step walkthrough

  1. 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.4 and treats noise around mu = 1 the same as noise around mu = 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)
    
    1. Random family: y_i ~ Poisson(mu_i), modeling non-negative counts where both the expected value E[y_i | x_i] and variance Var(y_i | x_i) equal mu_i.
    2. Linear predictor: eta_i = intercept + x_i . coef, a standard weighted sum of features taking any value in (-inf, +inf).
    3. Link function: g(mu_i) = log(mu_i) = eta_i, whose inverse mu_i = exp(eta_i) guarantees strictly positive expected counts. The log link is the canonical link for the Poisson family (meaning eta_i matches the natural parameter inside exp(...) when the Poisson probability is written in exponential-family form), which makes the gradient and curvature formulas remarkably clean. Adding 1 to feature x_j multiplies the predicted mean count by exp(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=True by default, plus an optional ridge penalty (l2 / 2) * ||coef||^2 (l2 >= 0) applied only to coef — never to intercept (penalizing the intercept would artificially pull average predictions toward exp(0) = 1.0). - Prediction output: predict(X) returns the conditional mean E[y | x] = exp(eta), a positive floating-point number (never rounded to an integer). - Convergence & invalid inputs: Optimize via damped Newton's method, setting converged_ = True once the largest magnitude entry of a full Newton step falls below tol. Bad shapes, NaN/inf, negative targets, all-zero targets with an intercept, or unregularized collinear columns raise ValueError.

  2. Derive the loss, gradient, and Hessian from zero

    For a single observation with mean mu, the Poisson probability mass function is P(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) = eta and mu = exp(eta), and drop log(y!) because it depends only on the data y (never on our parameters beta). Averaging over n rows (so the strength of l2 does not change when dataset size n doubles) and adding the L2 penalty gives our objective J(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_i with respect to eta_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 > 0 everywhere, every row's loss is curved strictly upward (convex). Applying the chain rule through eta = A @ beta stacks all n rows 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 A has linearly independent columns (or l2 > 0), hessian is strictly positive definite, so J(beta) has a single global minimum with no local traps. In code, if a trial beta is huge enough to overflow exp(eta) to inf, objective suppresses NumPy's warning and returns float("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)
    
  3. 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 matrix hessian: at the current beta, it approximates J with a second-order quadratic bowl and jumps straight to the bottom of that bowl by solving the p x p linear system hessian @ step = gradient, updating beta_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 weights w_i = mu_i.)

    Notice how we build A^T @ diag(mu) @ A: explicitly calling np.diag(mu) would allocate an n x n matrix (for n = 20,000 rows, 20,000^2 * 8 bytes = 3.2 GB of RAM!). Instead, diag(mu) @ A simply multiplies row i of A by scalar mu[i], which NumPy broadcasting (A * mu[:, np.newaxis]) does in O(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_i to underflow to 0.0 and makes hessian numerically singular, np.linalg.solve raises LinAlgError; returning None lets 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 step
    
  4. Validate inputs and warm-start at the constant model

    Before running a single iteration, catch data problems that guarantee failure or undefined math: - X must be 2-D, non-empty, and finite; y must be 1-D with len(y) == X.shape[0], finite, and >= 0. - All-zero targets (sum(y) == 0) with an intercept: When every y_i = 0, the unpenalized loss is mean(exp(intercept)), which shrinks toward 0 as intercept -> -inf and never reaches a finite minimum. Raise ValueError right away. - Collinear columns (matrix_rank(A) < p) when l2 == 0: If column 2 equals 2 * column 1, infinitely many coef pairs give the exact same predictions and hessian is singular everywhere. Raise ValueError advising the caller to drop the redundant column or set l2 > 0.

    Where should beta start? Setting coef = 0 and intercept = 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])
    
  5. 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 at X = [[1], [2]], y = [1000, 1000000] without an intercept starting at coef = 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 with step_scale = 1.0, and whenever objective(beta - step_scale * step) exceeds the current loss (including +inf on overflow!), halve step_scale /= 2.0 until 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): When beta is already 1e-8 away from the minimum, the true loss improvement (1/2) * gradient . step is around 1e-16 — smaller than 64-bit floating-point rounding noise (~1e-15)! A strict test candidate_loss > current_loss randomly rejects valid final steps and stalls converged_ = False. Allowing 1e-12 * (1.0 + abs(current_loss)) absorbs float noise while still rejecting any genuine uphill jump. 2. Stop on step size max(|step|) < tol, NOT gradient size: Suppose X = [[0.0], [0.0], [1.0], [1.0]] and y = [3, 5, 0, 0] with l2 = 0 (Example 3). For the x = 1 group, every count is 0, so the model wants mu_1 = exp(intercept + coef) = 0, pushing coef -> -inf forever! As mu_1 -> 0, the gradient (mu_1 - 0) shrinks toward 0 even though coef has not converged; meanwhile, the Newton step H^-1 @ g stays near 1.0 per iteration, so checking np.max(np.abs(step)) < self.tol honestly leaves converged_ = 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
                    break
    
  6. Predict conditional means rather than rounded counts

    At inference time, linear_predictor(X) computes eta = intercept_ + X @ coef_ (checking first that fit() has run and X has the expected column count), and predict(X) applies the inverse link exp(eta) to return the conditional mean E[y | x].

    Why never round predict(X) to an integer? Suppose 1,000 insurance policies each have an expected claim count of 0.12 claims per year. Summing the unrounded expectations predicts 120 total claims across the portfolio, whereas rounding every policy to 0 predicts 0 claims! If a caller ever needs the probability of an exact integer count k, they can plug mu = model.predict(X) directly into mu^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))
    
  7. 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]] and y = [2, 4, 5, 9, 13] (n = 5, l2 = 0, fit_intercept = True). Notice the closed-form target first: the x = 0 group has mean (2 + 4) / 2 = 3, and the x = 1 group has mean (5 + 9 + 13) / 3 = 9. So exp(intercept) = 3 (intercept = ln(3) ≈ 1.098612) and exp(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!

  8. Complete solution

    Putting input validation, objective, newton_step, and PoissonGLM together 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 n rows and p parameters (k features plus optional intercept), scaling A by mu takes O(n * p) operations, multiplying A.T @ weighted_A to build the p x p Hessian does p^2 dot products of length n in O(n * p^2) time, and solving the p x p linear system hessian @ step = gradient via Gaussian elimination takes O(p^3) time. Any backtracking step-halving evaluation computes A @ beta in O(n * p) time.
  • Total training time — O((I + 1) * n * p^2 + I * p^3): When l2 == 0, the one-time np.linalg.matrix_rank(A) check runs a singular value decomposition (SVD) (a matrix factorization that reveals exact column rank) in O(n * p^2) time (assuming n >= p), followed by I <= max_iter Newton iterations (typically I = 5 to 8 iterations on well-posed data thanks to quadratic convergence).
  • Space — O(n * p + p^2): Storing the n x p design matrix A and weighted_A uses O(n * p) memory (explicitly avoiding an n x n diagonal weight matrix!), while storing the Hessian uses O(p^2) memory.
  • Prediction (linear_predictor and predict) — O(m * p) time and O(m) output space: Scoring m new rows performs one matrix-vector product X @ coef_ of cost O(m * p) followed by m scalar exp evaluations.

Edge cases

  • Intercept-only model (X has shape (n, 0)): Works seamlessly (p = 1), converging immediately on the warm start intercept_ = log(mean(y)) and coef_ = [].
  • All targets equal to 0 with an intercept: No finite optimum exists because mean(exp(intercept)) decreases forever as intercept -> -inf; fit detects np.sum(y) == 0 up front and raises ValueError.
  • Subgroup with all zeros (data separation): On Example 3 (x = [0, 0, 1, 1], y = [3, 5, 0, 0]) with l2 = 0, the x = 1 group wants mu = 0 (coef -> -inf). coef steps downward by ~1 per iteration without overflowing or crashing, and fit honestly sets converged_ = False at max_iter. Adding any l2 > 0 (such as l2 = 0.5) restores a unique finite minimum.
  • Collinear (linearly dependent) features: When l2 == 0, redundant columns leave infinitely many optimal beta vectors and a singular Hessian, so fit raises ValueError; when l2 > 0, the + l2 * I penalty makes the objective strictly convex and solvable.
  • Huge counts causing exp overflow on step 1: objective catches non-finite exp(eta) values as float("inf") without emitting runtime warnings, and backtracking halves step_scale until eta re-enters floating-point range.
  • Non-integer non-negative targets (e.g., y = 0.5 events/day): Valid and consistent — solving A^T @ (mu - y) = 0 depends only on E[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 i was observed for t_i months rather than 1 unit of time, expected counts are t_i * exp(eta_i) = exp(eta_i + log(t_i)), handled in GLMs by adding log(t_i) as a fixed offset (a known per-row shift added to eta_i with weight fixed to 1.0).

Common mistakes

  • Fitting ordinary least squares on log(y) or log(y + 1) instead of a Poisson GLM. log(0) blows up, adding +1 distorts small counts arbitrarily, and by Jensen's inequality (for a concave function like log, the average of the logs E[log(y)] is strictly smaller than the log of the average log(E[y]) whenever y varies), exp of a log(y) fit systematically underpredicts mean counts.
  • Penalizing intercept_ in the L2 term. Shrinking intercept_ toward 0 pulls baseline predictions toward exp(0) = 1.0 even when average counts are 0.01 or 500, breaking calibration (mean(mu) no longer equals mean(y)).
  • Building np.diag(mu) explicitly as an n x n array. That turns linear O(n * p) memory into quadratic O(n^2) memory and crashes RAM on tens of thousands of rows.
  • Mixing summed gradients with a mean objective (or vice versa). If objective divides by n while gradient forgets / n, the L2 penalty weight l2 is mismatched by a factor of n, breaking line search and optimization!
  • Requiring strict candidate_loss < current_loss with zero floating-point slack. One step before tol = 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|) < tol on separated data. When an all-zero subgroup sends coef -> -inf, mu -> 0 makes mu - y -> 0, so the gradient approaches 0 even though coef is running away to -inf! Checking Newton step length max(|step|) < tol avoids that false positive.
  • Rounding predict(X) to integers. A GLM predicts the conditional expectation E[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 in O(n * p) time per step) avoids the O(n * p^2 + p^3) matrix build/solve when feature count p is in the thousands, while mini-batch gradient methods handle tens of millions of rows n.
  • Coordinate descent (as in glmnet): Updates one parameter beta_j at a time on a quadratic approximation, which is the standard choice when adding an L1 (Lasso) penalty l1 * sum(|coef_j|) whose absolute-value corner at 0 is non-differentiable for plain Newton's method.
  • Modular Family + Link Fisher scoring: Factor out inverse_link(eta), variance(mu), and deviance(y, mu) into pluggable objects and run Fisher scoring (Newton's method using the expected Hessian weights w = (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 w separates all y = 1 rows (x_i . w > 0) from all y = 0 rows (x_i . w < 0) — a condition called complete separation — multiplying w by any larger scalar c -> +inf pushes predicted probabilities sigmoid(c * x_i . w) ever closer to 1 and 0 and drives the cross-entropy log loss ever closer to 0 without ever reaching a minimum at any finite w. For example, on x = [-2, -1, 1, 2] and y = [0, 0, 1, 1] with no penalty, Newton's method pushes the slope w through 1.20 -> 2.02 -> 2.91 -> ..., growing by roughly +1 on every single iteration (9.8 at step 10, 19.8 at step 20) until exp saturates, standard errors blow up to huge numbers, and predicted probabilities pin hard at 0.0 and 1.0 (while first-order gradient descent diverges much more slowly at rate O(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 reporting converged_ = False just as our Poisson solver does on an all-zero subgroup.

Follow-up questions

Similar questions

More Quantbot Technologies interview questions

All 2 Quantbot Technologies questions →