Skip to content

35. Regression

A regression model predicts a number: the price of a house, the revenue of next month, the progression of a disease. This module builds the full regression toolbox on one realistic task: predicting the sale price of 3,000 houses in data/houses.csv. You start with linear regression, written from scratch and then with scikit-learn. You add regularization, polynomial features and four nonlinear models. Every model is judged the same way: one train/test split, five metrics and a look at the residuals.

  • Fit a linear regression from scratch with np.linalg.lstsq, match it with scikit-learn’s LinearRegression inside a Pipeline with a ColumnTransformer, and read its coefficients in USD and in percent.
  • Measure a regression model with MAE, MSE, RMSE, R² and MAPE, and know when each one misleads.
  • Diagnose a model with residual plots: residuals against fitted values, a histogram and a Q-Q plot.
  • Predict log price and back-transform it with TransformedTargetRegressor.
  • Shrink coefficients with Ridge, Lasso and ElasticNet, pick alpha with RidgeCV and LassoCV, and see under- and overfitting as you change a polynomial degree.
  • Fit KNN, decision tree, random forest and gradient boosting regressors, tune their key setting with cross-validation, and compare every model in one table.

The lesson page runs top to bottom in one namespace. The setup block loads the libraries and the houses, separates the features from the target and splits the data once. The test set (the 750 houses that the models never see during training) is used only to score finished models.

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.model_selection import 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.max_columns", 12)
pd.set_option("display.precision", 3)
np.set_printoptions(precision=3, suppress=True)
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
)
cat_cols = ["neighborhood"]
num_cols = [c for c in X.columns if c not in cat_cols]
print(X_train.shape, X_test.shape)
print(len(num_cols), "numeric columns, e.g.", num_cols[:4])
Output
(2250, 11) (750, 11)
10 numeric columns, e.g. ['sqft', 'bedrooms', 'bathrooms', 'year_built']

X keeps the eleven columns that describe a house. house_id is a label, not a property of the house, so it is dropped. sold_date is dropped to keep the feature list identical to the reference scores in the data dictionary (exercise M35-X01 adds it back). lot_sqft and school_rating each have 90 blanks, so the pipelines impute them.

Regression is supervised learning with a numeric target: every training row has the right answer, and the model learns to reproduce it. Classification (module 36) predicts a category instead.

Every regression model needs a baseline: the score of a model that ignores the features. The simplest baseline predicts the mean training price for every house. scikit-learn calls it DummyRegressor. A real model must beat it clearly, or it has learned nothing.

from sklearn.dummy import DummyRegressor
from sklearn.metrics import mean_absolute_error
baseline = DummyRegressor(strategy="mean").fit(X_train, y_train)
baseline_pred = baseline.predict(X_test)
print(f"baseline predicts {baseline_pred[0]:,.0f} USD for every house")
print(f"baseline MAE: {mean_absolute_error(y_test, baseline_pred):,.0f} USD")
Output
baseline predicts 474,008 USD for every house
baseline MAE: 215,799 USD

The mean absolute error (MAE) is the average size of an error, in USD. Guessing the mean is wrong by about this much per house. Every model in this module is measured against this number.

Linear regression: a weighted sum of features

Section titled “Linear regression: a weighted sum of features”

Linear regression predicts the target as a weighted sum of the features plus a constant:

y^=b+w1x1+w2x2+⋯+wpxp\hat{y} = b + w_1 x_1 + w_2 x_2 + \dots + w_p x_p

Each weight wjw_j is a coefficient: the change in the prediction when feature xjx_j grows by one unit and every other feature stays the same. The constant bb is the intercept: the prediction when every feature is 0. The hat in y^\hat{y} (“y hat”) marks a prediction, not a true value.

The model chooses the weights that make the residuals (true value minus prediction, yi−y^iy_i - \hat{y}_i) as small as possible. It minimizes the sum of squared residuals. This method is called ordinary least squares (OLS):

min⁡b, w∑i=1n(yi−y^i)2\min_{b,\,\mathbf{w}} \sum_{i=1}^{n} \left(y_i - \hat{y}_i\right)^2

Squaring makes every residual positive and punishes big misses more than small ones. With one feature, the solution is the straight line that fits the cloud of points best. Here is the line for price against size, solved with np.linalg.lstsq as in module 32. The column of ones gives the intercept.

A = np.column_stack([np.ones(len(X_train)), X_train["sqft"]])
w, *_ = np.linalg.lstsq(A, y_train.to_numpy())
print(f"price ≈ {w[0]:,.0f} + {w[1]:,.1f} × sqft")
print(f"a 2,000 sqft house: {w[0] + w[1] * 2000:,.0f} USD")
Output
price ≈ -127,730 + 323.1 × sqft
a 2,000 sqft house: 518,446 USD

Each extra square foot adds the slope to the predicted price. The negative intercept is no mistake: a house of 0 sqft does not exist, so the intercept is only an anchor for the line, not a price.

For many features, put the rows in a design matrix AA (the feature matrix with a column of ones in front). The best weights solve the normal equations A⊤A w=A⊤yA^\top A\,\mathbf{w} = A^\top \mathbf{y}, so w=(A⊤A)−1A⊤y\mathbf{w} = (A^\top A)^{-1} A^\top \mathbf{y}. Never compute the inverse in code. lstsq solves the same problem in a numerically stable way, and scikit-learn’s LinearRegression does too (module 32 explains why).

Linear regression in a scikit-learn Pipeline

Section titled “Linear regression in a scikit-learn Pipeline”

Real features need preparation before a linear model can use them: the neighborhood is text, two columns have blanks, and the numbers have very different scales. A ColumnTransformer (module 34) prepares each group of columns, and a Pipeline chains it with the model. The pipeline learns every preparation step from the training rows only, so no information from the test set leaks into the model.

flowchart LR
    X["X_train<br/>11 columns"] --> CT["ColumnTransformer"]
    CT --> C["neighborhood<br/>OneHotEncoder"]
    CT --> N["10 numbers<br/>SimpleImputer → StandardScaler"]
    C --> M["LinearRegression"]
    N --> M
    M --> P["predict(X_test)"]

This function builds the preprocessor. The lesson reuses it for every linear model. drop="first" leaves out one neighborhood column; the next section explains why.

def make_preprocessor(scale: bool = True) -> ColumnTransformer:
"""One-hot encode the neighborhood, impute (and scale) the numbers."""
num_steps = [SimpleImputer(strategy="median")]
if scale:
num_steps.append(StandardScaler())
return ColumnTransformer(
[
("cat", OneHotEncoder(drop="first"), cat_cols),
("num", make_pipeline(*num_steps), num_cols),
],
verbose_feature_names_out=False,
)
from sklearn.linear_model import LinearRegression
linear = make_pipeline(make_preprocessor(), LinearRegression())
linear.fit(X_train, y_train)
print(list(linear.named_steps))
print(f"test MAE: {mean_absolute_error(y_test, linear.predict(X_test)):,.0f} USD")
print(f"test R²: {linear.score(X_test, y_test):.3f}")
Output
['columntransformer', 'linearregression']
test MAE: 98,861 USD
test R²: 0.792

The linear model cuts the baseline error by more than half. A regressor’s .score() returns R² (see Regression metrics): 0.79 means that the model explains 79% of the price variance in the test set. This matches the reference score in the data dictionary.

A coefficient answers one question: “how much does the prediction change when this feature grows by one unit, with every other feature held fixed?” Four rules keep the reading honest:

Rule Why
Read the unit. A raw coefficient is “USD per sqft” or “USD per km”. A standardized coefficient is “USD per standard deviation”.
Compare sizes only after standardizing. A per-sqft coefficient looks tiny next to a per-bedroom one, because one square foot is a tiny change.
A one-hot coefficient is relative to the reference category. With drop="first", the first neighborhood (alphabetically, Cedar Park) has no column. Every other neighborhood coefficient is the difference from it.
A coefficient is an association, not a cause. Correlated features share credit. The model describes the data; it does not run an experiment.

Why drop one category? The one-hot columns of a row always sum to 1, exactly like the column of ones for the intercept. With all eight columns, one column is the sum of others, so infinitely many weight sets give the same predictions. Dropping one column makes the weights unique and gives them a clear meaning. This exact case is called perfect collinearity (the dummy variable trap, module 33). When features are strongly but not exactly correlated, it is called multicollinearity: the weights are unique but unstable, even when the predictions are fine.

