Linear Regression, Tree Ensembles, Rare Fraud, and Seasonal Forecasting
Machine LearningModel answerLast updated
Explain OLS and its assumptions, compare bagging, random forests and boosting, handle a 0.2% positive class, and outline a forecasting pipeline for data with trend and seasonality.
Context
You are the ML lead for an online marketplace. Two projects are on your plate:
- A fraud classifier, where only about 0.2% of examples are fraudulent.
- A demand forecaster whose history shows both a long-run trend and repeating seasonal cycles.
Questions
Answer each part as you would in a technical discussion, with reasoning and trade-offs rather than a list of buzzwords.
- Ordinary least squares. Describe how OLS fits a model. Give the objective, the closed-form solution and how it is computed in practice. List the assumptions it relies on and say what each one is needed for.
- Tree ensembles. Compare bagging, random forests and gradient-boosted trees. Cover how each is built, which source of error it mainly reduces, how much tuning it needs, and when you would choose each.
- Rare positives. With a 0.2% positive rate, explain how you would handle the imbalance during training and during evaluation. Cover splitting, reweighting or resampling, probability calibration, metrics, and threshold choice.
- Forecasting workflow. Lay out an end-to-end process for building a forecasting model when trend and seasonality are present, from problem framing through validation and deployment.
What a strong answer shows
- Preprocessing and feature engineering choices
- Resampling or weighting strategies and their pitfalls
- Metrics that stay meaningful under heavy imbalance
- Validation that respects the order of time
Hints
Hint 1
For OLS, start from the squared-error objective, set its gradient to zero, and ask which assumptions are needed for unbiasedness versus for valid standard errors and tests.
Hint 2
Frame the ensemble comparison around bias versus variance: bagging and random forests average independent trees, while boosting adds trees one after another to correct earlier errors.
Hint 3
At 0.2% positives, a model that always predicts the majority class is 99.8% accurate. Think about which metrics have a meaningful baseline, where resampling must happen relative to the split, and what weighting does to predicted probabilities.
Hint 4
For forecasting, avoid random shuffles. Use rolling-origin validation, build strong naive baselines first, and make sure every feature would have been known at forecast time.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Ordinary least squares
Model. y = Xβ + ε, with X an n × p design matrix (including an intercept column).
Objective. Minimize the residual sum of squares, L(β) = ‖y − Xβ‖².
Solution. Setting the gradient −2Xᵀ(y − Xβ) to zero gives the normal equations XᵀXβ = Xᵀy, so β̂ = (XᵀX)⁻¹Xᵀy. Geometrically, the fitted values are the orthogonal projection of y onto the column space of X, so the residuals are orthogonal to every feature. In practice, solve via QR or SVD instead of forming an explicit inverse, which is numerically fragile when features are nearly collinear.
Assumptions and what each buys you
| Assumption | Why it matters | Common remedy |
|---|---|---|
| Linear in parameters (features may be transformed) | Model is correctly specified | Add transforms or interactions |
| Exogeneity, E[ε|X] = 0 | Unbiased estimates | Add confounders, use instruments |
| No perfect collinearity | XᵀX invertible | Drop features, ridge |
| Constant error variance | Correct standard errors, efficiency | Robust (HC) errors, weighted LS |
| Uncorrelated errors | Correct standard errors | HAC errors, ARIMA errors |
| Normal errors | Exact small-sample t/F tests only | Usually fine with large n |
With the first five, OLS is the best linear unbiased estimator (Gauss–Markov). Diagnose with residual plots, VIF, Breusch–Pagan, Durbin–Watson and Q–Q plots.
2. Bagging vs random forest vs gradient boosting
- Bagging trains learners independently on bootstrap samples and averages them. It mainly cuts variance. It suits any high-variance base learner, but with trees a random forest is usually better.
- Random forest adds a random feature subset at every split, which decorrelates the trees and makes averaging more effective. It needs little tuning, is hard to overfit by adding trees, gives out-of-bag error for free, and tolerates noisy labels. It is a strong default baseline when validation is limited.
- Gradient boosting builds trees sequentially, each fitting the gradient of the loss of the current ensemble. It reduces bias (and variance through shrinkage and subsampling). It usually wins on tabular accuracy and supports custom losses (quantile, Tweedie, focal) and sample weights. The cost is more tuning (learning rate, depth, number of trees, regularization) and a need for a trustworthy validation set for early stopping.
Rule of thumb: random forest for a quick, robust baseline; boosting when you need the best accuracy and have clean validation; plain bagging mostly for non-tree learners.
3. Handling a 0.2% positive class
Why it is hard. With 1M rows you have only about 2,000 positives. Always predicting "legitimate" gets 99.8% accuracy, so accuracy says nothing.
Splitting
- Use stratified splits, or time-based splits if fraud patterns drift (they usually do).
- Group by account or user so one fraudster never lands in both train and test.
Training, in rough order of preference
- Class weights or cost-sensitive loss. Weight positives by about N_neg/N_pos (≈ 499) or by the real cost ratio (
scale_pos_weight,class_weight). All data is kept. - Undersample negatives (for example keep 5–10%). Fast, and works well with boosted trees.
- Oversampling or SMOTE. Use cautiously: synthetic points can be unrealistic, especially with categorical features. Apply it only inside the training fold, never before the split, or you leak information.
- Focal loss (mostly for neural nets) and anomaly-score features (for example isolation forest) when labels are scarce or delayed.
Recalibrate. Weighting or sampling inflates predicted probabilities. If you keep a fraction β of negatives, correct with p = β·p_s / (β·p_s + 1 − p_s), or fit isotonic or Platt scaling on an untouched validation set.
Evaluation
- Prefer PR-AUC / average precision (random baseline 0.002) over ROC-AUC, which looks flattering because of the huge number of true negatives.
- Report operating-point metrics: recall at a fixed precision, precision@k matching review capacity, or recall at a false-positive budget.
- Pick the threshold on validation data by minimizing expected cost (FN × fraud loss + FP × review and friction cost), never by defaulting to 0.5.
- With only a few hundred test positives, metrics are noisy, so give bootstrap confidence intervals.
4. Forecasting with trend and seasonality
- Frame the problem. Fix horizon, granularity (for example SKU × region × day) and the downstream decision. Inventory decisions need quantile forecasts (P50, P90), not only a mean.
- Clean. Make missing dates explicit, align time zones, handle outliers, and treat stockouts as censored demand rather than true zeros.
- Explore. Plot the series, run an STL decomposition, use ACF/PACF to find periods (weekly and yearly are typical), test stationarity (ADF, KPSS), and apply a log or Box–Cox transform if variance grows with level.
- Baselines first. Seasonal naive (same weekday last week or same day last year) and moving average. Every model must beat these.
- Candidate models.
- Few series: ETS/Holt–Winters or SARIMA.
- Multiple seasonalities, holidays: Prophet-style or regression with Fourier terms.
- Many related series: a global gradient-boosted or neural model with lag features, rolling means, calendar and holiday flags, price and promotion features, and series identifiers.
- Features without leakage. Only use information available at forecast time. Lags must be at least the horizon, and future covariates (holidays, planned promotions) must be genuinely known in advance.
- Validation. Use rolling-origin (expanding or sliding window) cross-validation, never random k-fold. Include a gap if features use lookback windows. Evaluate with MAE, RMSE, and a scale-free metric such as MASE or WAPE (be careful with MAPE near zero), plus pinball loss for quantiles. Check residuals for leftover autocorrelation.
- Deploy and monitor. Retrain on a schedule, track error by segment and horizon, watch for drift and structural breaks (pricing changes, new markets), and compare against the baseline continuously.
Common mistakes
- Reporting accuracy or ROC-AUC on a 0.2% positive rate.
- Resampling before splitting, or leaving uncalibrated probabilities after reweighting.
- Shuffling time-series data into random folds, or using features not known at prediction time.
- Treating stockout zeros as real demand.
- Inverting XᵀX directly and ignoring autocorrelated errors when using OLS on time series.