Validation set vs test set: choosing the ridge penalty in Python

Machine Learning
Tutorial
Python
OLS always has the lowest MSE on the data it is fitted to, yet in this simulation ridge regression has a lower MSE than OLS on the test data. I show what the training, validation, and test data each do in Python.
Published

November 20, 2026

Updated

November 26, 2026

OLS gives the lowest sum of squared residuals on the data it is fitted to, because that sum is what OLS minimizes. But the lowest sum does not imply that OLS is the best forecasting method because OLS fits the noise in those data, which does not repeat in new data. Ridge regression (Hoerl & Kennard, 1970), in contrast, accepts a higher sum of squared residuals in exchange for potentially improved forecasting by penalizing the size of its coefficients.

In this tutorial, I simulate 20 years of monthly market returns and ten candidate signals, of which two predict the return. Then I fit OLS and ridge regression on the first ten years (the training data), choose ridge’s penalty on the next five years (the validation data), and compare the two models on the last five years (the test data).

Step 1. Simulating the data

I start by simulating monthly market returns from January 2000 to December 2019 and ten signals that may be associated with market returns. The return in month \(t\) depends on the signals at the end of month \(t-1\):

\[ r_t = a + \sum_{j=1}^{10} \beta_j x_{j,t-1} + \varepsilon_t \tag{1} \]

where \(r_t\) is the market return in month \(t\) in percent, \(a\) is the intercept, \(x_{j,t-1}\) is signal \(j\) at the end of month \(t-1\), \(\beta_j\) is the true coefficient of signal \(j\), and \(\varepsilon_t\) is noise.

In the simulation, I set the true relationship between the signals and the market return such that the intercept has a true value of 0.5, \(\beta_1\) and \(\beta_2\) have a true value of 0.6, and the remaining eight coefficients are 0. So of the ten signals, only signals 1 and 2 are associated with the market return. Both OLS and ridge still use all ten signals.

I draw each signal from a normal distribution with mean 0 and standard deviation 1, and the noise from a normal distribution with mean 0 and standard deviation 4.5 percentage points. All draws are independent.

Because I simulate the noise with a standard deviation well above that of signals 1 and 2, most of the variation in the market return comes from the noise.

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression, Ridge
from sklearn.metrics import mean_squared_error
from sklearn.preprocessing import StandardScaler

SEED = 0
N_MONTHS = 240
INTERCEPT = 0.5
TRUE_COEFFICIENTS = np.array([0.6, 0.6, 0, 0, 0, 0, 0, 0, 0, 0])
NOISE_SD = 4.5

rng = np.random.default_rng(SEED)
signals = [f"signal_{j}" for j in range(1, 11)]
dates = pd.date_range("2000-01-31", periods=N_MONTHS, freq="BME", name="date")
data = pd.DataFrame(rng.standard_normal((N_MONTHS, 10)), index=dates, columns=signals)
noise = rng.normal(0, NOISE_SD, N_MONTHS)
data.insert(0, "return", INTERCEPT + data[signals] @ TRUE_COEFFICIENTS + noise)
print(data.iloc[:, :5].round(2).head().to_string())
            return  signal_1  signal_2  signal_3  signal_4
date                                                      
2000-01-31    7.35      0.13     -0.13      0.64      0.10
2000-02-29   -4.00     -0.62      0.04     -2.33     -0.22
2000-03-31   -0.80     -0.13      1.37     -0.67      0.35
2000-04-28   -3.75     -1.01     -0.21     -0.16      0.54
2000-05-31   -5.65     -1.26      1.51      1.35      0.78

The table shows the first five rows and the first five columns of the simulated data, with the returns in percent. Each row holds a month’s return next to the signals at the end of the month before, as in (1), so the simulated data need no lag and keep all 240 months.

Step 2. What OLS and ridge minimize, and why ridge needs validation data

Ridge penalizes the coefficients, and the scale of the coefficients strongly affects the penalty. Because a coefficient’s scale depends on the units of its signal, I standardize the signals. I use scikit-learn’s StandardScaler, which gives each signal a mean of 0 and a standard deviation of 1:

