Machine Learning II: Generalization and Model Selection

Holdout and cross-validation

Ben Dai

CUHK · Department of Statistics and Data Science

Generalization

01
CUHK emblem

A model can fit its training data beautifully and still fail on new examples.

Three familiar models make different assumptions

fewer learned valuesmore stored detail
SIMPLEGlobal mean

Use one learned number for every user–item pair.

\[\widehat r_{ui}=\mu\]
MORE STRUCTUREThree-mean average

Average global, user, and item means, with fallback for missing IDs.

personalization without storing every answer

MAXIMUM DETAILMemorization + fallback

Store every observed rating; use the global mean for an unseen pair.

perfect recall of the training rows

A model that remembers more can reduce training error. That alone does not tell us which model predicts unseen pairs best.

Memorization wins on the training ratings

TRAINING TRIPLES
useritemrating
\(u_1\)\(i_2\)4
\(u_2\)\(i_1\)5
\(u_1\)\(i_4\)2
store exact answers →
LOOKUP ON SEEN PAIRS
\((u_1,i_2)\)→\(\widehat r=4\)
\((u_2,i_1)\)→\(\widehat r=5\)
\((u_1,i_4)\)→\(\widehat r=2\)

training RMSE = 0

NOW PREDICT A NEW PAIR\((u_4,i_7)\)→\(\mu\)

No stored answer: fall back to the global mean.

Perfect reconstruction is not generalization: the training rows cannot reveal how the lookup rule behaves on a new pair.

Model selection needs fresh known ratings

FITtraining triples

learn the global mean, user/item summaries, or stored lookup table

produce candidate predictors →
global mean
three-mean average
memorization + fallback
predict →
FRESH PAIRSratings known to us

but never shown while fitting the candidates

TRAINING RMSECan it reconstruct ratings it learned from?
VALIDATION RMSECan it predict held-out ratings?

We call those fresh, scored rows the validation set. They let us compare candidates before the final test.

Train and validation reveal model fit

candidatetraining RMSEvalidation RMSEdiagnosis
global meanhighhighunderfitting
three-mean averagelowerlowestuseful fit
memorization + fallbackzerohighoverfitting

UnderfittingThe model misses useful patterns in both training and validation data.

OverfittingThe model learns training details that do not transfer to held-out ratings.

Validation turns “fits the data” into the question we actually care about: does the learned pattern transfer?

Three fits to the same noisy data

noisy training observations underlying trend (shown for illustration)

Three fits on identical noisy training observations: the flat underfit line misses the trend, the smooth useful fit follows it, and the jagged overfit line passes through every point.

The overfit curve learns the noise around the trend. Those deviations may not repeat on new data.

Model selection with Ridge regression

02
CUHK emblem

Keep the prediction rule fixed; use validation to choose the penalty strength.

Ridge regression: four questions

Return to the California housing model from ML I. Ridge(alpha=…) adds a penalty on large coefficients.
1 · MODEL
\(\widehat y=b+x^{\mathsf T}w\)

Predict from the feature values.

2 · HYPERPARAMETER
\(\alpha\geq 0\)

Choose the penalty strength before fitting.

3 · FITTING CRITERION \[\min_{b,w}\;\sum_{i=1}^{n}\bigl(y_i-b-x_i^{\mathsf T}w\bigr)^2+\alpha\lVert w\rVert_2^2\]

Fit the training rows; penalize the coefficients \(w\), not the intercept \(b\).

4 · LEARNED PARAMETERS\(\widehat b,\widehat w\)

After fit: intercept_ and coef_.

What does \(\alpha\) change?

\(\alpha=0\)No penalty

The fitting objective becomes ordinary least squares. Coefficients may follow training noise.

moderate \(\alpha\)Some shrinkage

Smaller coefficients can improve prediction on new rows.

large \(\alpha\)Strong shrinkage

Too much penalty can miss useful relationships.

We do not know the best \(\alpha\) from the training loss alone. Compare held-out RMSE.

Holdout validation chooses \(\alpha\)

FIT SPLITfit Ridge for each \(\alpha\)

learn a new \(\widehat b\) and \(\widehat w\) each time

predict held-out rows
VALIDATION SPLITcompare RMSE

score each fitted Ridge model without refitting it

\(\alpha=0.1\)higher validation RMSE
\(\alpha=1\)lowest validation RMSE
\(\alpha=100\)higher validation RMSE

In this illustration, choose \(\alpha=1\). These rankings are schematic; the best value depends on the data.

One validation split can give a noisy ranking

SPLIT A
best: \(\alpha=0.1\)

