Concepts / Cross-Validation

Cross-Validation

The spread of scores across folds is itself informative.

  • Programming
Interactive lab

Try it: K-Fold Cross-Validation and Model Selection

How hold-out and k-fold cross-validation choose among candidate models: each fold takes a turn as the validation set, the fold errors are averaged, the lowest average picks the model, and only then is the untouched test set used once — while tuning on the test set would report an optimistic number.

How it works

  1. Set 10 test points aside; they take no part in any choice.
  2. Optionally shuffle the 20 development points (seeded), then cut them into k folds (hold-out: one chunk validates, the rest trains).
  3. For every round, train each candidate polynomial on the other folds and measure its validation MSE on the held-out fold.
  4. Average each candidate's fold errors (with repeated shuffling: average the p run scores; p × k fits per candidate).
  5. Select the candidate with the lowest average, retrain it on all development points, and evaluate it once on the test set.
  6. For contrast, show which candidate the test set itself would have picked — that figure is leaked and optimistic.

Default run (12 steps): 20 development points (sorted by x as they arrived) and 10 test points set aside. Candidates: polynomial degree 0, 1, 2, 3, 4, 5, 6. Plan: 5-fold cross-validation, shuffled with seed 1 → 5 fits per candidate (p × k = 1 × 5), 35 in total. … 5-fold cross-validation picks degree 3 (score 0.0768); its honest test MSE is 0.0889. Picking by test error would report degree 4 at 0.0868 — a leaked, optimistic figure.

Simplified: One fixed toy dataset (20 development + 10 test points from sin(2πx) with noise) and polynomial least squares of degree 0–6 as the candidate models. Shuffling uses a seeded mulberry32 Fisher–Yates; folds are contiguous chunks like scikit-learn's KFold. Hold-out uses the first of k chunks as the validation set.

Educational simulation

Loading the simulation…

The Belief That Cross-Validation Produces a Model

Many learners first meet cross-validation as a more careful version of splitting data once. It runs the model several times, and it is easy to conclude that the end result is a stronger model, ready to be used on new data. This article looks at what cross-validation actually gives you, why it is valuable, and where its limits lie. The first step is to name the belief that causes the most trouble.

What do you think happens?

Suppose you run a cross-validation function on a dataset, and it finishes. Do you have a trained model that you can now use to predict labels for brand-new examples, or do you have something else?

  • A trained model that can predict labels for brand-new examples

  • Accuracy estimates that describe how the algorithm is likely to perform, but no model to apply to new data

Reveal answer
Answer:

Accuracy estimates, not a model you can apply to new data.

Cross-validation judges the algorithm. The models it builds along the way are scaffolding that is discarded once their scores are recorded. It answers how well a particular algorithm, trained on a particular dataset, is likely to generalize.

Why One Split Can Mislead

When you build a model, you want to know how well it will perform on data it has never seen. A common first step is to divide your data into a training set, used to build the model, and a test set, used to measure its accuracy. That measurement depends on which rows happened to land in the test set. A different random split could produce a noticeably different accuracy number, so a single split gives you one estimate that may be lucky or unlucky.

The function train_test_split shuffles the data and divides it, so the outcome depends on which examples landed on each side. Picture two draws. In one, all the difficult-to-classify examples go into the training set. The test set then contains only easy cases, and the accuracy looks impressively high. In the other, the difficult examples all land in the test set, and the accuracy looks disappointingly low. In both cases the score tells you more about the draw than about the algorithm.

Partitioning Data into Folds

The most commonly used version is k-fold cross-validation, where k is a number chosen by the user, usually 5 or 10. The first step is always the same: the data is partitioned into k parts of approximately equal size. Each part is called a fold. In five-fold cross-validation, the data becomes five folds. In the simplest arrangement, the first fifth of the data forms the first fold, the second fifth forms the second fold, and so on.