With a log target (the model predicts log⁡y\log y instead of yy), each coefficient acts on a multiplier. One more unit of xjx_j multiplies the predicted price by ewje^{w_j}, which is a change of (ewj−1)×100(e^{w_j} - 1) \times 100 percent. For small wjw_j, this is close to 100 wj100 \, w_j percent. Example 2 reads a pool premium this way.

A metric turns the errors of a model into one number. Each metric answers a different question, so look at more than one. In the formulas, yiy_i is the true value, y^i\hat{y}_i the prediction, yˉ\bar{y} the mean true value and nn the number of rows.

Metric Formula Unit Reads as
MAE 1n∑i∣yi−y^i∣\frac{1}{n}\sum_{i} \lvert y_i - \hat{y}_i \rvert USD the typical size of an error
MSE 1n∑i(yi−y^i)2\frac{1}{n}\sum_{i} (y_i - \hat{y}_i)^2 USD² the loss that OLS minimizes
RMSE MSE\sqrt{\text{MSE}} USD an error size that weights big misses more
R² 1−∑i(yi−y^i)2∑i(yi−yˉ)21 - \dfrac{\sum_{i} (y_i - \hat{y}_i)^2}{\sum_{i} (y_i - \bar{y})^2} none the share of variance explained; 1 is perfect, 0 is the mean baseline
MAPE 1n∑i∣yi−y^iyi∣\frac{1}{n}\sum_{i} \left\lvert \dfrac{y_i - \hat{y}_i}{y_i} \right\rvert fraction the typical error as a share of the true value

The mean squared error (MSE) is in squared units, which nobody can picture, so you usually report its square root, the root mean squared error (RMSE). The coefficient of determination (R²) compares the model’s squared errors with those of the mean baseline. The mean absolute percentage error (MAPE) divides each error by its true value.

Five houses make the formulas concrete. The last prediction misses by 300,000 USD.

from sklearn.metrics import (
mean_absolute_percentage_error,
mean_squared_error,
r2_score,
root_mean_squared_error,
)
y_true = np.array([350_000, 420_000, 515_000, 610_000, 1_200_000])
y_pred = np.array([370_000, 400_000, 540_000, 580_000, 900_000])
err = y_true - y_pred
mae = np.mean(np.abs(err))
mse = np.mean(err**2)
rmse = np.sqrt(mse)
r2 = 1 - np.sum(err**2) / np.sum((y_true - y_true.mean()) ** 2)
mape = np.mean(np.abs(err / y_true))
print(f"by hand: MAE {mae:,.0f} RMSE {rmse:,.0f} R² {r2:.3f} MAPE {mape:.3f}")
print(f"MSE {mse:,.0f} (USD²)")
checks = [
np.isclose(mae, mean_absolute_error(y_true, y_pred)),
np.isclose(mse, mean_squared_error(y_true, y_pred)),
np.isclose(rmse, root_mean_squared_error(y_true, y_pred)),
np.isclose(r2, r2_score(y_true, y_pred)),
np.isclose(mape, mean_absolute_percentage_error(y_true, y_pred)),
]
print("scikit-learn agrees:", all(checks))
Output
by hand: MAE 79,000 RMSE 135,886 R² 0.799 MAPE 0.090
MSE 18,465,000,000 (USD²)
scikit-learn agrees: True

The one big miss pulls RMSE far above MAE. Four of the five errors are 20,000 to 30,000 USD, but the squared 300,000 dominates the sum. mean_absolute_percentage_error returns a fraction: 0.1 means 10%. Since scikit-learn 1.4, root_mean_squared_error is its own function; the old mean_squared_error(..., squared=False) no longer exists.

Every metric misleads in some situation:

Metric Misleads when Example
MAE Big misses matter more than small ones. It treats one 300k miss like ten 30k misses.
MSE, RMSE A few outliers dominate. One mispriced sale can double the RMSE of a good model.
R² You compare different test sets or targets. R² on log price and R² on price are different numbers; a test set with a wider price range gives a higher R² for the same errors.
MAPE True values are near 0, or you care about money, not ratios. A 10% error on a cheap house and on a mansion count the same; MAPE also rewards predictions that are too low.

Report a metric in the unit that your users care about. An estate agency thinks in USD and in percent, so this module reports MAE, RMSE and MAPE on the price scale, with R² as a unit-free summary.

A metric is one number. A residual plot shows every error, so it reveals patterns that a metric hides. The fitted value of a row is its prediction y^i\hat{y}_i. Three plots answer three questions:

Plot Healthy pattern Warning sign Usual fix
Residuals against fitted values a flat band around 0 a curve add nonlinear features, or use a nonlinear model
a funnel that widens to the right model the log of the target
Histogram of residuals one hump, centered at 0 a long tail on one side check the outliers; consider a log target
Q-Q plot (quantile–quantile plot) the points follow the diagonal line the ends curve away from the line heavy tails: a few very large errors

A funnel means that the spread of the errors changes with the size of the prediction. This is called heteroscedasticity. Its opposite, a constant spread, is homoscedasticity. House prices are a classic case: an error of 50,000 USD is common for a 1.5M house and huge for a 250k house. A Q-Q plot sorts the residuals and plots them against the values that a normal distribution would give at the same ranks. Normal residuals are not required to make point predictions. They matter for classical confidence and prediction intervals (module 29).

House prices are right-skewed: most houses cost 200k to 600k, and a long tail reaches 3.7M. A linear model on the raw price fits the expensive tail badly and makes errors that grow with the price. The log of the price is much closer to symmetric.

print(f"skew of price: {y_train.skew():.2f}")
print(f"skew of log price: {np.log(y_train).skew():.2f}")
Output
skew of price: 2.71
skew of log price: 0.70

Skewness measures asymmetry: 0 is symmetric, and a positive value means a long right tail. A model on the log scale treats the features as multipliers: a pool adds a percentage, not a fixed amount of USD. Example 3 tests whether this suits the house prices better than a model in USD.

To use a log target, fit the model on log⁡y\log y, and then back-transform each prediction with ez^e^{\hat{z}} to get USD again. TransformedTargetRegressor does both steps for you: it applies func to the target before fit and inverse_func to the output of predict. Example 3 uses it.

One subtle effect: the back-transformed prediction estimates the typical (median) price, not the mean price, because the exponential of an average log is below the average of the values. This retransformation bias is small when the residuals on the log scale are small. Example 3 measures it.

Regularization: Ridge, Lasso and ElasticNet

Section titled “Regularization: Ridge, Lasso and ElasticNet”

With many features, few rows or correlated features, OLS weights can become large and unstable. They fit the noise of the training set. Regularization adds a penalty on the size of the weights to the loss, so the model prefers small weights unless a feature really earns a large one. This pull toward 0 is called shrinkage. The strength of the penalty is a hyperparameter called alpha in scikit-learn: alpha=0 is plain OLS, and a large alpha shrinks every weight toward 0.

Model Penalty Loss that scikit-learn minimizes Effect
Ridge L2 penalty: sum of squared weights ∥y−Xw∥22+α∥w∥22\lVert \mathbf{y} - X\mathbf{w} \rVert_2^2 + \alpha \lVert \mathbf{w} \rVert_2^2 shrinks all weights smoothly; none becomes exactly 0
Lasso L1 penalty: sum of absolute weights 12n∥y−Xw∥22+α∥w∥1\frac{1}{2n}\lVert \mathbf{y} - X\mathbf{w} \rVert_2^2 + \alpha \lVert \mathbf{w} \rVert_1 sets some weights to exactly 0: it selects features
ElasticNet a mix of L1 and L2 12n∥y−Xw∥22+αρ∥w∥1+α(1−ρ)2∥w∥22\frac{1}{2n}\lVert \mathbf{y} - X\mathbf{w} \rVert_2^2 + \alpha\rho \lVert \mathbf{w} \rVert_1 + \frac{\alpha(1-\rho)}{2} \lVert \mathbf{w} \rVert_2^2 l1_ratio =ρ=\rho sets the mix; keeps groups of correlated features together

Ridge regression uses the L2 penalty. Lasso regression (least absolute shrinkage and selection operator) uses the L1 penalty. ElasticNet combines them. The intercept is never penalized. Notice the 12n\frac{1}{2n} in the Lasso and ElasticNet losses: the same alpha value is much stronger in Lasso than in Ridge, so never copy an alpha from one to the other.

Standardize first. The penalty treats every weight the same. A feature measured in square feet needs a tiny weight, and the same feature in thousands of square feet needs a weight 1,000 times larger. Without scaling, the penalty depends on the units you happened to choose. Put a StandardScaler before the model in the pipeline, so every feature has mean 0 and standard deviation 1.

