Machine Learning

Model Selection and Hyperparameter Search

Model selection turns many candidate settings into one chosen procedure; dev/CV may choose, while test stays untouched for final evidence.

status: publishedimportance: criticaldifficulty 3/5math: undergraduateread: 20mlive demo

Concept Structure

Model Selection and Hyperparameter Search

01Intuition

Start with the picture, metaphor, or geometric mechanism.

02Math

Make the objects explicit and connect them with notation.

03Code

Mirror the equations with runnable implementation details.

04Interactive Demo

Manipulate the mechanism and watch the idea respond.

3prerequisites
2next concepts
3related links

Learning map

Model Selection and Hyperparameter Search
BeforeTrain/Dev/Test Splits, Cross-Validation, and LeakageNow4/4 sections readyTryManipulate one control and predict the visible change.NextEvaluation Pipelines

Object flow

4/4 sections readyAsk about thisResearch room
ConceptModel Selection and Hyperparameter SearchMachine Learning
5 sources attachedLocal snapshot ready
concept:machine-learning/model-selection-hyperparameter-search

Conceptual Bridge

What should feel connected as you move through this page.

Carry inTrain/Dev/Test Splits, Cross-Validation, and Leakage

Bring the mental model from Train/Dev/Test Splits, Cross-Validation, and Leakage; this page will reuse it instead of restarting from zero.

Work hereModel Selection and Hyperparameter Search

Model selection turns many candidate settings into one chosen procedure; dev/CV may choose, while test stays untouched for final evidence.

Carry outEvaluation Pipelines

The next edge should feel earned: use the demo prediction here before following Evaluation Pipelines.

Test the linkManipulate one control and predict the visible change.Then continue to Evaluation Pipelines
01

01

Intuition

Build the mental picture first so the rest of the page has something to attach to.

Section prompt

You are here because training one model is rarely the real experiment. In practice, you try many settings: polynomial degree, regularization strength, feature count, threshold, architecture size, prompt template, learning rate, batch size, or decoding rule. Model selection is the discipline that keeps that search from quietly becoming test-set memorization.

Before this, know train/dev/test splits, regularization, and why metrics can hide different costs. By the end, you should be able to run a small grid search, explain what the development set is allowed to choose, and say why the test set must stay untouched until the selected procedure is frozen.

Think of a hyperparameter grid as a menu of possible procedures:

  • degree 2, ridge λ=1\lambda=1
  • degree 5, ridge λ=0.1\lambda=0.1
  • degree 8, ridge λ=100\lambda=100
  • many more

Each candidate gets fit on training data. Then a development set or cross-validation estimate chooses which candidate to keep. That chosen candidate is not "the model that happened to have the lowest visible number." It is the result of a search procedure.

The dangerous move is test peeking:

  1. fit many candidates on train
  2. look at the test scores
  3. choose the candidate with the best test score
  4. report that same best test score

That score is no longer a final estimate. It is the score you optimized over. With enough candidates, one can look unusually good on the test set by luck. The model may not be better; you may have selected a lucky error bar.

The repair is simple and strict:

  • train data fits parameters
  • dev or cross-validation chooses hyperparameters
  • test data estimates the already chosen procedure once

If you need to tune and estimate performance on scarce data, use an outer evaluation loop such as nested cross-validation or keep a separate audit set. The invariant is not "never search." The invariant is "never report the data you searched over as if it were untouched evidence."

02

02

Math

Translate the story into symbols, assumptions, and a derivation you can inspect.

Section prompt

Let Λ\Lambda be a finite set of hyperparameter settings. A setting λΛ\lambda\in\Lambda might encode degree, penalty strength, feature count, threshold, or an architecture choice.

For each candidate, the training algorithm fits parameters using only training data:

f^λ=Aλ(Dtrain).\hat f_\lambda=A_\lambda(D_{\text{train}}).

The development risk estimate is

R^dev(λ)=1ndev(xi,yi)DdevL(f^λ(xi),yi).\widehat R_{\text{dev}}(\lambda) = \frac{1}{n_{\text{dev}}} \sum_{(x_i,y_i)\in D_{\text{dev}}} L(\hat f_\lambda(x_i),y_i).

Model selection chooses the setting with the lowest development estimate:

λ^=argminλΛR^dev(λ).\hat\lambda = \arg\min_{\lambda\in\Lambda} \widehat R_{\text{dev}}(\lambda).

Only after λ^\hat\lambda is fixed do we evaluate once on test:

R^test=1ntest(xi,yi)DtestL(f^λ^(xi),yi).\widehat R_{\text{test}} = \frac{1}{n_{\text{test}}} \sum_{(x_i,y_i)\in D_{\text{test}}} L(\hat f_{\hat\lambda}(x_i),y_i).

This estimates the selected procedure, not every candidate separately. The test set did not choose λ^\hat\lambda; it only measured the procedure after selection.

Cross-validation replaces one development split with several rotating validation folds. For KK folds F1,,FKF_1,\ldots,F_K inside the training budget,