\[ z_{j,t-1} = \frac{x_{j,t-1} - \bar{x}_j}{s_j} \tag{2} \]

where \(\bar{x}_j\) is the mean of signal \(j\), \(s_j\) its standard deviation, and \(t-1\) the end of the month before the return, as in (1). A standardized value is how many standard deviations an observation is above or below its average.

OLS minimizes the sum of squared residuals, where the residual is the difference between the realized return and the return that we predict:

\[ \min_{c,\, b_1, \dots, b_{10}} \; \sum_{t \in \text{training}} \Big( r_t - c - \sum_{j=1}^{10} b_j z_{j,t-1} \Big)^2 \tag{3} \]

where \(c\) is the intercept and \(b_j\) is the coefficient of the standardized signal \(j\). In contrast, ridge adds a penalty on the size of the coefficients to the sum in (3), with the aim of a lower MSE than OLS’s on new data:

\[ \min_{c,\, b_1, \dots, b_{10}} \; \sum_{t \in \text{training}} \Big( r_t - c - \sum_{j=1}^{10} b_j z_{j,t-1} \Big)^2 + \lambda \sum_{j=1}^{10} b_j^2 \tag{4} \]

where \(\lambda \ge 0\) is the penalty, and the intercept \(c\) has no penalty. Scikit-learn’s Ridge(alpha=...) minimizes (4) with \(\lambda\) equal to alpha. A ridge regression with no penalty, \(\lambda = 0\), is OLS. The larger the penalty, the smaller the sum of the squared coefficients, although a single coefficient can move away from 0 on the way.

The training data cannot choose the penalty, because OLS estimates the coefficients that give the smallest sum of squared residuals in the training data, smaller than ridge’s for every \(\lambda\):

\[ \sum_{t \in \text{training}} \hat{e}_{t,\text{ridge}}^{\,2} \;\ge\; \sum_{t \in \text{training}} \hat{e}_{t,\text{OLS}}^{\,2} \tag{5} \]

where \(\hat{e}_t\) is a model’s residual in month \(t\), so on the training data, the penalty with the lowest MSE is always 0. But aiming for the smallest residuals makes OLS fit the noise in the training data, which does not repeat in unseen data.

So besides the training data and the test data, I need a third part between them, the validation data. On the validation data, the penalty with the lowest MSE is not 0 by construction and can be any value.

The validation data have new noise, so the OLS coefficients fitted to the training data no longer give the lowest MSE, and a penalty can lower the MSE. For each \(\lambda\), I estimate the coefficients on the training data and compute the MSE on the validation data. The validation data are used to choose the penalty \(\lambda\) that minimizes the validation MSE. Then I compare OLS and ridge once on the test data, where ridge is OLS with the chosen penalty on the coefficients.

I split the data into training data from 2000 to 2009 (120 months), validation data from 2010 to 2014 (60 months), and test data from 2015 to 2019 (60 months).

The 240 months as one bar in three parts. Training data, 2000 to 2009, 120 months: OLS and ridge estimate their coefficients. Validation data, 2010 to 2014, 60 months: choose ridge's penalty. Test data, 2015 to 2019, 60 months: compare OLS and ridge once.

The training, validation, and test data must follow each other in time because financial time series are chronological. Violating that order causes information leakage and an unrealistic setting. In a live setting, a model cannot be trained on the future and tested on the past. Observations in financial data also depend on each other over time, through, e.g., trends and volatility clustering, so a model trained on later months would carry information about the earlier months it is tested on.

The mean and standard deviation in (2) come only from the training data, and I apply them to the training data, but also to the validation and test data. I use the training values because, in a realistic setting, at the start of the test data in January 2015, it is nearly impossible to know the realized values of every signal over the entire test period. Standardizing with the mean and standard deviation of the test data would bring that information into the forecasts, which is information leakage. The same holds for the validation data.

train = data.loc["2000":"2009"]
validation = data.loc["2010":"2014"]
test = data.loc["2015":"2019"]

