Choose a Setting with Cross-Validation
A model has settings you choose before it trains, such as how deep a decision tree may grow. To pick a good one, you compare the scores of the candidates. A score measured on one small validation part moves up and down with the rows that happened to land in it, so a small difference between two settings may mean nothing. Cross-validation measures each setting several times on different rows, and the spread of those measurements tells you which differences are real, all without touching the test set.
One validation part gives a noisy score
A validation score is a share of right answers on a few hundred rows. Each of those rows is either easy or hard for the model, and a random split decides which ones you get. Draw the validation rows again with a different seed, and you get a different mix of easy and hard rows, so the score changes even though the model and its setting stayed the same.
The size of that wobble follows from the arithmetic. With 200 validation rows, every single row is worth half a percentage point of accuracy. If the split swaps four rows the model gets right for four it gets wrong, the score drops by two points. The chart shows what that looks like for one model with one fixed setting, scored on five different random splits of the same table (the numbers are an illustration of the effect, not a measurement).
- 0.78 to 0.82: four points of wobble
- 0.70
- 0.75
- 0.80
- 0.85
- validation accuracy
- Split A
- Split B
- Split C
- Split D
- Split E
- 0.78
- 0.81
- 0.79
- 0.82
Now imagine comparing two settings with one split each: one scores 0.80 and the other 0.81. The one-point gap is smaller than the wobble you just saw from reshuffling alone, so it could come entirely from the rows the split happened to pick. A single validation score cannot tell you whether the gap is real. It also judges the model on only a fifth or so of the rows. Both problems have the same fix: measure more than once.
True or false?
If one setting scores 0.81 on a validation part and another scores 0.80, the first one is better.
False. A different random split could reverse the order. A one-point gap on a few hundred rows is within the noise that the choice of rows alone produces.
The same model with the same setting can get a different validation score when only the seed of the split changes.
True. The seed decides which rows land in the validation part, and some rows are easier to predict than others.
K-fold cross-validation: every row is validated once
Cross-validation turns one measurement into several. You cut the rows into k parts of equal size, called folds, and train the model k times. Each round holds out a different fold, trains a fresh model on the other k - 1 folds and scores it on the fold it held out. With k = 5, each round trains on four fifths of the rows and validates on the remaining fifth.
- Fold 1
- Fold 2
- Fold 3
- Fold 4
- Fold 5
- Score
- Round 1
- Round 2
- Round 3
- Round 4
- Round 5
- held out
- 0.78
- 0.80
- 0.81
- 0.79
- 0.82
- Grey folds train the model, the held-out fold scores it
Read the picture down a column: every fold is held out in exactly one round, so every row is used for validation once and for training in the other rounds. No row is wasted on a single fixed validation part, and no row is ever scored by a model that trained on it. The price is time: five rounds mean five models trained instead of one.
In scikit-learn, cross_val_score runs all the rounds for you. It takes the model, the features and the labels, and returns an array with one score per fold. You pass it the rows you are allowed to learn from and keep the test rows out of it entirely, because cross-validation replaces the fixed validation part, not the test set.
from sklearn.model_selection import cross_val_score
from sklearn.tree import DecisionTreeClassifier
# X and y: the features and labels of the rows that are not test data
model = DecisionTreeClassifier(max_depth=3, random_state=0)
scores = cross_val_score(model, X, y, cv=5)
print(scores) # five accuracies, one per fold
print(scores.mean()) # their average
print(scores.std()) # their spreadA few details of this call matter in practice:
cv=5asks for 5 folds, which is also what you get when you leavecvout. Five or ten folds are the usual choice.- For a classifier with a yes-or-no label, a whole number for
cvbuilds stratified folds: each fold keeps about the same share of each answer as the whole set of rows. - Without a
scoringargument, each fold score is the model's default score, which for a classifier is accuracy. - The folds are cut in the order the rows come in, without shuffling, so the same call gives the same folds every time. That is fine when the rows are already in random order, for example because they come out of a random split. If the file is sorted (by date, by customer id), each fold covers one stretch of it, the fold scores no longer measure the same thing, and shuffling first can be essential. To shuffle the rows first, with a fixed seed, pass
cv=StratifiedKFold(n_splits=5, shuffle=True, random_state=0)(imported fromsklearn.model_selection). - A decision tree has a little randomness of its own while it trains, so it gets
random_state=0too. With both fixed, the scores come out the same on every run.
True or false?
In 5-fold cross-validation, every row is used for validation exactly once.
True. Each row sits in one fold, and each fold is held out in exactly one of the five rounds.
`cross_val_score` returns a single averaged score.
False. It returns an array with one score per fold. You compute the mean and the spread from that array yourself.
With cross-validation, the test set is no longer needed.
False. Cross-validation replaces the fixed validation part. A test set is still kept aside for the final measurement, after every choice is made.
Mean and spread: the estimate and its uncertainty
Five fold scores give you two useful numbers. Their mean, the ordinary average, is the estimate of how the model does on rows it has not seen. It rests on every row instead of one fifth of them, so it moves much less from one split to another than a single validation score does.
Their spread says how far the fold scores sit from that mean, and so how much any single measurement can be trusted. The usual measure of spread is the standard deviation, which is what scores.std() computes: take each score's distance from the mean, square it, average those squares, and take the square root. The result is roughly the typical distance of one fold score from the mean.
the estimate
the standard deviation of the k fold scores
With the fold scores 0.78, 0.80, 0.81, 0.79 and 0.82, the mean is 0.80. The distances from it are -0.02, 0, 0.01, -0.01 and 0.02; their squares average to 0.0002, and the square root of that is about 0.014. So the model scores about 0.80, and a single fold could easily land a point or two either side.
The spread is what makes a comparison readable. Here are the fold scores of two settings of the same model, measured on the same five folds:
fold accuracy
- Setting A
- Setting B
Setting B has a mean of 0.805 and setting A one of 0.800, a gap of half a point, while the spreads are about 0.010 for B and 0.014 for A. The two boxes overlap almost completely: what separates them is smaller than what separates one fold from the next. A practical reading rule follows from that: when two means differ by less than the spread, treat them as equal. It is a rule of thumb for reading scores, not a formal statistical test, but it stops you from picking a winner that a different split could overturn.
For the comparison to be fair, every setting has to be scored on the same folds. Leaving the rows unshuffled gives the same folds every time, and so does shuffling them with the same fixed seed.
True or false?
A mean of 0.812 beats a mean of 0.809 when both settings have a spread of about 0.015.
False. The gap of 0.003 is far smaller than the spread, so the two settings are equal as far as these scores can tell.
A small spread means the fold scores agree closely with each other, so their mean can be trusted more.
True. When every fold gives nearly the same score, the result depends little on which rows were held out.
Hyperparameters: settings you choose before training
A model has two kinds of numbers. Some it learns: a decision tree's questions and the thresholds in them are chosen by fit from the training rows. Others you choose before training starts, and the model never changes them. These settings are called hyperparameters, and in scikit-learn you pass them when you create the model, as in DecisionTreeClassifier(max_depth=3).
| Aspect | Hyperparameter | Learned by the model |
|---|---|---|
| Example | the maximum depth of a tree | which question each node asks |
| Chosen by | you | fit, from the training rows |
| Fixed | before training | during training |
| In code | an argument when the model is created | stored on the fitted model |
Since training cannot choose a hyperparameter, you choose it by experiment: try each candidate value, score it with cross-validation, and compare the means using their spreads. For a tree's depth, that is a short loop. max_depth=None means no limit: the tree keeps splitting until its leaves are pure or too small to split.
for depth in [2, 4, 6, None]:
model = DecisionTreeClassifier(max_depth=depth, random_state=0)
scores = cross_val_score(model, X, y, cv=5)
print(depth, round(scores.mean(), 3), round(scores.std(), 3))Suppose the loop prints the results below (made-up numbers that show the pattern). The deepest tree, with no limit, falls behind because it learns its training folds too closely. Depths 4 and 6 are the best, but their means are only 0.002 apart while each has a spread of about 0.010.
| max_depth | Mean | Spread | Reading |
|---|---|---|---|
| 2 | 0.781 | 0.012 | clearly lower |
| 4 | 0.795 | 0.010 | tied for best, simpler: keep |
| 6 | 0.797 | 0.011 | tied for best |
| None | 0.731 | 0.014 | clearly lower |
When the best scores tie within their spread, keep the simpler setting. A shallower tree asks fewer questions, so it is easier to read and explain, and it has less room to learn noise from its training rows. Here that is depth 4.
None of this touches the test set. If you tried each depth on the test rows and kept the one that scored best there, the test score would have helped make the choice, and it would no longer be an honest measurement of rows the model never influenced. Even the winning cross-validated mean is a little optimistic: it was kept because it was the highest of several noisy numbers, so some luck helped it to the top. The test set, kept aside until every choice is made, is what gives the final, honest number.
True or false?
The maximum depth of a decision tree is learned by `fit` from the training rows.
False. It is a hyperparameter: you set it when you create the model, and `fit` then learns the questions within that limit.
If depth 4 and depth 6 have means within each other's spread, choosing depth 4 is the sensible choice.
True. The scores cannot tell them apart, and the shallower tree is easier to read and less likely to have learned noise.
Trying every depth on the test set and keeping the best gives an honest estimate for new rows.
False. The test score then took part in the choice, so it is tuned to those rows and overstates how the model does on new ones.