To choose alpha, try several values with cross-validation on the training set. RidgeCV(alphas=...) and LassoCV(cv=5) do this in one fit and store the winner in alpha_. Example 5 uses both.

Polynomial regression, underfitting and overfitting

Section titled “Polynomial regression, underfitting and overfitting”

A straight line cannot follow a curve. Polynomial regression adds powers of the features (x2x^2, x3x^3, …) and their products as new columns, then fits an ordinary linear regression on them. The model is still linear in its weights, so OLS solves it, but its prediction can bend. PolynomialFeatures (module 33) builds the columns:

from sklearn.preprocessing import PolynomialFeatures
poly = PolynomialFeatures(degree=2, include_bias=False)
demo = pd.DataFrame({"sqft": [1_000, 2_000], "condition": [3, 4]})
print(poly.fit_transform(demo))
print(poly.get_feature_names_out())
Output
[[ 1000. 3. 1000000. 3000. 9.]
[ 2000. 4. 4000000. 8000. 16.]]
['sqft' 'condition' 'sqft^2' 'sqft condition' 'condition^2']

The degree is the highest power. It controls how flexible the model is:

  • Underfitting: the model is too simple to capture the pattern. The error is high on the training set and on the test set.
  • Overfitting: the model is so flexible that it learns the noise of the training rows. The training error is low, but the test error is much higher.
flowchart LR
    U["Degree too low<br/>underfit<br/>train error high"] --> G["Degree right<br/>train ≈ test<br/>both low"]
    G --> O["Degree too high<br/>overfit<br/>train low, test high"]

The gap between the training error and the test error is the warning light. Every flexible model has a setting like the degree: k in KNN, the depth of a tree, the number of boosting rounds. Example 6 shows the full curve. Module 37 studies it as the bias–variance trade-off.

A k-nearest neighbors (KNN) regressor stores the training rows. To predict a new house, it finds the kk most similar training houses (by Euclidean distance on the features) and averages their prices:

y^=1k∑i∈Nk(x)yi\hat{y} = \frac{1}{k} \sum_{i \in N_k(\mathbf{x})} y_i

Nk(x)N_k(\mathbf{x}) is the set of the kk nearest neighbors of x\mathbf{x}. This is what an estate agent does with “comparables”. The method has no coefficients and makes no straight-line assumption. Two settings matter:

  • Scaling. Distances add up the feature differences. Unscaled, 500 sqft of difference swamps 3 points of condition. Always scale before KNN.
  • k. With k=1, the model copies one neighbor and overfits. A large k averages over houses that are not similar and underfits.

KNN predicts slowly on big data, because each prediction searches the training set. It cannot extrapolate (predict outside the range of the training targets): the prediction is always an average of known prices.

A decision tree asks a sequence of yes/no questions about the features, such as “is sqft ≤ 2,535?”. Each question is a split. The rows that reach the same final box (a leaf) get the same prediction: the mean training target of that leaf. To choose a split, the tree tries every feature and threshold and keeps the one that lowers the squared error the most. Then it repeats the search inside each half.

A tree with one split (a stump) shows the idea:

from sklearn.tree import DecisionTreeRegressor, export_text
stump = DecisionTreeRegressor(max_depth=1, random_state=42)
stump.fit(X_train[["sqft"]], y_train)
print(export_text(stump, feature_names=["sqft"], decimals=0))
Output
|--- sqft <= 2535
| |--- value: [393486]
|--- sqft > 2535
| |--- value: [926351]

Small houses get one price and large houses another. A deeper tree splits each half again, so its predictions form a staircase. The max_depth hyperparameter limits the number of questions on any path. A shallow tree underfits. A tree with no depth limit grows until each leaf holds a single house, and it overfits badly. Other limits such as min_samples_leaf stop splits that would leave too few rows in a leaf.

Trees need no scaling, because a split compares one feature with a threshold. They capture interactions on their own: a split on neighborhood followed by a split on size gives each neighborhood its own size effect.

One deep tree is unstable: change a few training rows and the tree changes. A random forest grows many deep trees and averages their predictions. Each tree trains on a bootstrap sample (rows drawn at random with replacement), so each tree sees a slightly different data set. A forest can also let each split consider only a random subset of the features, which makes the trees even more different. The trees make different mistakes, and averaging cancels much of their noise. This general idea, training many models on resampled data and averaging them, is called bagging (bootstrap aggregating). A model built from several models is an ensemble.

flowchart LR
    D["Training set"] --> B1["Bootstrap sample 1"] --> T1["Tree 1"]
    D --> B2["Bootstrap sample 2"] --> T2["Tree 2"]
    D --> B3["Bootstrap sample …"] --> T3["Tree …"]
    T1 --> A["Average of<br/>the predictions"]
    T2 --> A
    T3 --> A

Key settings of RandomForestRegressor: n_estimators (the number of trees; more is better but slower), max_features (the share of features tried at each split; the regressor’s default 1.0 tries all of them, so only the bootstrap samples differ, and values such as 0.5 add the feature randomness) and min_samples_leaf. A forest rarely overfits badly as trees are added, and it works well with default settings. Module 38 covers ensembles in depth.

Gradient boosting also combines many trees, but it builds them one after another. It starts from a constant prediction (the mean). Each new small tree is fitted to the residuals of the current model, and its prediction is added with a small weight, the learning rate η\eta:

Fm(x)=Fm−1(x)+η hm(x)F_m(\mathbf{x}) = F_{m-1}(\mathbf{x}) + \eta \, h_m(\mathbf{x})

FmF_m is the model after mm trees and hmh_m is the mm-th tree. Each tree alone is a weak learner: a model only a little better than guessing. Together, they correct each other step by step. A smaller learning rate needs more trees but usually generalizes better. Exercise M35-X03 writes this loop from scratch.

scikit-learn’s HistGradientBoostingRegressor is the fast implementation. It first sorts each feature into at most 255 bins (a histogram), so finding a split is cheap even on large data. It handles missing values natively, and it handles categorical columns natively when they have the pandas category dtype. Key settings: max_iter (the number of trees, 100 by default), learning_rate (0.1), max_leaf_nodes (31) and early stopping, which is on automatically when the training set has more than 10,000 rows.

Model Scale features? Missing values Key hyperparameters Strengths Weaknesses
LinearRegression no (yes to compare coefficients) impute none fast, readable coefficients straight lines only
Ridge, Lasso, ElasticNet yes impute alpha, l1_ratio stable with correlated or many features; Lasso selects straight lines only
PolynomialFeatures + linear yes impute degree smooth curves columns explode with degree; wild at the edges
KNeighborsRegressor yes impute n_neighbors, weights no assumptions about shape slow predictions; no extrapolation; weak with many features
DecisionTreeRegressor no native since scikit-learn 1.3 max_depth, min_samples_leaf readable rules; interactions unstable; staircase predictions
RandomForestRegressor no native since 1.4 n_estimators, max_features strong default; hard to overfit large models; slow on big data
HistGradientBoostingRegressor no native learning_rate, max_iter, max_leaf_nodes usually the most accurate on tables; native categories more settings to tune; less readable

Start with the baseline and a linear model. They are fast, and they tell you how much a complex model must beat. Then try a gradient boosting model. Example 7 builds the full comparison.

Example 1 — Fit a linear regression from scratch and match scikit-learn

Section titled “Example 1 — Fit a linear regression from scratch and match scikit-learn”

Goal: An estate agency wants a price model that it can explain line by line. Fit the linear model on every feature with lstsq, and prove that scikit-learn’s LinearRegression finds exactly the same weights.

Step 1 — Build the feature matrix with the preprocessor

Section titled “Step 1 — Build the feature matrix with the preprocessor”
pre = make_preprocessor()
A_train = pre.fit_transform(X_train)
A_test = pre.transform(X_test)
print(A_train.shape, A_test.shape)
print(pre.get_feature_names_out()[:3])
Output
(2250, 17) (750, 17)
['neighborhood_Downtown' 'neighborhood_Lakeview'
'neighborhood_Maple Grove']

The preprocessor learns the medians, means and standard deviations from the training rows (fit_transform) and reuses them on the test rows (transform). Seven neighborhood columns plus ten numeric columns give 17 features.

Step 2 — Solve the least-squares problem