scaler = StandardScaler().fit(train[signals])
X_train = scaler.transform(train[signals])
X_validation = scaler.transform(validation[signals])
X_test = scaler.transform(test[signals])
y_train, y_validation, y_test = train["return"], validation["return"], test["return"]

parts = {"training": train, "validation": validation, "test": test}
print(pd.DataFrame({"first month": [part.index[0].strftime("%b %Y") for part in parts.values()],
                    "last month": [part.index[-1].strftime("%b %Y") for part in parts.values()],
                    "months": [len(part) for part in parts.values()]}, index=list(parts)).to_string())
           first month last month  months
training      Jan 2000   Dec 2009     120
validation    Jan 2010   Dec 2014      60
test          Jan 2015   Dec 2019      60

Step 3. Fitting OLS on the training data

The table divides each \(b_j\) by \(s_j\) to show it in the signal’s own units, alongside the true \(\beta_j\).

ols = LinearRegression().fit(X_train, y_train)
coefficients = pd.DataFrame({"true": TRUE_COEFFICIENTS, "OLS": ols.coef_ / scaler.scale_}, index=signals)
print(coefficients.round(2).to_string())
print(f"training MSE of OLS: {mean_squared_error(y_train, ols.predict(X_train)):.2f}")
print(f"training MSE of the true coefficients: "
      f"{mean_squared_error(y_train, INTERCEPT + train[signals] @ TRUE_COEFFICIENTS):.2f}")
           true   OLS
signal_1    0.6  0.38
signal_2    0.6  0.64
signal_3    0.0 -0.56
signal_4    0.0  0.24
signal_5    0.0  0.56
signal_6    0.0  0.15
signal_7    0.0 -0.08
signal_8    0.0 -0.02
signal_9    0.0  0.18
signal_10   0.0 -0.05
training MSE of OLS: 16.45
training MSE of the true coefficients: 17.54

OLS gives the eight signals other than signals 1 and 2 coefficients that are not 0, although their true coefficients are 0, because it uses them to fit the noise in the training data. So OLS’s training MSE, 16.45, is lower than the 17.54 of the true coefficients.

Step 4. Choosing the penalty on the validation data

With one signal, (4) shows how much ridge shrinks its coefficient. Here \(z_{t-1}\) is the standardized signal from (2), and \(n = 120\) is the number of training months. Because \(z_{t-1}\) has a mean of 0 in the training data, the intercept equals the average training return \(\bar{r}\). Because its variance is 1, computed by dividing by \(n\), the sum of its squares is:

\[ \sum_{t} z_{t-1}^2 = \frac{\sum_{t} \left( x_{t-1} - \bar{x} \right)^2}{s^2} = \frac{n s^2}{s^2} = n \]

Setting the derivative of (4) with respect to \(b\) to zero gives:

\[ -2 \sum_{t} z_{t-1} \left( r_t - \bar{r} - b z_{t-1} \right) + 2 \lambda b = 0 \tag{6} \]

\[ b \Big( \sum_{t} z_{t-1}^2 + \lambda \Big) = \sum_{t} z_{t-1} \left( r_t - \bar{r} \right) \]

\[ \hat{b}_{\text{ridge}} = \frac{\sum_{t} z_{t-1} \left( r_t - \bar{r} \right)}{n + \lambda} = \hat{b}_{\text{OLS}} \times \frac{n}{n + \lambda} \tag{7} \]

where \(\hat{b}_{\text{OLS}} = \sum_t z_{t-1} (r_t - \bar{r}) / n\) is (7) with \(\lambda = 0\). With \(n = 120\), a penalty of 120 halves the coefficient, and a penalty of 251 multiplies it by \(120 / 371 = 0.32\). With ten signals, (7) holds for every coefficient if the standardized signals are uncorrelated in the training data. They are not exactly uncorrelated here, so the ten coefficients shrink by different factors.

I fit ridge on the training data with 51 penalties from 0.1 to 10,000. For each penalty, I compute the mean squared error (MSE) on the training data and on the validation data:

\[ \text{MSE} = \frac{1}{n} \sum_{t} \left( r_t - \hat{r}_t \right)^2 \tag{8} \]

