Skip to content

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.

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
import numpy as np
import pandas as pd
from sklearn.base import clone
from sklearn.compose import ColumnTransformer, TransformedTargetRegressor
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import KFold, train_test_split
from sklearn.pipeline import make_pipeline
from 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,
)
Idea Formula Code
prediction y^=b+x⊤w\hat{y} = b + \mathbf{x}^\top \mathbf{w} model.predict(X)
OLS loss ∑i(yi−y^i)2\sum_i (y_i - \hat{y}_i)^2 what LinearRegression minimizes
normal equations A⊤A w=A⊤yA^\top A\,\mathbf{w} = A^\top \mathbf{y} np.linalg.lstsq(A, y)
coefficient change in y^\hat{y} per unit of xjx_j, others fixed model.coef_
one-hot coefficient difference from the dropped reference category OneHotEncoder(drop="first")
log-target coefficient (ew−1)×100(e^{w} - 1) \times 100 % per unit np.exp(coef) - 1
A_train = pre.fit_transform(X_train) # learn medians, means, sds on train only
A1 = np.column_stack([np.ones(len(A_train)), A_train]) # ones column = intercept
w, *_ = 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_))
Output
True True
linear = 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 deviation
Output
sqft 179361.0
has_pool 24215.0
dtype: float64
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 USD
Output
price R² 0.792
log R² 0.898
Fact Detail
when it helps right-skewed targets (prices, incomes, counts); multiplicative effects; a funnel in the residuals
what predict returns ez^e^{\hat{z}}: 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_
Metric Formula Function Misleads when
MAE 1n∑∣y−y^∣\frac{1}{n}\sum \lvert y - \hat{y} \rvert mean_absolute_error big misses matter more than small
MSE 1n∑(y−y^)2\frac{1}{n}\sum (y - \hat{y})^2 mean_squared_error always hard to read (squared units)
RMSE MSE\sqrt{\text{MSE}} root_mean_squared_error a few outliers dominate
R² 1−∑(y−y^)2∑(y−yˉ)21 - \frac{\sum (y - \hat{y})^2}{\sum (y - \bar{y})^2} r2_score comparing different test sets or target scales
MAPE 1n∑∣y−y^y∣\frac{1}{n}\sum \left\lvert \frac{y - \hat{y}}{y} \right\rvert 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, always
print(f"MAPE {mean_absolute_percentage_error(y_test, pred):.1%}") # a fraction
Output
MAE 65,262
RMSE 102,961
R² 0.898
MAPE 13.5%
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 low
worst = resid.abs().nlargest(3).index
print(houses.loc[worst, ["house_id", "neighborhood", "year_built"]].to_string())
Output
house_id neighborhood year_built
179 H0180 Old Town 1957
296 H0297 Old Town 1957
1584 H1585 Lakeview 2022
Model Penalty added to the loss Zeros? Typical grid
Ridge α∥w∥22\alpha \lVert \mathbf{w} \rVert_2^2 no np.logspace(-3, 3, 13)
Lasso α∥w∥1\alpha \lVert \mathbf{w} \rVert_1 (loss scaled by 12n\frac{1}{2n}) yes LassoCV builds its own
ElasticNet αρ∥w∥1+α(1−ρ)2∥w∥22\alpha\rho \lVert \mathbf{w} \rVert_1 + \frac{\alpha(1-\rho)}{2} \lVert \mathbf{w} \rVert_2^2 yes l1_ratio in [0.1, 0.5, 0.9]
from sklearn.datasets import load_diabetes
from 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 first
print(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]}")
Output
Ridge alpha_ 1
Lasso alpha_ 0.0789, kept 9 of 10
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 HistGradientBoostingRegressor
from sklearn.model_selection import cross_val_score
from 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}")
Output
max_depth=3: CV RMSE 184,545
max_depth=9: CV RMSE 148,786
max_depth=None: CV RMSE 154,143
hood = pd.CategoricalDtype(sorted(X_train["neighborhood"].unique())) # one list
Xc_train = X_train.astype({"neighborhood": hood})
Xc_test = X_test.astype({"neighborhood": hood})
boost = HistGradientBoostingRegressor(random_state=42).fit(Xc_train, y_train) # NaN ok
print(f"boosting R² {boost.score(Xc_test, y_test):.3f}, rounds {boost.n_iter_}")
Output
boosting R² 0.909, rounds 100

Boosting update: Fm(x)=Fm−1(x)+η hm(x)F_m(\mathbf{x}) = F_{m-1}(\mathbf{x}) + \eta\,h_m(\mathbf{x}), where each tree hmh_m fits the current residuals and η\eta is learning_rate.

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
  1. Split once (random_state=42). Never look at the test set until the end.
  2. Fit DummyRegressor for a baseline.
  3. Fit a linear model in a pipeline. Plot residuals against fitted values.
  4. Funnel or skew → log target with TransformedTargetRegressor.
  5. Many or correlated features → RidgeCV / LassoCV after scaling.
  6. Curves and interactions → HistGradientBoostingRegressor (or a forest).
  7. Tune with cross-validation on the training set; compare models in one table of MAE, RMSE, R² and MAPE.
  8. Score the chosen model once on the test set. Inspect its worst residuals.
  • 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. Use root_mean_squared_error.
  • mean_absolute_percentage_error returns 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 alpha and Lasso’s alpha live on different scales (Lasso divides the squared error by 2n2n). 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 one CategoricalDtype from the training data.
  • HistGradientBoostingRegressor turns 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 a make_preprocessor() function.