Section titled “Step 2 — Solve the least-squares problem”
A1 = np.column_stack([np.ones(len(A_train)), A_train])
w, residual_ss, rank, _ = np.linalg.lstsq(A1, y_train.to_numpy())
intercept, weights = w[0], w[1:]
print("rank:", rank, "of", A1.shape[1], "columns")
print(f"intercept: {intercept:,.0f}")
print(weights[:3].round(0))
Output
rank: 18 of 18 columns
intercept: 327,946
[191388. 370772. 46761.]

The column of ones carries the intercept. The rank equals the number of columns, so no column is a combination of the others and the weights are unique. That is the reason for drop="first".

Step 3 — Fit LinearRegression on the same matrix

Section titled “Step 3 — Fit LinearRegression on the same matrix”
ols = LinearRegression().fit(A_train, y_train)
print(f"intercept: {ols.intercept_:,.0f}")
print(ols.coef_[:3].round(0))
print("same weights:", np.allclose(ols.coef_, weights))
Output
intercept: 327,946
[191388. 370772. 46761.]
same weights: True

scikit-learn learns the same intercept and weights. It stores them in intercept_ and coef_. The trailing underscore marks an attribute learned by fit (module 34).

Step 4 — Predict the test houses with both

Section titled “Step 4 — Predict the test houses with both”
pred_scratch = intercept + A_test @ weights
pred_pipeline = linear.predict(X_test)
print(f"from scratch R²: {r2_score(y_test, pred_scratch):.3f}")
print(f"pipeline R²: {r2_score(y_test, pred_pipeline):.3f}")
print("same predictions:", np.allclose(pred_scratch, pred_pipeline))
Output
from scratch R²: 0.792
pipeline R²: 0.792
same predictions: True

A prediction is one matrix–vector product plus the intercept. The pipeline linear from the Concepts section does the same work in one call, and it applies the preprocessing for you.

Common mistakes:

  • Fitting the preprocessor on all 3,000 houses before the split. The test medians and means leak into the training data. Fit it on X_train only, or let a pipeline do it.
  • Keeping all eight neighborhood columns and the intercept. The design matrix then has 19 columns but rank 18, and the weights are no longer unique (the predictions still are).
  • Forgetting the column of ones. The line is then forced through 0, and every weight is distorted.

Example 2 — Read the coefficients of a log-price model

Section titled “Example 2 — Read the coefficients of a log-price model”

Goal: The agency asks: “What is a pool worth? How much does one level of condition add?” Fit the model on log price with unscaled features, and read each coefficient as a percent change.

Step 1 — Fit on log price with raw units

Section titled “Step 1 — Fit on log price with raw units”
log_linear = make_pipeline(make_preprocessor(scale=False), LinearRegression())
log_linear.fit(X_train, np.log(y_train))
names = log_linear[0].get_feature_names_out()
coefs = pd.Series(log_linear[-1].coef_, index=names)
effects = pd.DataFrame({"coef": coefs, "pct_change": (np.exp(coefs) - 1) * 100})
print(effects.loc[num_cols].to_string(float_format=lambda v: f"{v:.4f}"))
Output
coef pct_change
sqft 0.0004 0.0357
bedrooms -0.0057 -0.5732
bathrooms 0.0469 4.8059
year_built 0.0025 0.2514
lot_sqft 0.0000 0.0005
garage_spaces 0.0325 3.3079
has_pool 0.0789 8.2114
condition 0.1172 12.4339
distance_to_center_km -0.0078 -0.7740
school_rating 0.0362 3.6830

Without scaling, each coefficient is “change in log price per unit”. pct_change converts it with (ew−1)×100(e^{w} - 1) \times 100. A pool goes with about +8% on the price, holding the other features fixed.

Step 2 — Convert small units into useful ones

Section titled “Step 2 — Convert small units into useful ones”
for feature, step in [("sqft", 100), ("distance_to_center_km", 5), ("year_built", 10)]:
pct = (np.exp(coefs[feature] * step) - 1) * 100
print(f"{feature:22} +{step:<4} → {pct:+.1f}% on price")
Output
sqft +100 → +3.6% on price
distance_to_center_km +5 → -3.8% on price
year_built +10 → +2.5% on price

One square foot is too small to think about. Multiply the coefficient by a meaningful step before you take the exponential. 100 more square feet go with a few percent more on the price; 5 km farther from the center go with a few percent less.

Step 3 — Read the neighborhoods against the reference

Section titled “Step 3 — Read the neighborhoods against the reference”
reference = log_linear[0].named_transformers_["cat"].categories_[0][0]
print("reference neighborhood:", reference)
hood_effects = effects.filter(like="neighborhood_", axis=0)["pct_change"]
print(hood_effects.sort_values().round(1))
Output
reference neighborhood: Cedar Park
neighborhood_Westfield 7.4
neighborhood_Maple Grove 29.5
neighborhood_Downtown 55.5
neighborhood_Riverside 60.5
neighborhood_Old Town 77.6
neighborhood_Oak Hill 84.2
neighborhood_Lakeview 108.1
Name: pct_change, dtype: float64

Every neighborhood is compared with Cedar Park, the dropped first category. A Lakeview house is predicted at about twice the price of a similar Cedar Park house. Change the reference, and every number in this list changes, but the predictions do not.

print(X_train[["sqft", "bedrooms", "bathrooms"]].corr().round(2))
print(f"bedrooms: {effects.loc['bedrooms', 'pct_change']:+.2f}% per bedroom")
Output
sqft bedrooms bathrooms
sqft 1.00 0.86 0.85
bedrooms 0.86 1.00 0.90
bathrooms 0.85 0.90 1.00
bedrooms: -0.57% per bedroom

Bedrooms are strongly correlated with size. At a fixed sqft, one more bedroom means smaller rooms, so the coefficient is close to zero or negative. On its own, a bedroom count still goes with higher prices, because big houses have more bedrooms. A coefficient is always “holding the others fixed”.

Common mistakes:

  • Reading 0.0004 for sqft as “size does not matter”. The unit is one square foot. Scale the step first.
  • Reading a log coefficient of 0.73 as +73%. For larger coefficients, use ew−1e^{w} - 1: 0.73 is about +108%.
  • Saying “a pool causes +8%”. The data shows an association. Houses with pools can differ in ways the model does not see.

Example 3 — Predict log price and back-transform

Section titled “Example 3 — Predict log price and back-transform”

Goal: The agency needs prices in USD. Fit the full linear model on log price, back-transform its predictions automatically, choose between the price and log-price targets with cross-validation, and then report both on the test set.

Step 1 — Wrap the pipeline in TransformedTargetRegressor

Section titled “Step 1 — Wrap the pipeline in TransformedTargetRegressor”
from sklearn.compose import TransformedTargetRegressor
log_model = TransformedTargetRegressor(
regressor=make_pipeline(make_preprocessor(), LinearRegression()),
func=np.log,
inverse_func=np.exp,
)
log_model.fit(X_train, y_train)
print(log_model.predict(X_test.head(3)).round(-2))
print(y_test.head(3).to_numpy())
Output
[367900. 202100. 871900.]
[381500 214500 981000]

You pass the raw prices to fit. The wrapper takes the log, fits the inner pipeline on it and applies np.exp inside predict. Every prediction comes out in USD, so every metric works as usual.

Step 2 — Write one function for all the metrics

Section titled “Step 2 — Write one function for all the metrics”
def regression_report(y_true, y_pred) -> dict[str, float]:
"""MAE, RMSE, R² and MAPE of one set of predictions."""
return {
"MAE": mean_absolute_error(y_true, y_pred),
"RMSE": root_mean_squared_error(y_true, y_pred),
"R2": r2_score(y_true, y_pred),
"MAPE": mean_absolute_percentage_error(y_true, y_pred),
}
print({k: round(v, 3) for k, v in regression_report(y_test, baseline_pred).items()})
Output
{'MAE': 215798.949, 'RMSE': 323250.383, 'R2': -0.001, 'MAPE': 0.511}

One function keeps every comparison consistent. The baseline row confirms the meaning of R²: predicting the mean gives an R² of about 0 (slightly below, because the training mean is not the test mean).

Step 3 — Compare the two targets with cross-validation

Section titled “Step 3 — Compare the two targets with cross-validation”
from sklearn.model_selection import KFold, cross_val_score
cv = KFold(n_splits=5, shuffle=True, random_state=42)
for name, model in [("price target", linear), ("log target", log_model)]:
rmse_cv = -cross_val_score(
model, X_train, y_train, cv=cv, scoring="neg_root_mean_squared_error"
)
r2_cv = cross_val_score(model, X_train, y_train, cv=cv, scoring="r2")
print(f"{name}: CV RMSE {rmse_cv.mean():,.0f}, CV R² {r2_cv.mean():.3f}")
Output
price target: CV RMSE 146,717, CV R² 0.784
log target: CV RMSE 107,252, CV R² 0.884