where \(n\) is the number of months in the part and \(\hat{r}_t\) is the model’s predicted return for month \(t\). On the training data, the prediction comes from a model fitted on those same data.

penalties = np.logspace(-1, 4, 51)
rows = []
for penalty in penalties:
    ridge = Ridge(alpha=penalty).fit(X_train, y_train)
    rows.append({"penalty": penalty,
                 "training MSE": mean_squared_error(y_train, ridge.predict(X_train)),
                 "validation MSE": mean_squared_error(y_validation, ridge.predict(X_validation))})
grid = pd.DataFrame(rows).set_index("penalty")
chosen_penalty = grid["validation MSE"].idxmin()
print(grid.iloc[::10].round(2).to_string())
print(f"chosen penalty: {chosen_penalty:.0f}")
print(f"validation MSE of OLS: {mean_squared_error(y_validation, ols.predict(X_validation)):.2f}, "
      f"of ridge with the chosen penalty: {grid['validation MSE'].min():.2f}")
         training MSE  validation MSE
penalty                              
0.1             16.45           24.37
1.0             16.45           24.36
10.0            16.46           24.27
100.0           16.71           23.92
1000.0          17.43           23.92
10000.0         17.66           23.99
chosen penalty: 251
validation MSE of OLS: 24.37, of ridge with the chosen penalty: 23.86
TEAL, ORANGE, GREY = "#17868A", "#D2822B", "#7a7168"
plt.rcParams.update({"figure.facecolor": "#FCEFE3", "axes.facecolor": "#FCEFE3", "axes.edgecolor": "#D5C6B4",
                     "axes.spines.top": False, "axes.spines.right": False, "axes.grid": True, "axes.grid.axis": "y",
                     "axes.axisbelow": True,
                     "grid.color": "#EADCCC", "axes.labelcolor": "#4a4a4a", "axes.labelsize": 13,
                     "xtick.color": GREY, "ytick.color": GREY, "legend.frameon": False})
ols_training_mse = mean_squared_error(y_train, ols.predict(X_train))
ols_validation_mse = mean_squared_error(y_validation, ols.predict(X_validation))
lowest = grid["validation MSE"].min() - ols_validation_mse
figure, axis = plt.subplots(figsize=(10, 6.5))
axis.axhline(0, color=GREY, linewidth=1)
axis.text(grid.index[-1], 0.04, "OLS (no penalty)", ha="right", va="bottom", fontsize=12, color=GREY)
axis.plot(grid.index, grid["training MSE"] - ols_training_mse, color=ORANGE, linewidth=2.5,
          label="Training data, 2000 to 2009")
axis.plot(grid.index, grid["validation MSE"] - ols_validation_mse, color=TEAL, linewidth=2.5,
          label="Validation data, 2010 to 2014")
axis.scatter(chosen_penalty, lowest, color=TEAL, s=50, zorder=3)
axis.annotate(f"Chosen penalty: {chosen_penalty:.0f}", (chosen_penalty, lowest), xytext=(0, -26),
              textcoords="offset points", ha="center", fontsize=12, color="#4a4a4a")
axis.set_ylim(-0.85, 1.45)
axis.set_xscale("log")
axis.set_xlabel("Penalty λ (log scale: each step is 10 times larger)")
axis.set_ylabel("Ridge's MSE minus OLS's MSE")
axis.legend(loc="upper left")
figure.savefig("ridge_mse_by_penalty.png", dpi=200, bbox_inches="tight")

Ridge's MSE minus OLS's MSE against the penalty on a log scale. On the training data, the difference rises from 0 to 1.21 as the penalty grows. On the validation data, it falls to minus 0.51 at a penalty of about 251 and then rises to minus 0.38.

The chart shows ridge’s MSE minus OLS’s MSE for each penalty, so OLS is the line at 0. The penalty axis is on a log scale, where each step is 10 times larger than the one before. On the training data, ridge’s MSE is above OLS’s 16.45 for every penalty, by up to 1.21 at a penalty of 10,000, as (5) requires. On the validation data, ridge’s MSE falls from OLS’s 24.37 to 23.86 (0.51 lower) at a penalty of about 251, then rises to 23.99 (0.38 below OLS’s). I choose about 251, the penalty with the lowest validation MSE.