R^cv(λ)=1ntraink=1KiFkL ⁣(Aλ(DtrainFk)(xi),yi).\widehat R_{\text{cv}}(\lambda) = \frac{1}{n_{\text{train}}} \sum_{k=1}^{K} \sum_{i\in F_k} L\!\left(A_\lambda(D_{\text{train}}\setminus F_k)(x_i),y_i\right).

Then choose

λ^cv=argminλΛR^cv(λ).\hat\lambda_{\text{cv}} = \arg\min_{\lambda\in\Lambda} \widehat R_{\text{cv}}(\lambda).

The crucial detail is fold locality. Preprocessing, feature selection, early stopping, calibration, and threshold choice must be learned inside each training fold when they are part of the candidate procedure.

Test peeking changes the selection rule to

λ~=argminλΛR^test(λ).\tilde\lambda = \arg\min_{\lambda\in\Lambda} \widehat R_{\text{test}}(\lambda).

The reported value

minλΛR^test(λ)\min_{\lambda\in\Lambda}\widehat R_{\text{test}}(\lambda)

is optimistically biased as an estimate of future performance because the minimum selected a favorable noise realization. More candidates usually create more chances to find a lucky low estimate. That does not mean large grids are forbidden. It means the grid must be selected using development/CV evidence and evaluated with untouched data.

Nested cross-validation separates the two jobs when no external test set is available. The inner loop chooses λ\lambda; the outer loop estimates the performance of the whole selection procedure.

03

03

Code

Keep the implementation aligned with the notation so the algorithm is legible.

Section prompt
import numpy as np

rng = np.random.default_rng(4)
degrees = range(1, 9)
lambdas = [0.1, 1.0, 10.0, 100.0]

def true_risk(degree, lam):
    log_lambda = np.log10(lam)
    return 0.12 + 0.015 * (degree - 4) ** 2 + 0.012 * (log_lambda - 0.3) ** 2

rows = []
for degree in degrees:
    for lam in lambdas:
        risk = true_risk(degree, lam)
        dev = risk + rng.normal(0, 0.035)
        test = risk + rng.normal(0, 0.035)
        audit = risk + rng.normal(0, 0.008)
        rows.append((dev, test, audit, degree, lam))

by_dev = min(rows, key=lambda row: row[0])
by_test = min(rows, key=lambda row: row[1])

for name, row in [("dev-selected", by_dev), ("test-peeked", by_test)]:
    print(name, {
        "degree": row[3],
        "lambda": row[4],
        "dev": round(float(row[0]), 3),
        "test": round(float(row[1]), 3),
        "audit": round(float(row[2]), 3),
    })

print("test-peek optimism:", round(by_test[2] - by_test[1], 3))

The code simulates noisy estimates for a degree/lambda grid. The development-selected candidate is the clean protocol. The test-peeked candidate is the invalid protocol: it chooses the lowest test number and then tries to report that same number as final evidence. The audit column stands in for fresh data that did not participate in the search.

04

04

Interactive Demo

Use direct manipulation to connect the explanation to a moving system.

Section prompt

Choose the search width and estimate noise. Before revealing the grid, predict which protocol will survive the fresh audit: development selection, test peeking, or a small-grid tie.

The grid shows candidate degree/lambda settings while the scores stay hidden. After reveal, the heatmap appears: one marker shows the candidate chosen by development score and another shows the candidate chosen by repeatedly reading test scores. The point is not that test peeking always chooses a more complex model. The point is sharper: once the test set chooses, its score is no longer untouched evidence.

Live Concept Demo

Explore Model Selection and Hyperparameter Search

The stage is code-native and interactive. Use it to test the explanation against the mechanism.

difficulty 3/5undergraduatecode-aligned
Demo Prediction Checkpoint

Manipulate one control and predict the visible change.

Commit to what Model Selection and Hyperparameter Search should make visible before reading the result.

After The First Pass

Turn the concept into an inspected object.

Once the invariant is visible in the intuition, math, code, and demo, use these panels to inspect the mechanism visually, check source support, practice the idea, and attach a grounded research question.

Mechanism Storyboard

See the idea move before the page explains it

Model selection turns many candidate settings into one chosen procedure; dev/CV may choose, while test stays untouched for final evidence.

Prediction open01 / Intuition
Prediction lens

Start with the picture, metaphor, or geometric mechanism.

Commit first

Before reading further, choose the kind of change Model Selection and Hyperparameter Search should make visible.

Visual Inquiry

Make the image answer a mathematical question

Model selection turns many candidate settings into one chosen procedure; dev/CV may choose, while test stays untouched for final evidence.

4/4 stages readyLive demo connected
Prediction

Which visible object should carry the first intuition?

Commit first

Pick the cue that should make Model Selection and Hyperparameter Search easier to reason about before the page gives the answer.

Source Grounding

Canonical references for the mechanism on this page.

course-notes · 2019CS229 Notes: Regularization and Model SelectionStanford CS229

Source for hold-out cross-validation, k-fold cross-validation, and choosing among model classes or hyperparameters using held-out empirical error.

Open source
book · 2023An Introduction to Statistical LearningJames, Witten, Hastie, Tibshirani, and Taylor

Source for validation-set and cross-validation approaches to estimating test error for model assessment and model selection.