The decision uses only the training set. cross_val_score clones each model and refits it on 4 folds at a time, so the preprocessor and the log transform are refitted inside every fold. The scorers see back-transformed predictions, so both models are scored in USD. The log target wins clearly on both CV scores, so the agency adopts it.

Step 4 — Report both models on the test set

Section titled “Step 4 — Report both models on the test set”
reports = pd.DataFrame(
{
"price target": regression_report(y_test, linear.predict(X_test)),
"log target": regression_report(y_test, log_model.predict(X_test)),
}
).T
print(reports.round({"MAE": 0, "RMSE": 0, "R2": 3, "MAPE": 3}))
Output
MAE RMSE R2 MAPE
price target 98861.0 147324.0 0.792 0.237
log target 65262.0 102961.0 0.898 0.135

The test set confirms the cross-validated choice: the MAE drops by about a third and R² rises from 0.79 to 0.90. On these houses, the multiplicative model fits much better. R² is measured on the price scale for both models, so the comparison is fair. This test table is a report, made once, not the basis of the decision.

Step 5 — Measure the retransformation bias

Section titled “Step 5 — Measure the retransformation bias”
pred_log = log_model.predict(X_test)
print(f"mean actual price: {y_test.mean():,.0f}")
print(f"mean predicted price: {pred_log.mean():,.0f}")
print(f"median residual: {np.median(y_test - pred_log):,.0f}")
Output
mean actual price: 483,838
mean predicted price: 472,366
median residual: 5,683

The back-transformed predictions run a little below the actual prices on average, as the concept section predicted. The bias is small next to the MAE, so you can ignore it here. When totals matter (for example the summed value of a portfolio of houses), multiply the predictions by a correction factor measured on the training residuals.

Common mistakes:

  • Computing R² of the log model on the log scale and comparing it with R² of the price model on the price scale. Back-transform first, then score both on the same scale.
  • Taking np.log of a target that can be 0. Use np.log1p with np.expm1 as the inverse.
  • Logging the target by hand for fit and forgetting np.exp after predict. The “prices” are then about 13, and every metric is nonsense. TransformedTargetRegressor makes this mistake impossible.

Example 4 — Diagnose the models with residual plots

Section titled “Example 4 — Diagnose the models with residual plots”

Goal: Before the agency trusts the log model, check where it fails. Plot the residuals of both linear models and inspect the worst predictions.

pred_price = linear.predict(X_test)
resid_price = y_test - pred_price
resid_log = np.log(y_test) - np.log(pred_log)
print(f"price residuals: mean {resid_price.mean():,.0f}, sd {resid_price.std():,.0f}")
print(f"log residuals: mean {resid_log.mean():.3f}, sd {resid_log.std():.3f}")
Output
price residuals: mean 2,420, sd 147,402
log residuals: mean 0.005, sd 0.172

The price-model residuals are in USD. The log-model residuals are on the log scale, where 0.10 means “about 10% too low”. Both means are near 0, so neither model is biased overall. The plots show what the means hide.

Step 2 — Plot residuals against fitted values

Section titled “Step 2 — Plot residuals against fitted values”
fig, axes = plt.subplots(1, 2, figsize=(10, 4))
axes[0].scatter(pred_price / 1e6, resid_price / 1e6, s=8, alpha=0.5)
axes[0].set(title="Price target", xlabel="Fitted (M USD)", ylabel="Residual (M USD)")
axes[1].scatter(np.log(pred_log), resid_log, s=8, alpha=0.5, color="tab:orange")
axes[1].set(title="Log target", xlabel="Fitted log price", ylabel="Residual (log)")
for ax in axes:
ax.axhline(0, color="black", linewidth=1)
fig.tight_layout()
plt.show()
Left: residuals of the price model form a U-shaped curve that also widens to the right; some fitted prices are below zero and the largest residual is above 1.2 million USD. Right: residuals of the log model form an even band around zero with a few isolated points far from it.
Residuals against fitted values for the price model (left) and the log-price model (right), test set.

The left panel shows both warning signs. It curves: the model overprices mid-range houses and badly underprices the most expensive ones. It is also a funnel: the errors grow with the price. A few fitted prices are even below 0 USD, which no house costs. The right panel is a flat band of roughly constant width. A handful of points sit far from the band; Step 4 looks at them.

Step 3 — Check the residual distribution

Section titled “Step 3 — Check the residual distribution”
from scipy import stats
fig, axes = plt.subplots(1, 2, figsize=(10, 4))
axes[0].hist(resid_log, bins=40, color="tab:orange")
axes[0].set(title="Log-model residuals", xlabel="Residual (log)", ylabel="Houses")
stats.probplot(resid_log, dist="norm", plot=axes[1])
axes[1].set_title("Q-Q plot against a normal distribution")
fig.tight_layout()
plt.show()
Left: the histogram of log residuals is a single symmetric hump centered at zero, with a few isolated bars far out on both sides. Right: in the Q-Q plot the points follow the diagonal line closely except for a few points at both ends that move away from it.
Distribution of the log-model residuals on the test set: histogram and normal Q-Q plot.

scipy.stats.probplot draws the Q-Q plot: the sorted residuals against normal quantiles, with a reference line. The middle follows the line closely, so the typical errors are close to normal. The few points far off at both ends are heavy tails: single houses with very large errors.

cols = ["house_id", "neighborhood", "sqft", "year_built", "price"]
check = houses.loc[X_test.index, cols]
check["predicted"] = pred_log.round(-2)
check["log_resid"] = resid_log
worst = check.reindex(check["log_resid"].abs().sort_values(ascending=False).index)
print(worst.head(5).to_string(index=False))
known_bad = ["H0537", "H0542", "H0751", "H0914", "H2277", "H0887", "H0957", "H1990"]
print("known bad sales in the test set:", check["house_id"].isin(known_bad).sum())
Output
house_id neighborhood sqft year_built price predicted log_resid
H0180 Old Town 1860 1957 219500 499800.0 -0.823
H0297 Old Town 2710 1957 356500 674300.0 -0.637
H1585 Lakeview 2470 2022 1814500 969700.0 0.627
H0013 Old Town 2130 1955 256000 463400.0 -0.593
H0457 Cedar Park 3860 1993 280000 506300.0 -0.592
known bad sales in the test set: 0

The worst errors are not random, and each one suggests a hypothesis to test. Three of the five are Old Town houses from the 1950s, all priced far too high. That suggests a curved age effect, which a single straight-line year_built coefficient cannot draw; exercise M35-C08 tests it with cross-validation. The big Cedar Park house is overpriced and the big new Lakeview house is underpriced. That suggests that a square foot is worth a different percentage in different neighborhoods, while this model gives every neighborhood the same size effect. Curves and interactions like these are what tree models can learn on their own, which Example 7 puts to the test.

Residual analysis also finds data errors, fraud and bargains. The data dictionary lists eight sales with injected price errors (known_bad). The last line shows that none of them is in the test set: all eight landed in the training set of this split, so the test residuals cannot show them. The mini-project finds them with out-of-fold residuals. Never delete test rows with big residuals to improve a score. Investigate them, and change the training data only for a documented reason.

Common mistakes:

  • Plotting residuals against the true values instead of the fitted values. That plot shows a slope for any model with errors, even a well-specified one, because the residual is part of the true value.
  • Judging the Q-Q plot by its ends only. A few points always stray; look at whether the bulk of the points follows the line.
  • Reading a flat band as proof that the model is good. It only means the errors have no pattern that a linear model could fix; the error size still needs a metric.

Example 5 — Shrink coefficients with Ridge, Lasso and ElasticNet

Section titled “Example 5 — Shrink coefficients with Ridge, Lasso and ElasticNet”

Goal: A clinic predicts diabetes progression one year ahead from ten baseline measurements of 442 patients. With few rows and correlated blood measurements, find out which features matter and how much regularization helps.

Step 1 — Load the diabetes data and split it once

Section titled “Step 1 — Load the diabetes data and split it once”
from sklearn.datasets import load_diabetes
diabetes = load_diabetes(as_frame=True, scaled=False)
Xd, yd = diabetes.data, diabetes.target
Xd_train, Xd_test, yd_train, yd_test = train_test_split(
Xd, yd, test_size=0.25, random_state=42
)
print(Xd.shape, list(Xd.columns))
print(Xd[["s1", "s2"]].corr().round(2).iloc[0, 1], "= correlation of s1 and s2")
Output
(442, 10) ['age', 'sex', 'bmi', 'bp', 's1', 's2', 's3', 's4', 's5', 's6']
0.9 = correlation of s1 and s2