Step 5. Testing both models once

I compare OLS and ridge forecasts with the average return of the training data:

\[ R^2_{\text{OOS}} = 1 - \frac{\sum_{t \in \text{test}} \left( r_t - \hat{r}_t \right)^2}{\sum_{t \in \text{test}} \left( r_t - \bar{r}_{\text{training}} \right)^2} \tag{9} \]

where \(\bar{r}_{\text{training}}\) is the average return in the training data.

ridge = Ridge(alpha=chosen_penalty).fit(X_train, y_train)
coefficients["ridge"] = ridge.coef_ / scaler.scale_
forecasts = {"training average": np.full(len(y_test), y_train.mean()),
             "OLS": ols.predict(X_test),
             "ridge": ridge.predict(X_test)}
test_mse = pd.Series({name: mean_squared_error(y_test, forecast) for name, forecast in forecasts.items()})
print(pd.DataFrame({"test MSE": test_mse,
                    "out-of-sample R², %": 100 * (1 - test_mse / test_mse["training average"])}).round(2).to_string())
print()
print(coefficients.round(2).to_string())
                  test MSE  out-of-sample R², %
training average     21.16                 0.00
OLS                  22.03                -4.14
ridge                21.11                 0.21

           true   OLS  ridge
signal_1    0.6  0.38   0.12
signal_2    0.6  0.64   0.21
signal_3    0.0 -0.56  -0.16
signal_4    0.0  0.24   0.04
signal_5    0.0  0.56   0.19
signal_6    0.0  0.15   0.04
signal_7    0.0 -0.08  -0.06
signal_8    0.0 -0.02  -0.02
signal_9    0.0  0.18   0.07
signal_10   0.0 -0.05   0.00

OLS out-of-sample R² is −4.14%, while ridge’s out-of-sample R² is 0.21%. Eight of the ten signals OLS uses have a true coefficient of 0. Ridge penalizes those signals, as well as the two signals that are truly associated with returns.

positions = np.arange(len(signals))
figure, axis = plt.subplots(figsize=(10, 6.5))
for offset, column, colour, label in [(-0.27, "true", GREY, "True coefficient"), (0, "OLS", ORANGE, "OLS"),
                                      (0.27, "ridge", TEAL, f"Ridge, penalty {chosen_penalty:.0f}")]:
    axis.bar(positions + offset, coefficients[column], width=0.25, color=colour, label=label)
axis.axhline(0, color="#4a4a4a", linewidth=0.8)
axis.set_xticks(positions, [str(j) for j in range(1, 11)], fontsize=12)
axis.set_xlabel("Signal")
axis.set_ylabel("Coefficient (% return per unit of the signal)")
axis.legend(loc="upper right")
figure.savefig("ridge_coefficients.png", dpi=200, bbox_inches="tight")

Coefficients of the ten signals. The true coefficients are 0.6 for signals 1 and 2 and 0 for the others. OLS gives signals 3 and 5 coefficients of minus 0.56 and 0.56. Ridge with a penalty of about 251 gives every signal a coefficient closer to 0 than OLS's.

Step 6. Repeating the test with 1,000 samples

One sample can mislead, so I repeat Steps 1 to 5 on 1,000 samples. In each sample, I also compute each model’s MSE on 10,000 new months simulated from (1), which measures its MSE on new data almost exactly.

