Skip to main content

Regression Models

Docs: Linear models · Trees · Ensembles · SVR · Regression metrics · XGBoost

Overview​

Use regression when the target is a number: hourly demand, a price, a sensor reading. The question is which model fits, and the answer is almost always "start linear". A linear model that explains most of the variance beats a boosted model you can't debug. The failure people hit is the opposite: reaching for gradient boosting first, then having no baseline to say whether its RMSE is any good.

Key concepts​

Cheatsheet​

ModelReach for it whenAvoid whenScaling?Key knobs#1 failure mode
Linear RegressionRelationship looks straight, need interpretabilityCurved residuals, correlated featuresYes—Fitting a line through a curve
Ridge (L2)Correlated features, keep them allYou need feature selectionYesalphaUntuned alpha (use RidgeCV)
Lasso (L1)Many features, most are noiseFeatures come in correlated groupsYesalphaRandomly dropping one of a correlated pair
ElasticNetFeature selection + correlated groupsSimple problems (overkill)Yesalpha, l1_ratioTuning only one of the two knobs
Polynomial + RidgeOne clear curve (peak or trough)Degree above 3 neededYesdegree, alphaExtrapolating beyond training range
Decision TreeHumans must read the rulesAccuracy is the goalNomax_depthUnconstrained depth → memorisation
Random ForestStrong baseline, no tuning budgetNeed best accuracy or extrapolationNon_estimatorsTrusting biased feature_importances_
Gradient BoostingBest tabular accuracyTiny data, no time to tuneNolearning_rate, max_depth, early stoppingNo early stopping → overfit
SVRSmall data, high-dim, non-linearMore than ~50k rowsYes (critical)C, epsilon, kernelUnscaled features

Running example: bike-rental demand​

Every model is applied to one problem: predict hourly bike rentals from temperature, humidity, wind, hour of day, day of week and season, plus ~100 engineered features (lags, rolling means, weather × hour interactions). Numbers show the typical pattern, not one specific run.

ModelTest RMSENotes
Predict-the-mean baseline165The number to beat
Linear Regression102Residuals show a hump at commute hours: linearity is wrong
Polynomial (deg 2) + Ridge88Captures the temperature curve
Ridge on all features84Correlated lag features handled
Lasso on 120 features86Keeps 18 features. Nearly as good, far simpler
Decision Tree (depth 4)95Worst accuracy, but the rules fit on a whiteboard
Random Forest (300 trees)61Big jump: the interactions are non-linear
XGBoost (tuned)55Best, but took 10× the tuning time of the forest
SVR (RBF)70Slowest to train, pickiest about inputs

Linear gets you 60% of the way in two minutes, trees buy accuracy with opacity, and boosting wins if you pay the tuning cost.

Evaluation metrics​

MetricIn plain wordsUse when
MAEAverage size of a missOutliers are noise you shouldn't be punished for; easy to explain
RMSESquare root of the average squared miss: big misses count extraDefault. Same units as the target
R²Share of the target's variance the model explains (1 = perfect)Comparing fit across targets
MAPEAverage miss as a percentage of the true valueStakeholders think in percent. Never when the target can be near zero

Five predictions with misses of 10, 10, 10, 10 and 100:

MetricValueWhy
MAE28Each miss counts by its size
RMSE45.6The single 100 is squared, so it dominates

If that 100 is a data-entry error, report MAE. If it's a real blown forecast that cost money, RMSE is telling the truth.

Linear vs non-linear​

Linear modelsNon-linear models
ExamplesLinear, Ridge, Lasso, ElasticNet, SVR (linear kernel)Decision Tree, Random Forest, Gradient Boosting, SVR (RBF)
Shape learnedStraight hyperplaneArbitrary
InterpretabilityCoefficients readableBlack box (shallow trees are the exception)
Data neededWorks on small dataBenefits from more data
Feature scalingRequiredNot for trees
ExtrapolationReasonable beyond the training rangeTrees predict the last value they saw
SignalMove
Roughly straight relationship, someone must audit coefficients, or under a few thousand rowsStay linear
Residuals show a pattern (curve, clusters)❌ Linear assumption is wrong. Add a curve term or go non-linear
Interactions matter (temperature × weekend)Go to trees
Linear is accurate enough✅ Stop. There's no prize for a fancier model

Choosing a model​

Figure M1-1: Regression model selection. Amber is the starting point for every regression problem; the residual plot picks the branch.

Linear regression​

The coefficients are the model. Fit a straight line; if it explains the variance, stop.

temperature (°C)rentals�ŷ = wx + b