load_diabetes is bundled with scikit-learn, so it works offline. scaled=False returns the raw units (age in years, BMI, blood pressure, six blood serum measurements s1–s6). s1 (total cholesterol) and s2 (LDL cholesterol) are strongly correlated, which is what makes OLS coefficients unstable.

Step 2 — Compare the coefficients of four models

Section titled “Step 2 — Compare the coefficients of four models”
from sklearn.linear_model import ElasticNet, Lasso, Ridge
models = {
"OLS": LinearRegression(),
"Ridge a=10": Ridge(alpha=10),
"Lasso a=1": Lasso(alpha=1),
"ENet a=1": ElasticNet(alpha=1, l1_ratio=0.5),
}
coef_table, test_r2 = {}, {}
for name, model in models.items():
pipe = make_pipeline(StandardScaler(), model).fit(Xd_train, yd_train)
coef_table[name] = pipe[-1].coef_
test_r2[name] = pipe.score(Xd_test, yd_test)
print(pd.DataFrame(coef_table, index=Xd.columns).round(1))
print("test R²:", {k: round(v, 3) for k, v in test_r2.items()})
Output
OLS Ridge a=10 Lasso a=1 ENet a=1
age 2.2 2.4 1.2 2.2
sex -11.5 -11.0 -9.3 -5.8
bmi 25.1 25.1 25.7 18.6
bp 18.2 17.6 17.0 12.8
s1 -44.1 -13.1 -8.4 -1.7
s2 24.5 0.5 -0.0 -2.8
s3 5.5 -7.8 -10.8 -9.2
s4 13.0 8.5 3.3 6.0
s5 33.4 21.2 21.1 13.7
s6 1.2 1.9 1.1 4.3
test R²: {'OLS': 0.485, 'Ridge a=10': 0.488, 'Lasso a=1': 0.496, 'ENet a=1': 0.483}

The features are standardized, so each coefficient is “points of progression per standard deviation”. OLS gives s1 and s2 large opposite weights that mostly cancel. Ridge pulls both toward 0, so they no longer fight. Lasso sets s2 to exactly 0 (-0.0 is a zero with a sign bit; it is still 0). ElasticNet shrinks every coefficient, some strongly, but keeps all ten. The test R² values are close: on this data, regularization mainly makes the model simpler and steadier, not more accurate.

Step 3 — Watch Lasso remove features as alpha grows

Section titled “Step 3 — Watch Lasso remove features as alpha grows”
for alpha in [0.1, 1, 3, 10, 30]:
lasso = make_pipeline(StandardScaler(), Lasso(alpha=alpha)).fit(Xd_train, yd_train)
kept = Xd.columns[lasso[-1].coef_ != 0].tolist()
r2_a = lasso.score(Xd_test, yd_test)
print(f"alpha {alpha:>4}: R² {r2_a:.3f}, {len(kept)} kept {kept}")
Output
alpha 0.1: R² 0.487, 9 kept ['age', 'sex', 'bmi', 'bp', 's1', 's2', 's4', 's5', 's6']
alpha 1: R² 0.496, 9 kept ['age', 'sex', 'bmi', 'bp', 's1', 's3', 's4', 's5', 's6']
alpha 3: R² 0.501, 6 kept ['sex', 'bmi', 'bp', 's1', 's3', 's5']
alpha 10: R² 0.478, 4 kept ['bmi', 'bp', 's3', 's5']
alpha 30: R² 0.248, 2 kept ['bmi', 's5']

A larger alpha removes more features. Around alpha=10, four features remain: BMI, blood pressure, s3 and s5. The test R² barely moves until the penalty starts to remove useful features. This is embedded feature selection (module 33): the model selects features while it trains.

alphas = np.logspace(-1, 1.7, 40)
path = [
make_pipeline(StandardScaler(), Lasso(alpha=a)).fit(Xd_train, yd_train)[-1].coef_
for a in alphas
]
fig, ax = plt.subplots(figsize=(8, 4.5))
ax.plot(alphas, path)
ax.set_xscale("log")
ax.axhline(0, color="black", linewidth=0.8)
ax.set(xlabel="alpha (log scale)", ylabel="Coefficient", title="Lasso coefficient path")
ax.legend(Xd.columns, ncols=2, fontsize=8)
plt.show()
Ten coefficient lines start apart at small alpha and move toward zero as alpha grows. Most lines reach exactly zero one after another; bmi and s5 stay away from zero longest.
Lasso coefficients of the ten diabetes features as alpha grows from 0.1 to 50.

Each line is one feature. As alpha grows, the lines hit 0 one after another and stay there. The features that survive longest are the strongest predictors.

Step 4 — Let RidgeCV and LassoCV choose alpha

Section titled “Step 4 — Let RidgeCV and LassoCV choose alpha”
from sklearn.linear_model import LassoCV, RidgeCV
ridge_cv = make_pipeline(StandardScaler(), RidgeCV(alphas=np.logspace(-2, 3, 11)))
ridge_cv.fit(Xd_train, yd_train)
lasso_cv = make_pipeline(StandardScaler(), LassoCV(cv=5, random_state=42))
lasso_cv.fit(Xd_train, yd_train)
for name, pipe in [("RidgeCV", ridge_cv), ("LassoCV", lasso_cv)]:
score = pipe.score(Xd_test, yd_test)
print(f"{name} alpha {pipe[-1].alpha_:.3f}, test R² {score:.3f}")
print("LassoCV keeps", int((lasso_cv[-1].coef_ != 0).sum()), "of 10 features")
Output
RidgeCV alpha 1.000, test R² 0.486
LassoCV alpha 0.106, test R² 0.487
LassoCV keeps 9 of 10 features

Both estimators try every alpha with cross-validation on the training set and refit with the winner. RidgeCV uses an efficient leave-one-out method by default; LassoCV builds its own grid of 100 alphas and uses 5 folds here. The test set is touched once, at the end.

Common mistakes:

  • Regularizing unscaled features. With raw units, Lasso(alpha=5) drops s5, one of the strongest predictors, only because its values span a few units while cholesterol spans hundreds (exercise M35-C06 shows it).
  • Choosing alpha by test-set score. The test score is then optimistic. Use RidgeCV, LassoCV or cross-validation on the training set.
  • Reading a Lasso zero as “this feature is useless”. With correlated features, Lasso keeps one of them and drops the others almost at random.

Goal: A small agency has only 40 sales. Price depends on the distance to the center in a curved way. Find the polynomial degree that fits the curve without fitting the noise.

small = X_train[["distance_to_center_km"]].iloc[:40]
small_y = np.log(y_train.iloc[:40])
test_x = X_test[["distance_to_center_km"]]
test_y = np.log(y_test)
print(small.shape, f"distances {small.min().iloc[0]}–{small.max().iloc[0]} km")
Output
(40, 1) distances 0.2–18.7 km

The first 40 training rows are a random sample, because train_test_split shuffled the data. The target is log price, and the full test set measures how well each curve generalizes.

def poly_model(degree: int):
return make_pipeline(
StandardScaler(), PolynomialFeatures(degree), LinearRegression()
)
rows = []
for degree in [1, 2, 3, 5, 10, 15]:
model = poly_model(degree).fit(small, small_y)
rows.append(
{
"degree": degree,
"train_rmse": root_mean_squared_error(small_y, model.predict(small)),
"test_rmse": root_mean_squared_error(test_y, model.predict(test_x)),
}
)
print(pd.DataFrame(rows).round(3).to_string(index=False))
Output
degree train_rmse test_rmse
1 0.503 0.539
2 0.445 0.445
3 0.344 0.457
5 0.305 0.415
10 0.286 0.556
15 0.275 17.139

The training error falls as the degree rises, because every extra power gives the curve more freedom. The test error first falls (degree 1 underfits) and then explodes (degree 15 overfits). The scaler comes first because x15x^{15} of raw distances would be enormous and numerically fragile.