def one_sample(seed):
    rng = np.random.default_rng(seed)
    X = rng.standard_normal((N_MONTHS, 10))
    y = INTERCEPT + X @ TRUE_COEFFICIENTS + rng.normal(0, NOISE_SD, N_MONTHS)
    X_new = rng.standard_normal((10_000, 10))
    y_new = INTERCEPT + X_new @ TRUE_COEFFICIENTS + rng.normal(0, NOISE_SD, 10_000)
    train, validation, test = slice(0, 120), slice(120, 180), slice(180, 240)
    scaler = StandardScaler().fit(X[train])
    X, X_new = scaler.transform(X), scaler.transform(X_new)
    ols = LinearRegression().fit(X[train], y[train])
    validation_mse = [mean_squared_error(y[validation], Ridge(alpha=penalty).fit(X[train], y[train]).predict(X[validation]))
                      for penalty in penalties]
    ridge = Ridge(alpha=penalties[np.argmin(validation_mse)]).fit(X[train], y[train])
    return {"OLS training": mean_squared_error(y[train], ols.predict(X[train])),
            "ridge training": mean_squared_error(y[train], ridge.predict(X[train])),
            "ridge validation": min(validation_mse),
            "average test": mean_squared_error(y[test], np.full(60, y[train].mean())),
            "OLS test": mean_squared_error(y[test], ols.predict(X[test])),
            "ridge test": mean_squared_error(y[test], ridge.predict(X[test])),
            "OLS new months": mean_squared_error(y_new, ols.predict(X_new)),
            "ridge new months": mean_squared_error(y_new, ridge.predict(X_new))}


samples = pd.DataFrame([one_sample(seed) for seed in range(1000)])
print(f"ridge's training MSE at least OLS's: {(samples['ridge training'] >= samples['OLS training'] - 1e-9).mean():.0%}")
print(f"ridge's test MSE below OLS's: {(samples['ridge test'] < samples['OLS test']).mean():.1%}")
print(f"ridge's test MSE below the training average's: {(samples['ridge test'] < samples['average test']).mean():.1%}")
print(f"OLS's test MSE below the training average's: {(samples['OLS test'] < samples['average test']).mean():.1%}")
print()
print("averages over the 1,000 samples:")
print(pd.DataFrame({"OLS": [np.nan, samples["OLS test"].mean(), samples["OLS new months"].mean()],
                    "ridge": [samples["ridge validation"].mean(), samples["ridge test"].mean(),
                              samples["ridge new months"].mean()]},
                   index=["validation MSE, chosen penalty", "test MSE", "MSE on 10,000 new months"]).round(2).to_string(na_rep="-"))
ridge's training MSE at least OLS's: 100%
ridge's test MSE below OLS's: 83.5%
ridge's test MSE below the training average's: 59.2%
OLS's test MSE below the training average's: 28.0%

averages over the 1,000 samples:
                                  OLS  ridge
validation MSE, chosen penalty      -  20.65
test MSE                        22.21  20.97
MSE on 10,000 new months        22.27  21.09

In all 1,000 samples, OLS has the lower training MSE, as (5) requires. On the test data, ridge has the lower MSE in 83.5% of the samples. Also, the validation MSE of the chosen penalty averages 20.65, below ridge’s average MSE of 21.09 on the new months, because I pick the lowest of 51 validation MSEs.

Step 7. Forecasting new months with the chosen model

The test data are used once, so the penalty stays at about 251, as chosen by the validation data. To forecast January 2020, I fit the scaler and ridge again on all 240 months, because their returns are now known, and apply both to the signals at the end of December 2019. Each month, the same steps can be repeated with one more month of data.

final_scaler = StandardScaler().fit(data[signals])
final_ridge = Ridge(alpha=chosen_penalty).fit(final_scaler.transform(data[signals]), data["return"])
signals_december_2019 = pd.DataFrame(rng.standard_normal((1, 10)), columns=signals)
forecast = final_ridge.predict(final_scaler.transform(signals_december_2019))[0]
print(f"forecast of the January 2020 return: {forecast:.2f}%")
forecast of the January 2020 return: 0.45%

The forecast of the January 2020 return is 0.45%.

Conclusion

On the training data, OLS always has a lower MSE than ridge by construction. The validation data are used to choose ridge’s penalty because, on new data, OLS may no longer have a lower MSE than ridge. In this simulation, ridge has the lower test MSE in 83.5% of 1,000 samples, and its average MSE on the new months is 21.09, against 22.27 for OLS.

References

Hoerl, A. E., & Kennard, R. W. (1970). Ridge regression: Biased estimation for nonorthogonal problems. Technometrics, 12(1), 55–67. https://doi.org/10.1080/00401706.1970.10488634