35. Regression — Cheat sheet
The essentials of module 35 on one page. Every runnable block on this page is checked against its output. The blocks run top to bottom and share one setup.
Quick lookup
Section titled “Quick lookup”| I want to… | Use… | Note |
|---|---|---|
| set a floor for any model | DummyRegressor(strategy="mean") |
R² ≈ 0; "median" minimizes MAE |
| fit OLS by hand | np.linalg.lstsq(np.column_stack([ones, X]), y) |
never inv(X.T @ X) |
| fit OLS | LinearRegression().fit(X, y) |
coef_, intercept_ |
| prepare mixed columns | ColumnTransformer([("cat", OneHotEncoder(drop="first"), cats), ("num", num_pipe, nums)]) |
inside a Pipeline |
| get feature names after preprocessing | pre.get_feature_names_out() |
aligns with coef_ |
| fit on log price, predict USD | TransformedTargetRegressor(reg, func=np.log, inverse_func=np.exp) |
np.log1p / np.expm1 if 0 is possible |
| read a log coefficient | (np.exp(w * step) - 1) * 100 |
percent change per step units |
| shrink weights (L2) | Ridge(alpha=1.0) |
scale first |
| select features (L1) | Lasso(alpha=...) |
zeros out weights; scale first |
| mix L1 and L2 | ElasticNet(alpha=..., l1_ratio=0.5) |
l1_ratio=1 is Lasso |
| choose alpha by CV | RidgeCV(alphas=...), LassoCV(cv=5), ElasticNetCV |
winner in alpha_ |
| bend a linear model | PolynomialFeatures(degree, include_bias=False) |
scale before high degrees |
| average similar rows | KNeighborsRegressor(n_neighbors=5) |
scale first; no extrapolation |
| learn rules | DecisionTreeRegressor(max_depth=..., min_samples_leaf=...) |
no scaling |
| average many trees | RandomForestRegressor(n_estimators=100, n_jobs=-1) |
oob_score=True for a free estimate |
| boost trees | HistGradientBoostingRegressor() |
native NaN; category dtype columns |
| predict a quantile | HistGradientBoostingRegressor(loss="quantile", quantile=0.9) |
for ranges, not means |
| typical error in USD | mean_absolute_error(y_true, y_pred) |
robust to outliers |
| error that punishes big misses | root_mean_squared_error(y_true, y_pred) |
not squared=False (removed) |
| variance explained | r2_score(y_true, y_pred) or model.score(X, y) |
order matters |
| relative error | mean_absolute_percentage_error(y_true, y_pred) |
returns a fraction |
| CV error of a setting | cross_val_score(m, X, y, cv=cv, scoring="neg_root_mean_squared_error") |
flip the sign |
| train and CV curves | cross_validate(..., return_train_score=True) |
over- vs underfit |
| a prediction for every row, honestly | cross_val_predict(model, X, y, cv=cv) |
out-of-fold |
| a Q-Q plot | scipy.stats.probplot(resid, dist="norm", plot=ax) |
residual normality |
Setup used on this page
Section titled “Setup used on this page”import numpy as npimport pandas as pdfrom sklearn.base import clonefrom sklearn.compose import ColumnTransformer, TransformedTargetRegressorfrom sklearn.impute import SimpleImputerfrom sklearn.linear_model import LinearRegressionfrom sklearn.model_selection import KFold, train_test_splitfrom sklearn.pipeline import make_pipelinefrom sklearn.preprocessing import OneHotEncoder, StandardScaler
pd.set_option("display.width", 100)pd.set_option("display.precision", 3)
houses = pd.read_csv("data/houses.csv")X = houses.drop(columns=["house_id", "sold_date", "price"])y = houses["price"]X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.25, random_state=42 # split once, before anything learns)cat_cols = ["neighborhood"]num_cols = [c for c in X.columns if c not in cat_cols]cv = KFold(n_splits=5, shuffle=True, random_state=42)pre = ColumnTransformer( [ ("cat", OneHotEncoder(drop="first"), cat_cols), # drop one: unique weights ( "num", make_pipeline(SimpleImputer(strategy="median"), StandardScaler()), num_cols, ), ], verbose_feature_names_out=False,)Linear regression
Section titled “Linear regression”| Idea | Formula | Code |
|---|---|---|
| prediction | model.predict(X) |
|
| OLS loss | what LinearRegression minimizes |
|
| normal equations | np.linalg.lstsq(A, y) |
|
| coefficient | change in per unit of , others fixed | model.coef_ |
| one-hot coefficient | difference from the dropped reference category | OneHotEncoder(drop="first") |
| log-target coefficient | % per unit | np.exp(coef) - 1 |
A_train = pre.fit_transform(X_train) # learn medians, means, sds on train onlyA1 = np.column_stack([np.ones(len(A_train)), A_train]) # ones column = interceptw, *_ = np.linalg.lstsq(A1, y_train.to_numpy())ols = LinearRegression().fit(A_train, y_train)print(np.isclose(w[0], ols.intercept_), np.allclose(w[1:], ols.coef_))True Truelinear = make_pipeline(pre, LinearRegression()).fit(X_train, y_train)coefs = pd.Series(linear[-1].coef_, index=linear[0].get_feature_names_out())print(coefs[["sqft", "has_pool"]].round(0)) # USD per standard deviationsqft 179361.0has_pool 24215.0dtype: float64Log target
Section titled “Log target”log_model = TransformedTargetRegressor( regressor=make_pipeline(clone(pre), LinearRegression()), # a fresh copy func=np.log, # applied to y before fit inverse_func=np.exp, # applied to predictions).fit(X_train, y_train)print(f"price R² {linear.score(X_test, y_test):.3f}")print(f"log R² {log_model.score(X_test, y_test):.3f}") # scored in USDprice R² 0.792log R² 0.898| Fact | Detail |
|---|---|
| when it helps | right-skewed targets (prices, incomes, counts); multiplicative effects; a funnel in the residuals |
what predict returns |
: closer to the median than the mean (slight underestimate of totals) |
| zeros in the target | func=np.log1p, inverse_func=np.expm1 |
| inner model after fit | log_model.regressor_ |
Metrics
Section titled “Metrics”| Metric | Formula | Function | Misleads when |
|---|---|---|---|
| MAE | mean_absolute_error |
big misses matter more than small | |
| MSE | mean_squared_error |
always hard to read (squared units) | |
| RMSE | root_mean_squared_error |
a few outliers dominate | |
| R² | r2_score |
comparing different test sets or target scales | |
| MAPE | mean_absolute_percentage_error |
targets near 0; favors underestimates |
from sklearn.metrics import ( mean_absolute_error, mean_absolute_percentage_error, r2_score, root_mean_squared_error,)
pred = log_model.predict(X_test)print(f"MAE {mean_absolute_error(y_test, pred):,.0f}")print(f"RMSE {root_mean_squared_error(y_test, pred):,.0f}")print(f"R² {r2_score(y_test, pred):.3f}") # y_true first, alwaysprint(f"MAPE {mean_absolute_percentage_error(y_test, pred):.1%}") # a fractionMAE 65,262RMSE 102,961R² 0.898MAPE 13.5%Residual analysis
Section titled “Residual analysis”| Plot | Code | Healthy | Warning → fix |
|---|---|---|---|
| residuals vs fitted | ax.scatter(pred, y - pred) |
flat band at 0 | curve → nonlinear terms or trees; funnel → log target |
| histogram | ax.hist(resid, bins=40) |
one hump at 0 | long tail → check outliers |
| Q-Q plot | stats.probplot(resid, dist="norm", plot=ax) |
points on the line | ends bend away → heavy tails |
| worst rows | resid.abs().nlargest(5) |
no pattern | a shared trait → a missing feature or a data error |
resid = np.log(y_test) - np.log(pred) # log residual: 0.1 ≈ 10% too lowworst = resid.abs().nlargest(3).indexprint(houses.loc[worst, ["house_id", "neighborhood", "year_built"]].to_string()) house_id neighborhood year_built179 H0180 Old Town 1957296 H0297 Old Town 19571584 H1585 Lakeview 2022Regularization
Section titled “Regularization”| Model | Penalty added to the loss | Zeros? | Typical grid |
|---|---|---|---|
Ridge |
no | np.logspace(-3, 3, 13) |
|
Lasso |
(loss scaled by ) | yes | LassoCV builds its own |
ElasticNet |
yes | l1_ratio in [0.1, 0.5, 0.9] |
from sklearn.datasets import load_diabetesfrom sklearn.linear_model import LassoCV, RidgeCV
Xd, yd = load_diabetes(return_X_y=True, as_frame=True)ridge = make_pipeline(StandardScaler(), RidgeCV(alphas=np.logspace(-2, 3, 11)))lasso = make_pipeline(StandardScaler(), LassoCV(cv=5, random_state=42)) # scale firstprint(f"Ridge alpha_ {ridge.fit(Xd, yd)[-1].alpha_:.3g}")kept = Xd.columns[lasso.fit(Xd, yd)[-1].coef_ != 0]print(f"Lasso alpha_ {lasso[-1].alpha_:.3g}, kept {len(kept)} of {Xd.shape[1]}")Ridge alpha_ 1Lasso alpha_ 0.0789, kept 9 of 10Flexible models
Section titled “Flexible models”| Model | Key settings | Too simple | Too flexible | Scale? |
|---|---|---|---|---|
| polynomial + linear | degree |
degree 1 on a curve | degree 10+ on few rows | yes |
KNeighborsRegressor |
n_neighbors, weights |
large k |
k=1 |
yes |
DecisionTreeRegressor |
max_depth, min_samples_leaf |
depth 1–3 | no limit | no |
RandomForestRegressor |
n_estimators, max_features, min_samples_leaf |
very large leaves | rarely overfits | no |
HistGradientBoostingRegressor |
learning_rate, max_iter, max_leaf_nodes |
few rounds | many rounds, high rate | no |
from sklearn.ensemble import HistGradientBoostingRegressorfrom sklearn.model_selection import cross_val_scorefrom sklearn.tree import DecisionTreeRegressor
for depth in [3, 9, None]: # underfit, about right, overfit reg = DecisionTreeRegressor(max_depth=depth, random_state=42) tree = make_pipeline(clone(pre), reg) rmse = -cross_val_score( tree, X_train, y_train, cv=cv, scoring="neg_root_mean_squared_error" ).mean() print(f"max_depth={depth}: CV RMSE {rmse:,.0f}")max_depth=3: CV RMSE 184,545max_depth=9: CV RMSE 148,786max_depth=None: CV RMSE 154,143hood = pd.CategoricalDtype(sorted(X_train["neighborhood"].unique())) # one listXc_train = X_train.astype({"neighborhood": hood})Xc_test = X_test.astype({"neighborhood": hood})boost = HistGradientBoostingRegressor(random_state=42).fit(Xc_train, y_train) # NaN okprint(f"boosting R² {boost.score(Xc_test, y_test):.3f}, rounds {boost.n_iter_}")boosting R² 0.909, rounds 100Boosting update: , where each tree fits the current residuals and is learning_rate.
Reference scores on data/houses.csv
Section titled “Reference scores on data/houses.csv”Hold-out test set, test_size=0.25, random_state=42, from the lesson:
| Model | MAE (USD) | RMSE (USD) | R² | MAPE |
|---|---|---|---|---|
| baseline (mean) | 215,799 | 323,250 | −0.001 | 0.511 |
| linear, price | 98,861 | 147,324 | 0.792 | 0.237 |
| tree, depth 9 | 84,905 | 144,490 | 0.800 | 0.169 |
| KNN, k = 5 | 73,125 | 113,025 | 0.878 | 0.153 |
| random forest, 100 trees | 65,209 | 104,001 | 0.896 | 0.136 |
| linear, log price | 65,262 | 102,961 | 0.898 | 0.135 |
| boosting, price | 60,889 | 97,559 | 0.909 | 0.125 |
| boosting, log price | 58,647 | 94,269 | 0.915 | 0.119 |
Workflow
Section titled “Workflow”- Split once (
random_state=42). Never look at the test set until the end. - Fit
DummyRegressorfor a baseline. - Fit a linear model in a pipeline. Plot residuals against fitted values.
- Funnel or skew → log target with
TransformedTargetRegressor. - Many or correlated features →
RidgeCV/LassoCVafter scaling. - Curves and interactions →
HistGradientBoostingRegressor(or a forest). - Tune with cross-validation on the training set; compare models in one table of MAE, RMSE, R² and MAPE.
- Score the chosen model once on the test set. Inspect its worst residuals.
Gotchas
Section titled “Gotchas”metric(y_true, y_pred): the true values come first. R² is not symmetric.mean_squared_error(..., squared=False)was removed in scikit-learn 1.6. Useroot_mean_squared_error.mean_absolute_percentage_errorreturns 0.12 for 12%. Format with:.1%.- Scale before Ridge, Lasso, ElasticNet, KNN and high polynomial degrees. Trees and boosting do not need it.
- Ridge’s
alphaand Lasso’salphalive on different scales (Lasso divides the squared error by ). Do not copy one to the other. - A Lasso zero is not proof that a feature is useless: among correlated features, Lasso keeps one almost at random.
- With one-hot columns and an intercept, drop one category (or use a penalty), or the weights are not unique.
- Compare R² only on the same test set and the same target scale. Score log models after back-transforming.
PolynomialFeatures(3)on 17 features makes over 1,000 columns. Add powers to chosen columns only.- An unlimited tree has training R² of 1.0. That is memorization, not skill.
- Trees, forests and KNN never predict outside the range of the training targets.
.astype("category")on train and test separately can give different category lists. Build oneCategoricalDtypefrom the training data.HistGradientBoostingRegressorturns on early stopping only above 10,000 rows (early_stopping="auto").- A raw coefficient’s size is not its importance: it depends on the feature’s unit.
- Residuals against the true values always slope. Plot them against the fitted values.
- One transformer object in two pipelines is refitted by both. Give each pipeline its own copy:
clone(pre)or amake_preprocessor()function.