grid = pd.DataFrame({"distance_to_center_km": np.linspace(0.2, 20.2, 300)})
fig, ax = plt.subplots(figsize=(8, 4.5))
ax.scatter(small, small_y, color="black", s=15, label="40 training houses")
for degree, color in [(1, "tab:blue"), (3, "tab:green"), (15, "tab:red")]:
curve = poly_model(degree).fit(small, small_y).predict(grid)
ax.plot(grid, curve, color=color, label=f"degree {degree}")
ax.set_ylim(11.5, 14.5)
ax.set(xlabel="Distance to center (km)", ylabel="Log price")
ax.legend()
plt.show()
Forty black training points with three fitted curves. The degree 1 line slopes gently and misses the curve. The degree 3 curve follows the broad shape smoothly. The degree 15 curve wiggles through the points and shoots off the chart between and beyond them.
Polynomial fits of degree 1, 3 and 15 to log price against distance, on 40 training houses.

The straight line misses the shape. The cubic follows it. The degree-15 curve passes close to every training point and swings wildly between them and beyond the last one. Those swings are what the test set punishes.

Step 4 — Choose the degree with cross-validation

Section titled “Step 4 — Choose the degree with cross-validation”
for degree in [1, 2, 3, 5]: # cv: 5 shuffled folds from Example 3
scores = cross_val_score(
poly_model(degree), small, small_y, cv=cv, scoring="neg_root_mean_squared_error"
)
print(f"degree {degree}: CV RMSE {-scores.mean():.3f}")
Output
degree 1: CV RMSE 0.499
degree 2: CV RMSE 0.526
degree 3: CV RMSE 0.374
degree 5: CV RMSE 0.403

Cross-validation picks degree 3, the smooth curve in the plot. Choosing the degree from the test errors in Step 2 would leak test information into the choice. Cross-validation (module 34) estimates the test error from the training sample alone. With only 40 rows, each fold has 8 houses, so the CV scores are noisy: degree 2 scores worse than degree 1 here, although it did better on the test set. scikit-learn scorers follow “higher is better”, so RMSE comes as a negative number; flip the sign to read it.

Common mistakes:

  • Picking the degree with the lowest training error. That is always the highest degree.
  • Forgetting the scaler before high-degree features. Large powers lose precision and give unstable fits.
  • Adding PolynomialFeatures(3) to all 17 house features. It creates over 1,000 columns. Add powers only to the features that need them, or use a tree model.

Example 7 — Compare KNN, trees, forests and boosting

Section titled “Example 7 — Compare KNN, trees, forests and boosting”

Goal: Decide which model the agency should use. Tune the key setting of KNN and of a decision tree with cross-validation, fit a random forest and gradient boosting, choose the winner by cross-validated error, and report every model once on the test set.

Step 1 — Pick k for KNN with cross-validation

Section titled “Step 1 — Pick k for KNN with cross-validation”
from sklearn.neighbors import KNeighborsRegressor
for k in [1, 5, 10, 20, 50]:
knn = make_pipeline(make_preprocessor(), KNeighborsRegressor(n_neighbors=k))
scores = cross_val_score(
knn, X_train, y_train, cv=cv, scoring="neg_root_mean_squared_error"
)
print(f"k={k:>2}: CV RMSE {-scores.mean():,.0f}")
Output
k= 1: CV RMSE 158,800
k= 5: CV RMSE 127,042
k=10: CV RMSE 128,955
k=20: CV RMSE 135,272
k=50: CV RMSE 150,505

The same cv object (5 shuffled folds) from Example 3 is reused. k=5 has the lowest CV error. k=1 overfits: each prediction copies one house, noise included. A very large k averages over houses that are not alike. The preprocessor scales the features inside each fold, so the distances are fair and nothing leaks.

Step 2 — Watch a tree overfit as it grows deeper

Section titled “Step 2 — Watch a tree overfit as it grows deeper”
from sklearn.model_selection import cross_validate
depths = range(1, 16)
train_rmse, cv_rmse = [], []
for depth in depths:
tree = make_pipeline(
make_preprocessor(scale=False),
DecisionTreeRegressor(max_depth=depth, random_state=42),
)
res = cross_validate(
tree, X_train, y_train, cv=cv,
scoring="neg_root_mean_squared_error", return_train_score=True,
)
train_rmse.append(-res["train_score"].mean())
cv_rmse.append(-res["test_score"].mean())
best_depth = depths[int(np.argmin(cv_rmse))]
print("best depth:", best_depth, f"CV RMSE {min(cv_rmse):,.0f}")
fig, ax = plt.subplots(figsize=(8, 4.5))
ax.plot(depths, np.array(train_rmse) / 1e3, marker="o", label="training folds")
ax.plot(depths, np.array(cv_rmse) / 1e3, marker="o", label="validation folds")
ax.set(xlabel="max_depth", ylabel="RMSE (thousand USD)", title="Decision tree depth")
ax.legend()
plt.show()
Output
best depth: 9 CV RMSE 148,810
Two RMSE curves against tree depth 1 to 15. The training curve falls steadily toward zero. The validation curve falls until a depth of about 6, stays flat near 150 thousand USD and creeps up after depth 9, so the gap between the curves keeps growing.
Training and cross-validated RMSE of a decision tree as max_depth grows.

The training error keeps falling, because each extra level fits the training rows more closely. The validation error stops improving after a moderate depth and then rises slightly. The widening gap is overfitting in one picture. cross_validate with return_train_score=True returns both curves in one call.

Step 3 — Define a random forest and gradient boosting

Section titled “Step 3 — Define a random forest and gradient boosting”
from sklearn.ensemble import HistGradientBoostingRegressor, RandomForestRegressor
forest = make_pipeline(
make_preprocessor(scale=False),
RandomForestRegressor(n_estimators=100, n_jobs=-1, random_state=42),
)
hood_type = pd.CategoricalDtype(sorted(X_train["neighborhood"].unique()))
X_train_cat = X_train.astype({"neighborhood": hood_type})
X_test_cat = X_test.astype({"neighborhood": hood_type})
boost = HistGradientBoostingRegressor(random_state=42)
boost_log = TransformedTargetRegressor(
regressor=HistGradientBoostingRegressor(random_state=42),
func=np.log,
inverse_func=np.exp,
)

The forest uses the same preprocessor without scaling: trees do not need it. Gradient boosting needs no preprocessing at all. It reads the category column and the blanks directly. A fixed CategoricalDtype built from the training data gives both frames the same category list. Step 4 fits all of them.

Step 4 — Choose by cross-validation, then report on the test set

Section titled “Step 4 — Choose by cross-validation, then report on the test set”
best_k = 5
knn = make_pipeline(make_preprocessor(), KNeighborsRegressor(n_neighbors=best_k))
tree = make_pipeline(
make_preprocessor(scale=False),
DecisionTreeRegressor(max_depth=best_depth, random_state=42),
)
candidates = { # name: (model, training frame, test frame)
"baseline (mean)": (baseline, X_train, X_test),
"linear, price": (linear, X_train, X_test),
"linear, log price": (log_model, X_train, X_test),
f"KNN k={best_k}": (knn, X_train, X_test),
f"tree depth={best_depth}": (tree, X_train, X_test),
"random forest": (forest, X_train, X_test),
"boosting, price": (boost, X_train_cat, X_test_cat),
"boosting, log price": (boost_log, X_train_cat, X_test_cat),
}
rows = {}
for name, (model, X_tr, X_te) in candidates.items():
cv_scores = cross_val_score(
model, X_tr, y_train, cv=cv, scoring="neg_root_mean_squared_error"
)
test_pred = model.fit(X_tr, y_train).predict(X_te)
rows[name] = {"CV_RMSE": -cv_scores.mean(), **regression_report(y_test, test_pred)}
comparison = pd.DataFrame(rows).T.sort_values("CV_RMSE")
print(comparison.round({"CV_RMSE": 0, "MAE": 0, "RMSE": 0, "R2": 3, "MAPE": 3}))
print("boosting rounds used:", boost.n_iter_)
Output
CV_RMSE MAE RMSE R2 MAPE
boosting, log price 101247.0 58647.0 94269.0 0.915 0.119
boosting, price 105819.0 60889.0 97559.0 0.909 0.125
linear, log price 107252.0 65262.0 102961.0 0.898 0.135
random forest 114812.0 65209.0 104001.0 0.896 0.136
KNN k=5 127042.0 73125.0 113025.0 0.878 0.153
linear, price 146717.0 98861.0 147324.0 0.792 0.237
tree depth=9 148810.0 84905.0 144490.0 0.800 0.169
baseline (mean) 317015.0 215799.0 323250.0 -0.001 0.511
boosting rounds used: 100