The word approximately matters. When the number of rows does not divide evenly by k, the folds cannot all be exactly the same size, so they are made as close as possible. Once the folds exist, a sequence of models is trained. Each model follows the same pattern: one fold is set aside as the test set, the model is built from the data in all the other folds, the accuracy is measured on the held-out fold, and that accuracy is recorded.

  1. 1
    Partition the dataset into k folds of approximately equal size.
  2. 2
    Set one fold aside as the test set.
  3. 3
    Train a model on the remaining k minus 1 folds.
  4. 4
    Evaluate that model on the held-out fold and record the accuracy.
  5. 5
    Choose a different fold as the test set and repeat until every fold has been the test set exactly once.

Rotating the Test Fold

The key idea is that every row gets a turn in the test set. No single arrangement of rows decides the final score. The diagram below shows how five-fold cross-validation moves through the data. Each round holds out one fold for testing and trains on the remaining four.

Round 1Test: Fold 1Round 2Test: Fold 2Round 3Test: Fold 3Round 4Test: Fold 4Round 5Test: Fold 5
In five-fold cross-validation, which fold is the test set in each round, and how does that choice change from round to round until every example has been tested once?

Notice what the rotation guarantees. Each fold appears in the test role exactly once, so every example is tested exactly once. Across the five rounds, every example also appears in the training role four times, because it is used for fitting in every round except the one where it is held out.

Worked example

Tracing a Ten-Row Dataset Through Five Folds

A dataset has 10 rows labeled A through J. Five-fold cross-validation splits them into five folds of two rows each: {A, B}, {C, D}, {E, F}, {G, H}, {I, J}. Which rows are used for training and testing in each round, and how many times is each row tested?

  1. 1
    Round 1

    Fold {A, B} is the test set. The model trains on C, D, E, F, G, H, I, J, which is 8 rows. The accuracy measured on A and B is recorded.

  2. 2
    Round 2

    Fold {C, D} is the test set. The model trains on A, B, E, F, G, H, I, J. One accuracy value is recorded.

  3. 3
    Round 3

    Fold {E, F} is the test set. The model trains on A, B, C, D, G, H, I, J. One accuracy value is recorded.

  4. 4
    Round 4

    Fold {G, H} is the test set. The model trains on A, B, C, D, E, F, I, J. One accuracy value is recorded.

  5. 5
    Round 5

    Fold {I, J} is the test set. The model trains on A through H. One accuracy value is recorded.

  6. 6
    Check

    Each row was in the test set exactly once, and in the training set in the other four rounds.

Result

Five models are trained, five accuracy values are collected, and every row is tested exactly once. Each model trains on 8 of the 10 rows.

Counting Models and Accuracy Values

Five-fold cross-validation trains five models and collects five accuracy values. The rounds run in sequence, and each round produces exactly one accuracy value. The diagram below traces that progression from the first round to the final result.

Round 1Train on 4 folds, score 1fold5 accuracy valuesone per roundRound 2Train on 4 folds, score 1foldRound 3Train on 4 folds, score 1foldRound 4Train on 4 folds, score 1foldRound 5Train on 4 folds, score 1foldnext foldnext foldnext foldnext foldcollected
How many models are trained, how many accuracy values come out, and how do the training and test rounds line up step by step?

The choice of k is set by the user. A larger k means more folds, so each fold is smaller and more models are trained. A smaller k means fewer, larger folds. The method itself stays the same in both cases: partition, rotate the test fold, train, score, and collect the results.

Training Share in Five and Ten Folds

A typical single split reserves about 25 percent of the data for evaluation and trains on the remaining 75 percent. With cross-validation, each iteration trains on k minus 1 of the k folds, so the training share per model is $\frac{k-1}{k}$ of the dataset. The test share for each round is $\frac{1}{k}$.

SetupFolds (k)Training share per modelTest share per model
Single train/test split (typical)not applicableabout 75%about 25%
Five-fold cross-validation580%20%
Ten-fold cross-validation1090%10%

Share of the dataset used for training and testing in each model

Ten-fold evaluation therefore lets each model fit on more of the data than five-fold evaluation does, at the price of more training runs. The gain is in how efficiently the data is used, not in any change to what the final score means.

Repeated Splits Versus a Single Split

Cross-validation evaluates generalization performance by splitting data repeatedly and training multiple models. That is more stable than a single train-test split, because the final picture is built from several different arrangements of the same rows rather than one arrangement. The diagram below compares the two approaches side by side.

