The interview problem
Two services each logged 10 incidents. Service A was observed for 100 service-hours and service B for 1,000. Do they have the same incident rate? Build a regression for incident counts using service attributes and observation exposure. Derive the training loss, explain coefficient interpretation and diagnose what changes when incidents cluster.
Original ML-fundamentals practice, not a reported company interview. All numerical examples are illustrative. Primary documentation retrieved September 27, 2026; page publication dates unstated; interview date not applicable.
1. Separate counts, rates and exposure
Let Y be the observed count and e be positive exposure measured in service-hours. A Poisson regression with a log link models:
Y_i | x_i, e_i ~ Poisson(mu_i) lambda_i = exp(x_iᵀ beta) incidents per service-hour mu_i = e_i lambda_i expected incident count log(mu_i) = log(e_i) + x_iᵀ beta
The exposure offset log(e) has coefficient fixed at one. It encodes proportional expected count as exposure increases while the rate-defining features remain fixed. Treating exposure as an ordinary learned feature is a different model. This proportionality deserves scrutiny if incident risk changes with service age or observation duration.
Counts must be nonnegative integers under the stated probability model, but their expected values need not be integers. Positive fractional exposure is valid. A forecast of 2.4 incidents is an expectation, not a claim that a fractional incident will occur. Changing exposure units requires changing the rate units consistently.
Define what an incident is before fitting: retries, duplicate alerts and multiple symptoms of one outage may otherwise count the same event repeatedly. Align the count and exposure windows. Missing telemetry must not become an observed zero.
2. Work through unequal observation windows
| Service | Incidents | Service-hours | Observed rate per hour |
|---|---|---|---|
| A | 10 | 100 | 0.10 |
| B | 10 | 1,000 | 0.01 |
The counts are equal; A’s observed rate is ten times B’s. This descriptive ratio alone does not establish a causal effect of service identity.
As a baseline, impose a common rate lambda across both rows. The maximum-likelihood estimate pools incidents and exposure:
lambda_hat = sum(y_i) / sum(e_i)
= 20 / 1,100 ≈ 0.0181818 incidents/hour
mu_A = 100 × lambda_hat ≈ 1.81818
mu_B = 1,000 × lambda_hat ≈ 18.18182The unweighted average of the two observed rates is 0.055, which is not the common-rate Poisson estimate. The longer observation contributes more exposure. Pooling is a model assumption here, not evidence that the two underlying rates really are equal.
Alternatively, use an intercept and an indicator for B. With these two rows and two parameters, the saturated fit has intercept log(0.1) and B coefficient log(0.01/0.1) ≈ −2.302585. Exponentiating the coefficient gives a fitted rate ratio of 0.1. Both counts fit exactly, leaving zero residual degrees of freedom: the perfect fit does not validate the model, estimate residual dispersion or establish causality.
For another context with rate 0.02/hour and exposure 100 hours, the expected count is 2. Under the Poisson assumption, the probability of at least one incident is 1 − exp(−2) ≈ 0.864665. A rate, expected count and probability are distinct quantities. A rate ratio is not generally a probability ratio.
3. Derive the objective and its geometry
For conditionally independent rows, the probability mass and negative log-likelihood are:
P(Y_i = y_i) = exp(−mu_i) mu_i^y_i / y_i! L(beta) = sum_i [mu_i − y_i log(mu_i) + log(y_i!)]
Substitute mu_i = e_i exp(x_iᵀ beta). Terms involving only observations and exposure can be removed while optimizing beta:
L_variable(beta) = sum_i [e_i exp(x_iᵀ beta) − y_i x_iᵀ beta] gradient = Xᵀ(mu − y) Hessian = Xᵀ diag(mu) X
The Hessian is positive semidefinite, so this objective is convex. Collinear features can prevent strict convexity and unique coefficients. Convexity also does not guarantee a finite unregularized optimum: with an intercept-only model and all counts zero, reducing the intercept toward negative infinity keeps improving the likelihood as the fitted rate approaches zero.
Use stable numerical routines and inspect convergence. Regularization can help identify poorly supported coefficients, but whether it resolves a boundary case depends on which parameters are penalized. Arbitrarily clipping predictions changes the objective or predictions and should not be described as mathematically equivalent fitting.
Ordinary least squares on log(Y + 1) is not this likelihood. It changes the target and weighting, handles zeros through an arbitrary transformation and requires care when converting predictions back to counts.
4. Understand the weighted-rate alternative
Some implementations fit a rate target r_i = y_i/e_i using exposure as the sample weight. The equivalence is visible in the objective:
weighted rate loss = sum_i e_i [lambda_i − r_i log(lambda_i)] count loss = sum_i [e_i lambda_i − y_i log(e_i lambda_i)] weighted − count = sum_i y_i log(e_i)
The difference is independent of beta, so the unregularized optima agree for the same design matrix. This does not claim a fractional observed rate is itself an integer-valued Poisson random variable. It is an optimization equivalence.
For the two-service example, the difference is 10 log(100) + 10 log(1,000) ≈ 115.129255. Evaluating trial rates 0.01, 0.02 and 0.05 gives that same difference. Constants and scaling matter when comparing reported likelihoods or information criteria, even when fitted means agree.
Regularized libraries may normalize losses by row count or total weight. Align the effective penalty before expecting equal estimates; the same numeric regularization parameter in two APIs does not necessarily mean the same optimization problem.
The statsmodels GLM interface accepts exposure and adds its logarithm to the linear predictor. An offset argument is already on the predictor scale, so use either exposure=e or offset=log(e) for this purpose, not both. Its array interface requires an explicit intercept if one is wanted. The scikit-learn example instead demonstrates a rate target with exposure weights. A rate prediction must be multiplied by the new exposure once to produce a count prediction.
5. Diagnose conditional dispersion
The Poisson model assumes conditional variance equals conditional mean. Raw variance across a heterogeneous dataset can exceed its raw mean even when every conditional distribution is Poisson:
Var(Y) = E[Var(Y | x, e)] + Var(E[Y | x, e])
= E[mu] + Var(mu)Different exposure lengths and feature values create the second term. Therefore, “the sample variance exceeds the mean” is not enough to reject a regression model. Inspect residuals and calibration conditional on relevant features and exposure.
A Pearson residual summary, sum((y − mu)²/mu)/(n − p), can help assess dispersion when there are residual degrees of freedom and suitable assumptions. It is not a universal test, particularly with sparse counts, dependence or a poorly specified mean. The saturated two-row example cannot provide this estimate.
If conditional counts remain more variable than the model allows, investigate omitted context, common incidents and temporal dependence. A negative-binomial alternative can model extra variation; under the NB2 convention its variance is mu + alpha mu². State the parameterization rather than assuming every implementation uses the same dispersion symbol.
Robust or cluster-aware standard errors address coefficient uncertainty under appropriate mean and dependence assumptions. They do not repair an incorrect mean or turn Poisson predictive intervals into valid intervals for clustered counts. A quasi-Poisson mean/variance specification likewise does not automatically define a full predictive probability distribution.
6. Handle zeros, exposure errors and unsuitable targets
- Many zeros: a Poisson mean of 0.1 already gives P(Y = 0) ≈ 90.48%. Assess excess zeros relative to the fitted conditional distribution before choosing a hurdle or zero-inflated model.
- Zero exposure: a positive count contradicts the stated exposure model. Zero count with zero exposure gives no information about the rate under that model. Handle these rows explicitly rather than adding an arbitrary small constant to make log(e) computable.
- Exposure measurement: inconsistent units or missing observation time distort rates. If outages reduce the measured exposure itself, the denominator may depend on the outcome; define the estimand carefully.
- Bounded events: when there can be at most one failure per request and the number of requests is known, a binomial model may be more appropriate. Any rare-event Poisson approximation should be stated.
- Shared incident bursts: treating correlated alerts as independent Poisson rows can understate uncertainty. Deduplicate the event definition or model the dependency that remains.
- Double exposure adjustment: weighting count targets by exposure is not the same as adding an exposure offset. Dividing by exposure, applying an offset and multiplying again can silently change the intended model.
7. Build and evaluate the modeling workflow
event definition and deduplication
↓
aligned count/exposure windows + available features
↓
service/time-aware train and validation splits
↓
Poisson baseline → conditional diagnostics → alternatives
↓
rate and count outputs with units and uncertaintyFor held-out count predictions, one useful loss is Poisson deviance:
D = 2 sum_i [y_i log(y_i / mu_i) − (y_i − mu_i)]
Use the convention that the first term is zero when y_i is zero; that row contributes 2mu_i. Keep normalization and exposure weighting consistent when comparing models. For the same predictions, the sum of exposure-weighted rate deviances equals the sum of count deviances. Their reported averages can differ because one divides by total exposure and another by row count; align those denominators before comparing scores.
Compare aggregated predicted and observed counts by exposure range, service family and time period. Inspect whether small windows or high-volume services dominate the chosen metric. Preserve the dependence structure in data splits and uncertainty calculations. Randomly separating adjacent windows of the same incident can give misleading validation results.
Distinguish confidence in the conditional mean from a prediction interval for a new count. The latter includes outcome variability; parameter uncertainty and shared dependence can add further uncertainty. If future exposure is unknown, forecast it or report results conditional on stated exposure scenarios. Do not use the realized future observation duration as though it were known at decision time.
8. Interview follow-ups
- What does exp(beta_j) mean? For a feature entering linearly without interactions, the multiplicative rate change for a one-unit increase, holding other features fixed. With interactions or transformations, compute the full change in the linear predictor. It is not automatically causal.
- What happens when hours become days? Exposure divides by 24 and the rate per day multiplies by 24; the expected count stays unchanged when the conversion is consistent.
- What if every training count is zero? The unregularized intercept-only rate estimate lies at the zero boundary; there is no finite log-rate maximum-likelihood estimate.
- Why not just use robust standard errors? They address a form of inference uncertainty, not predictive distribution misspecification or omitted mean structure.
- Can a model predict 20 incidents? Yes. A Poisson mean is not a probability and has no upper bound of one.
Self-review rubric
A strong answer computes rates using exposure, derives the log-link loss and explains the fixed offset. It correctly pools counts, distinguishes rates from probabilities, and proves the weighted-rate objective equivalence with its regularization caveat. An excellent answer checks conditional rather than raw dispersion, handles zero exposure and finite-optimum limits, and distinguishes coefficient inference from prediction uncertainty.
Sources and attribution
- statsmodels 0.14.4: GLM reference — exposure, offset and intercept interface semantics.
- scikit-learn: Poisson regression and non-normal loss — exposure-weighted rate modeling.
Page publication dates unstated; retrieved September 27, 2026. Service examples, derivations and review questions are original practice material. No company interview claim is made.
Continue your preparation
Choose a connected learning path or browse more ML fundamentals questions. Read our editorial method and attribution policy.