Open source
documentation · 2026scikit-learn Example: Nested versus non-nested cross-validationscikit-learn developers

Source for the warning that using the same data to tune and evaluate can produce optimistically biased scores.

Open source
paper · 2010On Over-fitting in Model Selection and Subsequent Selection Bias in Performance EvaluationCawley and Talbot

Source for model-selection overfitting and biased performance evaluation when selection variance is ignored.

Open source

Claim Review

Model selection turns many candidate settings into one chosen procedure; dev/CV may choose, while test stays untouched for final evidence.

Status1 substantive review recorded

Claims without a substantive review badge still need exact source-support review.

Sources5 references

cs229-regularization-model-selection, islr-resampling-model-selection, sklearn-grid-search, sklearn-nested-cross-validation, cawley-talbot-selection-bias

Witnesses4 local objects

Use equation, code, and demo objects to check whether the source support is operational.

Substantively reviewedHyperparameter search is model selection: candidates may be fit on training data and compared on development or cross-validation scores, but repeated test-set peeking turns the test score into a tuned selection signal and makes the reported performance optimistic.Claim metadata: source checked

CS229 and ISLR support held-out/CV model selection; scikit-learn supports grid/randomized search and warns through nested-CV examples that tuning and evaluating on the same data biases estimates; Cawley and Talbot support selection overfitting and subsequent selection bias.

Sources: CS229 Notes: Regularization and Model Selection, An Introduction to Statistical Learning, scikit-learn User Guide: Tuning the hyper-parameters of an estimator, scikit-learn Example: Nested versus non-nested cross-validation, On Over-fitting in Model Selection and Subsequent Selection Bias in Performance EvaluationThe code and demo use finite toy loss estimates for a degree/lambda grid; they do not claim a universal bias magnitude, an optimal search algorithm, or that nested CV is always required for every operational setting.A bounded review summary is present; still check caveats and exact source scope.

Substantive local review after three GPT Pro/Oracle stalls. CS229, ISLR, scikit-learn, and Cawley-Talbot support the model-selection/test-peeking contract. Claude alternate review found no math/source/code/demo blockers after documented desktop/mobile QA; the toy witness caveat remains. Evidence: responses/model-selection-browser-source-qa-20260628.md.

Reviewer: codex-source-audit+claude-alt-review; reviewed 2026-06-28

Practice Loop

Try the idea before it explains itself

Model selection turns many candidate settings into one chosen procedure; dev/CV may choose, while test stays untouched for final evidence.

Readiness0/3 checks ready
Predict

Before touching the demo, predict one visible change that should happen in Model Selection and Hyperparameter Search.

Hint 1

Reveal when your model needs a nudge.

Hint 2

Reveal when your model needs a nudge.

Hint 3

Reveal when your model needs a nudge.

Object research drawerClose
ConceptModel Selection and Hyperparameter SearchMachine Learning

Research Room

Attach the question to an exact object

Pick the concept, equation, source, code witness, claim, misconception, or demo state before asking for help. The handoff stays grounded to that object.
Next local actionNo local draft saved yet

Open the draft below to save one note and next action in this browser.

conceptMachine Learning

Model Selection and Hyperparameter Search

Anchored question

What is the smallest example that makes Model Selection and Hyperparameter Search click without losing the math?

Local action draftNo local draft saved yetExpand only when ready to capture one local next action
Local action draft

This draft stays locally in this browser for concept:machine-learning/model-selection-hyperparameter-search.

No local draft saved.
Evidence to inspect
  • Source ids to inspect: cs229-regularization-model-selection, islr-resampling-model-selection, sklearn-grid-search, sklearn-nested-cross-validation, cawley-talbot-selection-bias
  • Definition, prerequisite, and contrast concept links
  • The equation or code witness that makes the concept operational
  • One demo state that shows the invariant instead of a slogan
What would resolve this
  • The learner can state the mechanism in their own words
  • The learner can name the prerequisite that would repair confusion
  • The learner can predict how the mechanism changes under one perturbation
Grounded AI handoff

I am working in Continuous Function's research reading room. Object: concept - Model Selection and Hyperparameter Search Object key: concept:machine-learning/model-selection-hyperparameter-search Context: Machine Learning Anchor id: concept/concept-notebook/machine-learning/model-selection-hyperparameter-search Open question: What is the smallest example that makes Model Selection and Hyperparameter Search click without losing the math? Evidence to inspect: - Source ids to inspect: cs229-regularization-model-selection, islr-resampling-model-selection, sklearn-grid-search, sklearn-nested-cross-validation, cawley-talbot-selection-bias - Definition, prerequisite, and contrast concept links - The equation or code witness that makes the concept operational - One demo state that shows the invariant instead of a slogan What would resolve this: - The learner can state the mechanism in their own words - The learner can name the prerequisite that would repair confusion - The learner can predict how the mechanism changes under one perturbation Answer as a careful research tutor: stay source-grounded, separate verified evidence from assumptions, name the relevant math objects, and end with one next action.

Open source object
concept/concept-notebook/machine-learning/model-selection-hyperparameter-search concept:machine-learning/model-selection-hyperparameter-search