Accuracy values1Accuracy values5Test shareabout 25%Test share20% per roundExamples testedonly the test rowsExamples testedevery example once
How does one lucky or unlucky split produce an extreme accuracy score, and how does averaging across several different splits make the estimate more stable?

The spread of scores across folds is itself informative. The source reports that five-fold cross-validation on the iris dataset produced accuracies anywhere between 90 and 100 percent. That spread shows how sensitive the model is to which examples it trains on, and it gives a sense of the worst and best cases you might see when the model meets new data.

What Cross-Validation Does Not Return

Cross-validation answers a narrower question than the one learners often have in mind. It asks how well a particular algorithm, trained on a particular dataset, is likely to generalize. The answer comes from repeatedly training on part of the data and scoring on the part that was held back. The models built during the process are discarded once their scores are recorded.

Accuracy estimatesone per roundFinal modeltrained on all dataModelsdiscardedPredictionsfor new examplesApplied to new datanoApplied to new datayes
What is produced by cross-validation (accuracy estimates) versus what is produced by training a final model on all the data, and which of these can be applied to new data?

The Main Cost of Cross-Validation

Every benefit above has a price. The main disadvantage of cross-validation is increased computational cost. Because it trains k models instead of one, cross-validation is roughly k times slower than a single split of the data. A five-fold evaluation therefore takes about five times the training work, and a ten-fold evaluation about ten times.

The extra work comes entirely from repetition. Each round is a full training run on a different set of folds, so the cost grows with the number of rounds you choose to run.

Mistakes Beginners Make

  • Common mistake

    Believing that cross-validation leaves you with a model to use on new data

    What it looks like

    Running a five-fold evaluation and then calling predict on fresh rows with the result.

    Why it fails

    The function returns accuracy values. The fold models are discarded once their scores are recorded.

    Do this instead

    Use the scores to judge the algorithm, then train a final model on all the data if you need one for new predictions.

  • Common mistake

    Assuming a single split is an accurate estimate because it is random

    What it looks like

    Reporting 98 percent accuracy from one split and treating it as the expected performance.

    Why it fails

    A lucky draw that puts easy cases in the test set inflates the score, and an unlucky draw deflates it.

    Do this instead

    Repeat the split across folds and look at the spread of scores as well as their mean.

  • Common mistake

    Thinking that more folds always means a better estimate of the same thing

    Why it fails

    More folds increase the share of data used per training run and the number of models, which raises computational cost roughly in proportion to k.

    Do this instead

    Choose k with the cost in mind. The source describes 5 or 10 as common choices.

  • Common mistake

    The folds are not always exactly equal in size, because the number of rows may not divide evenly by k

Practice: Trace a Five-Fold Run

EASY

A dataset has 20 rows and you run five-fold cross-validation. How many models are trained, how many accuracy values are collected, how many rows does each model train on, and how many times is each row used as test data?

Hints
  • Five folds means five rounds, and each round trains one model.
  • Each fold holds 20 divided by 5 rows, so each model trains on the other four folds.
  • Every fold takes a turn as the test set exactly once.
MEDIUM

Compare five-fold and ten-fold cross-validation on the same 20-row dataset. What is the training share per model in each case, and what is the relative training cost?

Hints
  • The training share is k minus 1 divided by k.
  • Ten-fold trains ten models, so compare that count with five.

Key Takeaways

  • Cross-validation evaluates how well a particular algorithm, trained on a particular dataset, is likely to generalize. It does not return a model you can apply to new data.
  • A single train/test split can give an unrealistically high or low score because of the random draw. K-fold cross-validation partitions the data into k folds and rotates the test fold so every example is tested exactly once.
  • In five-fold cross-validation, five models are trained and five accuracy values are collected. Each model trains on 80 percent of the data, and ten-fold trains on 90 percent.
  • The main cost is computational: k models are trained instead of one, so the work is roughly k times that of a single split.
  • The spread of scores across folds shows how sensitive the model is to its training data and helps estimate best-case and worst-case performance.

Related concepts

More concepts starting with C