one held-out sample favors weaker shrinkage

SPLIT B
best: \(\alpha=1\)

another sample favors stronger shrinkage

One validation samplethe score depends on which rows were held out

One \(\alpha\) rankinga close comparison may reverse on another sample

Natural extensionlet every block take a turn as the validation set

K-fold CV rotates the validation role

\[\mathrm{CV\ RMSE}=\frac{1}{5}\sum_{j=1}^{5}\mathrm{RMSE}_j\]

For each \(\alpha\), fit Ridge five times and average its validation RMSE. Choose \(\alpha\) using these averages.

After validation, refit and test once

FITTING ROUNDSfit Ridge for each \(\alpha\)
HOLDOUT OR CV SCORESselect \(\alpha\)
selection finished
ALL DEVELOPMENT DATArefit Ridge with that \(\alpha\)

learn new coefficients from every development row

evaluate once
TESTfinal RMSE

no more model changes afterward

More fitting data helps after the model choice has been made.

GridSearchCV puts the CV loop in sklearn

from sklearn.linear_model import Ridge
from sklearn.model_selection import GridSearchCV

search = GridSearchCV(
    estimator=Ridge(),
    param_grid={"alpha": [0.1, 1, 100]},
    scoring="neg_root_mean_squared_error",
    cv=5,
    refit=True,
)
search.fit(X_train_housing, y_train_housing)
MODELRidge()

Fit a fresh Ridge model on the fitting rows of each fold.

CANDIDATESthree \(\alpha\) values

param_grid lists the settings we want to compare.

SELECTIONfive-fold RMSE

fit compares all candidates, selects one, then refits it on all training rows.

Read the selected Ridge model

CHOSEN SETTINGbest_params_

Which candidate \(\alpha\) won?

CV PERFORMANCE-best_score_

Change sklearn’s negative score back to positive RMSE.

FINAL FITbest_estimator_

The selected Ridge model is already refitted on all training rows.

from sklearn.metrics import root_mean_squared_error

best_alpha = search.best_params_["alpha"]
cv_rmse = -search.best_score_
final_model = search.best_estimator_

test_pred = final_model.predict(X_test_housing)
test_rmse = root_mean_squared_error(y_test_housing, test_pred)

Choose with CV, report on test once. Do not call fit again: search.fit(…) already did the final refit.

Diagnose Ridge with fitting and CV error

A 200-row sample of the housing training data makes the effect visible. Each point averages five fitting or validation folds.

Five-fold fit and validation RMSE for Ridge on 200 sampled housing training rows. Validation RMSE reaches its lowest value among the displayed settings at alpha 100; both errors grow under very strong regularization.

The lowest fitting error is at weak regularization. The lowest CV error among these candidates is at \(\alpha=100\).

Course housing training data · 200 rows sampled with seed 42 · 5-fold CV · illustrative diagnostic, not the final full-data search

Read the curve before selecting

WEAK PENALTY · \(\alpha=0.1\)fit 0.6818 · CV 0.8039

The fit is better than validation. A low training score alone is not the goal.

BEST OF THIS GRID · \(\alpha=100\)fit 0.7506 · CV 0.7802

Sacrificing some fitting accuracy improves validation prediction here.

TOO STRONG · \(\alpha=10{,}000\)fit 1.1625 · CV 1.1686

Both errors are high: useful relationships are being suppressed.

A validation curve is a diagnostic for this sample. The full-data search may select another \(\alpha\); it must still keep the final test set untouched.

Apply the workflow to rating prediction

03
CUHK emblem

The data roles stay the same when we return to user–item ratings.

Netflix Prize: data roles in practice

Netflix Prize diagram: training and probe ratings are known; quiz scores appear on a public leaderboard; test ratings determine the final score
KNOWN RATINGSTraining → fit
Probe → validate

Use these ratings while developing the model.

PUBLIC FEEDBACKQuiz → leaderboard

Labels are hidden, but the score can influence later choices.

FINAL CHECKTest → final score

Keep it outside the model-selection loop.

Diagram: Pantelis Monogioudis, Netflix Prize lecture notes. Split roles: Koren (2009), Section II.

For rating data, split pairs before fitting

OBSERVED TRIPLES

useritemrating

u1i24

u2i15

u1i42

u3i23

fold
FOLD TRAINlearn model values

global mean, user means, or item means from these triples only

predict
FOLD VALIDATIONpairs \((u,i)\) → ratings \(\widehat r_{ui}\)

compare with held-out ratings only after prediction

Compute learned quantities after the fold split.Computing them earlier leaks validation information into training.