best_k = 5 is the winner of Step 1, typed in, and best_depth comes from Step 2. The table is sorted by CV_RMSE, the only column used for the decision; it comes from the training set alone. Gradient boosting on log price has the lowest CV error, so it is the choice. The last line shows that all 100 boosting rounds ran: early stopping stays off on fewer than 10,000 rows. The other four columns are the one-time test report, and they agree: boosting on log price is also best on every test metric. Next come boosting on raw price and the linear model on log price, which beats the forest, KNN and the single tree in cross-validation, because the log turned the multiplicative price structure into a sum. Its remaining gap to boosting is plausibly the curves and interactions that the residuals of Example 4 suggested. For the agency, the trade-off is clear: the log-linear model is nearly as accurate and every coefficient can be explained to a client; boosting is the most accurate. Module 37 tunes these models properly, and module 43 explains the predictions of black-box models.

Common mistakes:

  • Choosing k or the depth by test score. The comparison table is then optimistic for exactly the tuned models.
  • Scaling for trees and forests “to be safe”. It does no harm, but it adds steps that do nothing; for KNN and penalized models it is required.
  • Converting the neighborhood with .astype("category") on train and test separately. If one frame lacks a neighborhood, the category lists differ. Build one CategoricalDtype from the training data.
Mistake Symptom Fix
Fitting a scaler or imputer on all the data before the split Test scores slightly too good; leakage Put every preprocessing step in a Pipeline and fit on X_train
Tuning alpha, k, the degree or the depth on the test set The chosen model disappoints on new data Use cross-validation on the training set (RidgeCV, LassoCV, cross_val_score)
Ridge, Lasso or KNN on unscaled features Strong features dropped or ignored; poor KNN scores StandardScaler before the model, inside the pipeline
Comparing R² of a log model on the log scale with R² of a price model A model looks better than it is Back-transform, then score every model on the same scale
Forgetting to back-transform log predictions Predicted “prices” near 13 TransformedTargetRegressor(func=np.log, inverse_func=np.exp)
r2_score(y_pred, y_true) A different (wrong) R²; the order matters Always metric(y_true, y_pred)
mean_squared_error(..., squared=False) TypeError in scikit-learn 1.6+ root_mean_squared_error(y_true, y_pred)
Reading MAPE 0.12 as 0.12% An error 100 times too small It is a fraction: 0.12 is 12%
Reading raw coefficient sizes as importance sqft looks unimportant Standardize first, or convert to a meaningful step
One-hot all categories plus an intercept Coefficients not unique; rank deficient OneHotEncoder(drop="first"), or use Ridge
A high polynomial degree on many features Thousands of columns, wild predictions Low degree on chosen features, or a tree model
An unlimited DecisionTreeRegressor Training R² of 1.0, poor test score Limit max_depth or min_samples_leaf, or use a forest
Deleting test rows with big residuals A score that looks better than reality Investigate outliers; change the training data only with a documented reason
  • Web and e-commerce: a property or used-car site shows an instant price estimate. A gradient boosting model on a log target serves the number; a residual check flags listings that look mispriced.
  • Operations and automation: a DevOps team predicts the run time of a build or a nightly job from its size and settings, and schedules the queue with the predictions. MAE in minutes is the metric everyone understands.
  • Capacity planning: a web team predicts the CPU load of a server from the request rate with a linear model, and the slope tells them how many requests one more server absorbs.
  • Tooling and monitoring: an alerting tool fits a regression of a metric on its expected drivers and raises an alert when the residual is unusually large, which is residual analysis running in production.
  • Regression predicts a number. Split once (random_state=42), put all preprocessing in a pipeline, and compare every model with a baseline such as DummyRegressor.
  • Linear regression minimizes the sum of squared residuals. np.linalg.lstsq and LinearRegression give the same weights. A coefficient is the change in the prediction per unit of a feature, holding the others fixed, and one-hot coefficients are relative to the dropped reference category.
  • MAE is the typical error, RMSE punishes big misses, R² is the share of variance explained, and MAPE is the typical relative error (as a fraction). Report several, on the scale your users care about.
  • Plot residuals against fitted values, and look at their histogram and Q-Q plot. A funnel suggests a log target; a curve suggests nonlinear features or a nonlinear model.
  • TransformedTargetRegressor fits on log price and returns USD. On this data, it lifts linear R² from 0.79 to 0.90. Log coefficients read as percent changes.
  • Ridge (L2) shrinks, Lasso (L1) also zeroes out features, ElasticNet mixes both. Standardize first and pick alpha with RidgeCV or LassoCV.
  • Flexibility settings (polynomial degree, k, max_depth) move a model from underfitting to overfitting. Choose them with cross-validation, not with the test set.
  • Trees need no scaling; forests average many trees; gradient boosting adds small trees that fix the remaining errors. HistGradientBoostingRegressor handles blanks and categories natively and was the most accurate model here.

Q1. Why does every regression project need a baseline model, and what R² does the mean baseline get?

Answer

The baseline tells you how much the features add. A model that does not beat it clearly has learned nothing useful. Predicting the training mean gives an R² close to 0 on the test set (slightly below 0, because the training mean differs a little from the test mean).

Q2. A log-price model has a coefficient of 0.117 for condition. What does it mean?

Answer

One more level of condition goes with a predicted price that is e0.117−1≈12.4%e^{0.117} - 1 \approx 12.4\% higher, holding every other feature fixed. It is an association, not a proven cause.

Q3. Why does the lesson use OneHotEncoder(drop="first") for the linear models?

Answer

The eight one-hot columns always sum to 1, which duplicates the intercept’s column of ones. The design matrix is then rank-deficient and the coefficients are not unique. Dropping one column fixes this and makes every neighborhood coefficient a difference from the dropped reference neighborhood (Cedar Park).

Q4. Model A has MAE 60,000 and RMSE 150,000. Model B has MAE 65,000 and RMSE 95,000. What does this tell you?

Answer

Model A is slightly better on a typical house, but it makes some very large errors: its RMSE is far above its MAE. Model B’s errors are more even. If one big miss is costly (for example a bank valuing a loan), choose B; if only the average error matters, A is a little better.

Q5. When does MAPE mislead?

Answer

When true values are close to 0 (the division explodes), and when money matters more than ratios: a 10% error on a 200k house and on a 2M house count the same. MAPE also favors predictions that are too low, because an underestimate can be at most 100% wrong while an overestimate has no limit.

Q6. The residuals of a model form a funnel that widens as the fitted value grows. What is this called, and what is a common fix for prices?

Answer

Heteroscedasticity: the error spread depends on the size of the prediction. For prices, model the log of the target (for example with TransformedTargetRegressor(func=np.log, inverse_func=np.exp)), so errors become relative instead of absolute.

Q7. Why must you standardize the features before Ridge, Lasso or KNN, but not before a random forest?

Answer

The Ridge and Lasso penalties treat every coefficient equally, and KNN adds up distances across features, so both depend on the units of each feature. A tree only compares one feature with a threshold at a time, and scaling does not change the order of the values, so it does not change the splits.

Q8. What is the practical difference between Ridge and Lasso?

Answer

Ridge (L2 penalty) shrinks all coefficients toward 0 but keeps every feature. Lasso (L1 penalty) can set coefficients to exactly 0, so it also selects features. With strongly correlated features, Ridge shares the weight among them, while Lasso tends to keep one and drop the others.

Q9. A polynomial model of degree 15 has a training RMSE of 0.27 and a test RMSE of 17. What is happening, and how do you choose a better degree?

Answer

The model overfits: it bends through the training points and swings wildly elsewhere. Choose the degree with cross-validation on the training data (for example cross_val_score with KFold(5, shuffle=True, random_state=42)), and pick the degree with the lowest validation error.

Q10. How does gradient boosting differ from a random forest?

Answer

A random forest trains many deep trees independently on bootstrap samples and averages them, which mainly reduces variance. Gradient boosting trains small trees one after another, each fitted to the residuals of the model so far and added with a learning rate, which mainly reduces bias.

Q11. Why is TransformedTargetRegressor safer than taking np.log(y_train) by hand?

Answer

It applies the inverse function (np.exp) inside predict, so predictions are always in USD and every metric, cross-validation score and saved model works on the original scale. By hand, it is easy to forget the back-transform or to score on the log scale by accident.

Your progress

0 / 4 done

  • Exercises: 26 exercises with hints and full solutions, from metrics by hand to gradient boosting from scratch.
  • Mini-project: build a valuation check that finds mispriced house sales with out-of-fold residuals.
  • Cheat sheet: every regressor, metric, diagnostic plot and gotcha of this module on one page.
  • Next module: 36. Classification predicts categories instead of numbers: churn with logistic regression, trees and boosting, judged with precision, recall and ROC-AUC.