Figure M1-2: Linear regression. Blue points are observed hours, the green line is the fit.

Use whenA feature-vs-target plot looks roughly straight. Always try it first
Get it rightPlot residuals against fitted values: a curve means non-linear, a funnel means errors grow with the prediction. Correlated features make coefficients unstable: use Ridge. Scale features to compare coefficient sizes
On the bike dataRMSE 102 vs 165 baseline. Coefficients read cleanly: +9 rentals per °C, −40 when raining. The residual hump at 8am and 6pm is the signal to move on, not the RMSE

Ridge regression (L2)​

Ridge shrinks every weight toward zero and keeps all of them, sharing credit across correlated features.

PenaltySum of squared weights. No weight reaches zero
Use whenFeatures are correlated. Plain linear regression gives them wild, cancelling coefficients
Get it rightScale first: the penalty hits all weights equally. Tune alpha with RidgeCV over a log-spaced grid (0.001–1000)
On the bike dataPlain OLS gave one lag +85 and its neighbour −79. Ridge shares credit across the lag group: RMSE 84, presentable coefficients

Lasso regression (L1)​

Lasso is feature selection built into the loss: some weights go to exactly zero.

Ridge (L2)Lasso (L1)w1w2w3w4w5all kept, shrunkw1w2w3w4w5w2, w4 zeroed out00

Figure M1-3: The same five weights under each penalty. Ridge shrinks all of them; Lasso zeroes w2 and w4.

PenaltySum of absolute weights
Use whenMany features, most of them noise
Get it rightScale first. Tune with LassoCV; too high an alpha zeroes everything. Correlated groups: Lasso keeps one at random. Use ElasticNet
On the bike data120 engineered features → 18 kept, RMSE 86. Slightly worse than Ridge for a model that fits on one slide

ElasticNet​

ElasticNet is Lasso with a safety net: sparsity from L1, and correlated groups survive thanks to L2.

KnobSettingWhy
alphaSearched by ElasticNetCVOverall penalty strength
l1_ratioSearch 0.1, 0.5, 0.7, 0.9, 0.95, 1.01.0 is pure Lasso, 0 is pure Ridge
Search result near 1 or near 0—Just use Lasso or Ridge

On the bike data, Lasso kept lag_1h in one split and lag_2h in another, so the "selected features" story changed between runs. ElasticNet keeps the lag group together and still zeroes the junk interactions: same RMSE as Lasso, reproducible selection.

Polynomial regression​

Polynomial regression is still a linear model: linear in the parameters, curved in the features. Add squared or cubed terms and every linear-model rule still applies.

temperature (°C)rentalsDegree 1 — underfitsDegree 2 — just rightHigh degree — overfits

Figure M1-4: Fitting a curve. Grey dashed is degree 1 (underfits), green is degree 2 (fits), red dotted is a high degree (overfits).

Use whenA clear curve with a peak or trough. Degree 2 or 3 covers almost every real case; needing 5+ means use a tree
Get it rightAlways pair with Ridge or Lasso. Never extrapolate: polynomials diverge outside the data. Low training error with high validation error means the degree is too high
On the bike dataDemand rises to about 27°C, then falls in the heat. One temperature² term drops RMSE from 102 to 88

Decision tree regressor​

The only model whose whole logic a human can read, and the worst one to ship alone.

Figure M1-5: A depth-2 tree on the bike data. Amber nodes are leaves: the prediction is the mean of the training hours that land there.

Use whenOperations, compliance or domain experts need rules they can check
Get it rightmax_depth 3–5; unconstrained trees memorise. No scaling needed. Treat it as a diagnostic, not the final model
On the bike dataRMSE 95. The splits at 7am, 9am and 5pm confirmed the commute structure the linear residuals hinted at

Random forest regressor​

Average hundreds of overfit trees and the overfitting cancels out. → See bagging vs boosting.

Use whenYou want a strong non-linear baseline without tuning
Get it right100 trees to start, 300–500 if variance remains. oob_score=True gives a free validation estimate. Rank features with permutation importance, not feature_importances_
On the bike dataRMSE 88 (best linear) → 61 with no tuning. That gap is the evidence the problem is non-linear

Gradient boosting​

Each tree fits the errors of the ensemble so far. Boosting removes bias, and early stopping is non-negotiable. → See bagging vs boosting.

LibraryPick it when
XGBoostStandard choice, strong regularisation, works everywhere
LightGBMLarge data (100k+ rows), need speed
CatBoostMany categorical features, minimal preprocessing
KnobSettingWhy
early_stopping_rounds50, on a validation setThe model picks its own tree count
learning_rate0.01–0.05 with 500–2000 roundsBeats a high rate with few rounds
max_depth3–6, tuned firstMain capacity control
Sampling paramsTuned lastSmall further gains

