How do I fit ridge regression without leaking the test set?

Standardise predictors inside each training fold with a pipeline, choose a ridge penalty with time-series cross-validation, and compare ridge with ordinary least squares on later rows.

After this lesson, you can fit a ridge regression, choose its penalty on earlier rows and test it on later rows, without the test rows shaping the model.

Why must the scaler learn from training rows only?

Ridge regression adds a penalty on the squared coefficients to the sum of squared errors, and a coefficient’s size depends on its predictor’s units, so the predictors are first standardised. The means and standard deviations for that step must come from the training rows only, or the test rows leak into the model.

\[ \sum_{t}(y_t - \hat y_t)^2 + \alpha\sum_{j}\beta_j^2, \qquad z_{t,j} = \frac{x_{t,j} - \mu_j}{\sigma_j} \]

Here \(y_t\) is the return in week \(t\), \(\hat y_t\) the fitted return, \(\beta_j\) the coefficient of predictor \(j\), \(\alpha\) the penalty, \(x_{t,j}\) the predictor, and \(\mu_j\) and \(\sigma_j\) its training mean and standard deviation.

The example has 16 weeks of a made-up stock, with last week’s return as a signal, last week’s volume in thousands of shares and this week’s return, both returns in percentage points. The first 12 weeks train the model and the last 4 test it. make_pipeline(StandardScaler(), Ridge()) chains the two steps, so each fit of the pipeline fits the scaler on its own training rows first.

The following box builds the data and splits it.

import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression, Ridge
from sklearn.metrics import r2_score
from sklearn.model_selection import GridSearchCV, TimeSeriesSplit
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

weeks = pd.DataFrame({
    "week": pd.date_range("2025-01-03", periods=16, freq="W-FRI"),
    "signal": [-2, 1, -1, 2, 0, 3, -2, 1, 2, -1, 0, 3, 4, 0, 2, -1],
    "volume": [80, 109, 91, 117, 101, 132, 83, 111, 118, 92, 104, 128, 145, 100, 122, 89],
    "stock_return": [-1.6, 0.6, -0.5, 1.1, 0.2, 1.8, -1.0, 0.9, 1.4, -0.7, -0.2, 1.6, 2.4, 0.2, 1.2, -0.6],
})
features = weeks[["signal", "volume"]]
train_features = features.iloc[:12]
test_features = features.iloc[12:]
train_return = weeks["stock_return"].iloc[:12]
test_return = weeks["stock_return"].iloc[12:]
print(weeks.head(3))
        week  signal  volume  stock_return
0 2025-01-03      -2      80          -1.6
1 2025-01-10       1     109           0.6
2 2025-01-17      -1      91          -0.5

The signal and volume move together, which makes the separate coefficients of ordinary least squares unstable and gives ridge something to fix.

How do I choose the penalty?

GridSearchCV fits the pipeline for every candidate penalty on every validation fold and keeps the penalty with the lowest mean validation error, here 1.0, with a mean squared error of 0.0631.

np.logspace(-2, 2, 5) gives five penalties from 0.01 to 100. TimeSeriesSplit(n_splits=3, test_size=2) makes three folds that always validate on later weeks, as in the lesson on TimeSeriesSplit. "ridge__alpha" names the step ridge and its parameter alpha, separated by two underscores. scoring="neg_mean_squared_error" scores by minus the mean squared error, because the search keeps the highest score, and .cv_results_["mean_test_score"] holds each penalty’s mean score.

The following box runs the search on the 12 training weeks.

penalties = np.logspace(-2, 2, 5)
search = GridSearchCV(make_pipeline(StandardScaler(), Ridge()), {"ridge__alpha": penalties}, cv=TimeSeriesSplit(n_splits=3, test_size=2), scoring="neg_mean_squared_error")
search.fit(train_features, train_return)
print(pd.DataFrame({"alpha": penalties, "mse": -search.cv_results_["mean_test_score"]}).round(4))
    alpha     mse
0    0.01  0.0727
1    0.10  0.0676
2    1.00  0.0631
3   10.00  0.1907
4  100.00  0.7886

After the search, the pipeline with the chosen penalty is fitted again on all 12 training weeks.

How does ridge compare with OLS on the test weeks?

On the four test weeks, ridge has an R² of 0.9857 and ordinary least squares 0.9844, so ridge’s squared errors are slightly smaller. Four weeks are too few to show that ridge forecasts better.

.predict() on the search standardises the test rows with the training means and standard deviations and then applies ridge. r2_score compares the squared errors with those of the mean test return.

The following box compares the two models on the test weeks.

ridge_prediction = search.predict(test_features)
ols_prediction = LinearRegression().fit(train_features, train_return).predict(test_features)
print(round(r2_score(test_return, ridge_prediction), 4), round(r2_score(test_return, ols_prediction), 4))
0.9857 0.9844

Your turn

Compute the mean squared error of both models on the test weeks. You should see 0.0181 for ridge and 0.0197 for ordinary least squares.

** 2 squares each error and .mean() averages the four squares.

print(round(((test_return - ridge_prediction) ** 2).mean(), 4), round(((test_return - ols_prediction) ** 2).mean(), 4))
0.0181 0.0197