Fig. 1 in words
442 diabetes patients · 15 penalties · 5 folds each · same data as code 05
1 5 folds · 309 learn patients
- run 1 to run 5: each run scores one fold and fits on the other four
- fit on 4 folds · score 1 fold
- ① test 133 sealed
- CV error = mean of the 5 fold scores, standard error = their sd ÷ √5
2 Ridge on 65 terms · error (MSE) by penalty α
- train (fold mean) · CV ± 1 SE, error 2 000 to 5 000
- too free: it memorises · ② CV 4 027 at α 0.001 · train 2 037
- ③ α 31.6 · 3 047
- ④ best + 1 SE = 3 250
- CV 5 214 at α 10 000
- too tight: it cannot bend
- penalty α (log scale) → more penalty, simpler model: 0.001 to 10 000
01 Price the Weights Penalty
- Ridge adds α × (sum of squared weights) to the squared error (Hoerl & Kennard 1970)
- Lasso prices absolute weights and “tends to produce some coefficients that are exactly 0” (Tibshirani 1996)
α = 0 is plain least squares. The penalty treats all columns alike, so I scale first (Sprint 28).
02 Too Free, Too Tight Fit
- α = 0.001: training error 2 037, CV error 4 027
- α = 10 000: both above 5 000; the model can barely bend
- Between them, CV error bottoms out at α = 31.6
Too loose chases noise, too tight misses signal: the bias–variance trade-off (Hastie et al. 2009, ch. 7).
03 K Folds Cross-val
- Cut the learn set into 5 folds: fit on 4, score the 5th, rotate
- Every learn patient is scored once, by a model that never saw it
- Stone (1974) formalised choosing and assessing predictions this way
The 133 test patients never enter the folds (Sprint 20).
04 One Standard Error 1-SE
- The best CV error is an estimate too: 3 047 ± 203
- The 1-SE rule takes the most penalised model within one standard error of the best (Hastie et al. 2009, §7.10)
Here α = 100, CV 3 062. On the sealed test set: 3 717 against 3 760.
05 Try It Yourself PYTHON 3.13.15
sprint29_regularisation_cross_validation.py
from sklearn import preprocessing as pp
from sklearn.datasets import load_diabetes
from sklearn.linear_model import Ridge
from sklearn.model_selection import KFold, cross_validate
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
X, y = load_diabetes(return_X_y=True) # 442 patients
a, b, ya, yb = train_test_split(X, y, test_size=0.3,
random_state=29)
folds = KFold(5, shuffle=True, random_state=29)
model = lambda alpha: make_pipeline( # 65 terms:
pp.PolynomialFeatures(2, include_bias=False),
pp.StandardScaler(), Ridge(alpha)) # squares, pairs
rows = [] # alpha, train, cv, se
for alpha in [10 ** (k / 2) for k in range(-6, 9)]:
r = cross_validate(model(alpha), a, ya, cv=folds,
scoring="neg_mean_squared_error",
return_train_score=True)
cv = -r["test_score"] # 5 fold MSEs
rows.append((alpha, -r["train_score"].mean(),
cv.mean(), cv.std(ddof=1) / 5**0.5))
best = min(rows, key=lambda r: r[2])
limit = best[2] + best[3] # 1-SE rule
one_se = max(r for r in rows if r[2] <= limit)
print(len(ya), "learn,", len(yb), "test; MSE:")
for alpha, tr, cv, se in (rows[0], best, one_se):
m = model(alpha).fit(a, ya) # refit
test = ((m.predict(b) - yb) ** 2).mean() # sealed
print(f"{alpha:8.3f} train {tr:4.0f} cv {cv:4.0f}",
f"±{se:3.0f} test {test:4.0f}")
Output, as printed on the image
309 learn, 133 test; MSE:
0.001 train 2037 cv 4027 ±412 test 4140
31.623 train 2232 cv 3047 ±203 test 3760
100.000 train 2404 cv 3062 ±121 test 3717
Run it. sprint29_regularisation_cross_validation.py · versions, data and steps
Check: 4 027 − 2 037 = 1 990 gap at α = 0.001 · 3 047 + 203 = 3 250 ≥ 3 062 · 10k/2, k = −6 … 8: 15 penalties. scikit-learn 1.9.1
06 General Notes Practice
- Build terms and scale inside the pipeline, so each fold fits its own
- Report the CV mean with its standard error
- A CV score used to pick α flatters the model it picked (Cawley & Talbot 2010)
scikit-learn's diabetes columns come centred and scaled on all 442 patients, test rows included.
07 Mini Project Hands-on
- Swap Ridge for Lasso; count the zero weights
- Use 10 folds, then 5 shuffled repeats
- Fit the plain 10 columns: does CV prefer them?
- Plot train and CV error against α
Lasso at α = 3: CV 2 907, with 16 of 65 weights non-zero. The plain 10 columns: CV 3 040.
R Trusted Sources
- Hoerl & Kennard (1970). Ridge Regression: Biased Estimation for Nonorthogonal Problems. Technometrics 12(1), 55–67
- Tibshirani (1996). Regression Shrinkage and Selection via the Lasso. J. R. Stat. Soc. B 58(1), 267–288
- Stone (1974). Cross-Validatory Choice and Assessment of Statistical Predictions. J. R. Stat. Soc. B 36(2), 111–147
- Hastie, Tibshirani & Friedman (2009). The Elements of Statistical Learning, 2nd ed., ch. 7. Springer
- Cawley & Talbot (2010). On Over-fitting in Model Selection and Subsequent Selection Bias in Performance Evaluation. JMLR 11, 2079–2107
- Efron, Hastie, Johnstone & Tibshirani (2004). Least Angle Regression. Ann. Stat. 32(2), 407–499