On the bike data: RMSE 55, the best, after a search that took longer than every other model combined. The untuned first attempt (61) was no better than the forest.

Support vector regression (SVR)​

Only points outside the ε-tube count toward the loss. Everything inside is free. kernel="linear" makes SVR a linear model; the default RBF kernel makes it non-linear.

x (feature)ε-tubesupport vectors

Figure M1-6: The ε-tube. Blue points inside the dashed tube cost nothing; circled points outside it are the support vectors that define the fit.

Use whenSmall (under 10k rows), high-dimensional, non-linear data: spectroscopy, lab measurements
Get it rightStandardise features. Training cost grows with the square of the rows or worse: above ~50k rows, pick another model. Tune C, epsilon and kernel
On the bike dataRMSE 70 on a 10k subsample, slowest to train, and worse on the full 100k rows the trees handled easily

Gotchas​

  • Skipping the residual plot. RMSE says how wrong, not why. Plot residuals against fitted values before changing models.
  • Unscaled features in linear models or SVR. Penalties and distances are dominated by the biggest units. Scale inside the pipeline.
  • Boosting without early stopping. A fixed round count overfits. Pass a validation set and let it stop.
  • Extrapolating with trees or polynomials. Trees flatten at the last seen value; polynomials explode. Keep predictions inside the training range or use a linear model.
  • MAPE with targets near zero. Division by a tiny number explodes the metric. Use MAE or RMSE for low-count hours.
  • Lasso on correlated groups. Which feature survives changes between runs. Use ElasticNet.

Scenario questions​

Q1 ★ Your RMSE is 45.6 but MAE is 28. What does that tell you, and which do you report?

Model answer
  • Clarify: what does a large miss cost the business compared to a small one?
  • Observe: RMSE well above MAE means a few large misses dominate; here one miss of 100 among misses of 10.
  • Hypothesise: either a data error in that row, or a real event the model can't predict.
  • Fix: check the row. Data error: fix it and report MAE. Real miss: report RMSE, because big misses cost money.
  • Prevent: agree the metric with stakeholders before modelling. The trade-off is that the metric choice changes which model wins.

Q2 ★★ Linear regression gives RMSE 102 and the residuals hump at 8am and 6pm. What next?

Model answer
  • Clarify: is interpretability still required?
  • Observe: residuals against hour of day show peaks at commute hours; residuals against temperature show a curve.
  • Hypothesise: demand depends on hour and temperature non-linearly, and on interactions like hour × weekend.
  • Fix: add a temperature² term (RMSE 88) if interpretability matters; otherwise a Random Forest (61), then tuned boosting (55).
  • Prevent: the residual plot is the trigger for every model change. The trade-off is losing readable coefficients.

Q3 ★★ Lasso keeps lag_1h in one run and lag_2h in another. Why, and what do you do?

Model answer
  • Clarify: do stakeholders rely on the list of selected features?
  • Observe: the two lags correlate at over 0.9; which one survives depends on the split.
  • Hypothesise: L1 picks one member of a correlated group arbitrarily.
  • Fix: ElasticNet, with l1_ratio searched, keeps the group together.
  • Prevent: check feature-to-feature correlation before trusting a selected-feature list. The trade-off is one more knob to tune.

Q4 ★★★ Next summer may be hotter than anything in the training data. Which model do you trust for those days?

Model answer
  • Clarify: how far outside the training range, and what decision depends on it (bike stocking, staffing)?
  • Observe: the tree models' predictions flatten above the hottest training day; the degree-2 polynomial keeps falling.
  • Hypothesise: trees can't extrapolate. Polynomials extrapolate wildly. Neither knows how people behave at 40°C.
  • Fix: flag out-of-range inputs, cap predictions with a domain rule, or fall back to a simpler model for those days.
  • Prevent: monitor input ranges against training. The trade-off is a cruder forecast on exactly the days that matter.

Summary​

  • Start linear. Two minutes, a baseline, and residuals that tell you what's missing.
  • The residual plot picks the next model. A curve means a curve term; interactions mean trees.
  • Penalties have personalities. Ridge keeps correlated features, Lasso deletes noise, ElasticNet does both.
  • Boosting wins only after tuning. Early stopping and a low learning rate, or the forest is just as good.
  • Pick the metric by the cost of a big miss. RMSE when large misses cost money, MAE when they're noise.

Next → Classification