Which future pair are we trying to predict?

PAIR-LEVEL HOLDOUTUsually known IDs, new pair

Remove selected ratings. Other ratings from these users and items may remain in fitting data.

Mostly asks: can we predict another interaction?
USER HOLDOUTEntire user is new

Keep every rating from selected users out of fitting. Their user means cannot be learned.

Asks: how do we serve a new user?
ITEM HOLDOUTEntire item is new

Keep every rating for selected items out of fitting. Their item means cannot be learned.

Asks: how do we serve a new item?

Choose the validation split to match the prediction situation. A random pair split can still contain a few unseen IDs, but it does not deliberately test cold start.

Our pair-level fold is mostly warm

In fold 1 of the course’s 0/1 rating data, “known” means the ID appears in the other four fitting folds.

97.5%of validation ratings have both a known user and a known item
validation pair count specific means available
known user + known item 9,980 user and item
new user + known item 35 item only
known user + new item 217 user only
new user + new item 1 none; use global mean

An overall pair-level RMSE is dominated by the warm rows. Report the cold cases separately if new IDs matter to the application.

Pick the split before the candidate

For each deployment question, which validation design would you use?

A · EXISTING CATALOGWill a returning user like another known film?

Hold out pairs; score predictions for known users and items.

B · NEW MEMBERSWhat can we recommend before a user has rated anything?

Hold out entire users; the user-mean path needs a fallback.

C · NEW FILMSHow will newly added films perform?

Hold out entire items; the item-mean path needs a fallback.

The same three-mean model can receive different scores under these splits because the question changes, not because the formula changes.

Three-mean RS: the weights are the choice

Return to the three-mean predictor from the previous lecture.

\[ \widehat r_{ui}=w_u\bar r_u+w_i\bar r_i+w_0\mu, \qquad w_u+w_i+w_0=1 \]

LEARNED IN EACH FOLDThree means

Compute the global, user, and item means from that fold’s fitting ratings. For an unseen ID, use that fold’s global mean.

CHOSEN BY CROSS-VALIDATIONThree weights

Try several user / item / global weight triples. Every candidate uses the same five folds.

GridSearchCV changes the weights; each fresh fit learns means only from its fitting fold.

GridSearchCV selects the RS weights

from sklearn.model_selection import GridSearchCV

weight_grid = [(1/3, 1/3, 1/3), (0.5, 0.3, 0.2),
               (0.3, 0.5, 0.2), (0.2, 0.2, 0.6)]

search = GridSearchCV(
    estimator=ThreeMeanRS(),
    param_grid={"weights": weight_grid},
    scoring="neg_root_mean_squared_error",
    cv=5,
    refit=True,
)
search.fit(X_train_rs, y_train_rs)
ESTIMATORThreeMeanRS()

Each fit learns means from four folds; predict scores the fifth.

CANDIDATESfour weight triples

weights is a constructor setting, just like Ridge’s alpha.

FINAL FITbest_estimator_

The winner is refitted on all training ratings.

Five-fold CV compares four weight candidates

For the course’s 0/1 rating split, GridSearchCV reports each candidate’s five validation RMSEs and their mean. Lower is better.

Candidate User / item / global Fold 1 Fold 2 Fold 3 Fold 4 Fold 5 CV mean
Equal 1/3, 1/3, 1/3 0.4658 0.4674 0.4681 0.4676 0.4663 0.4670
User-heavy 0.5, 0.3, 0.2 0.4618 0.4637 0.4647 0.4645 0.4623 0.4634
Item-heavy 0.3, 0.5, 0.2 0.4644 0.4667 0.4665 0.4655 0.4646 0.4656
Global-heavy 0.2, 0.2, 0.6 0.4751 0.4757 0.4768 0.4765 0.4758 0.4760

Choose (0.5, 0.3, 0.2) among these four. best_estimator_ already has the means refitted on all training ratings.

Course dataset/b-rs/train.csv · pair-level 5-fold CV via GridSearchCV(cv=5) · RMSE rounded to four decimals

How an estimator plugs into sklearn

We supply an estimator; sklearn reuses its methods during model selection.

PREPROCESSINGPrepare X, y

For RS, LabelEncoder maps IDs to lookup positions.

OUTPUTbest_estimator_

Ready for predict(X_test).

Define YourRS once. With BaseEstimator and the same fit / predict interface, it can use sklearn’s CV and search tools.

The complete workflow

FITlearns from known answers

VALIDATEchooses without touching test

TESTchecks the final frozen workflow

Next: use the same workflow to develop matrix factorization models.