Concepts / Summarizing Cross-Validation Scores

Summarizing Cross-Validation Scores

cross_val_score evaluates a model with cross-validation and takes the model, the data, and the target as its main parameters.

  • 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…

Running a First Evaluation

Cross-validation gives you a way to judge how well a model is likely to perform by testing it on several different slices of your data. In scikit-learn, the function cross_val_score runs that whole process for you. You hand it a model, the data, and the labels, and it returns the evaluation results. This article starts with one complete run, then explains how the printed output is produced, what each number means, and how the same ideas extend to tuning a model with a grid search.

Read the program below once before running it. It loads the iris dataset, creates a logistic regression model, and asks scikit-learn to evaluate that model with cross-validation. Then look at what it prints. The rest of the article explains how that printed line is produced.

python
Notes on the code
  • X holds the features and y holds the labels for the iris flowers
  • The model is an untrained logistic regression object
  • cross_val_score is called with no cv argument, so the default number of folds is used
  • The returned array is printed as one line

Before you run it, notice the three objects in the call: the model, the data, and the labels. Those three inputs are all cross_val_score needs to carry out the evaluation. The question to ask next is what the function hands back.

What do you think happens?

With no cv argument, how many values will the printed array contain?

  • one

  • three

  • five

  • one for each of the 150 flowers

Reveal answer
Answer:

three

By default cross_val_score performs three-fold cross-validation and returns one accuracy value per fold, so the array holds three values. Pay attention to the length of the array, not only to its contents, because the length is the first thing to check when an output looks unexpected.

The Three Inputs to the Call

The first three positional arguments of cross_val_score are the model to evaluate, the data (the features), and the target (the ground-truth labels). The model is whatever estimator you want to test. The data is the feature table, and the target holds the correct answer for each row. The function uses these three pieces to repeatedly train the model on some portion of the data and test it on another portion.

python
Notes on the code
  • model: the estimator to evaluate
  • X: the data, the features
  • y: the target, the ground-truth labels
  • cv: optional, controls how many folds are used

The cv argument is optional. When you leave it out, the function uses its default of three folds. When you pass a value, that value sets the number of folds, which is the subject of a later section.

How Folds Rotate

Cross-validation evaluates a model by splitting the data into folds and then training and testing on different subsets. In K-fold cross-validation, the data is split into k subsets. The model is evaluated once for each fold, so the function produces one score per fold. Each fold takes a turn as the held-out test portion, and the remaining folds are used for training during that round.

Round 1test on fold 1, train onfolds 2 and 3Round 2test on fold 2, train onfolds 1 and 3Round 3test on fold 3, train onfolds 1 and 2Per-fold scoresone accuracy value perroundnext foldnext foldcollect results
In each round, which fold is held out for testing, which folds train the model, and what is collected at the end?

The diagram shows the three-fold case, which is the default. Each fold is held out exactly once, and the model is trained on the remaining folds each time. The result is not one number for the whole procedure. It is a list of per-fold results, and that list is what the program prints.

Mapping Scores to Fold Positions

The returned array is ordered by fold. The first element is the result from the round where the first fold was held out, the second element comes from the round where the second fold was held out, and so on. Because each value is the result of one held-out fold, the array length always matches the number of folds.

scores[0]accuracy when fold 1 isheld outscores[1]accuracy when fold 2 isheld outscores[2]accuracy when fold 3 isheld out
Which element of the returned array corresponds to which fold when there are three folds?

This mapping is the reason the array is more informative than a single average. If one element is much lower than the others, you know which held-out portion caused the drop, and you can investigate that part of the data rather than only seeing an overall number.

Changing the Number of Folds

The cv parameter changes the number of folds. The rule for the output stays the same: the length of the returned array equals the number of folds. The next example keeps the same model and data and passes cv=5. Predict the length of the array before reading the answer.

python
Notes on the code
  • The model and data are unchanged from the first run
  • cv=5 asks for five folds
  • len returns how many values are in the array
Worked example

Predicting the output when cv changes from 3 to 5

The same model and data are passed to cross_val_score with cv=5. How many values are returned, and what does each one represent?

  1. 1
    Read the cv value

    cv=5 sets the number of folds to five instead of the default three.

  2. 2
    Apply the length rule

    The array length matches the number of folds, so the array holds five values.

  3. 3
    Identify what each value means

    Each value is the accuracy from one round in which one of the five folds was held out and the other four were used for training.

  4. 4
    Check the fold sizes

    With five folds, each held-out portion is a smaller slice of the data than it was with three folds, and each training set is built from four of the five folds.

Result

The printed array has five accuracy values, one per held-out fold, in fold order.

Changing cv does not change what the individual numbers mean. It changes how many rounds of training and testing take place, which changes how many values appear in the output. If the length of the output does not match the cv value you passed, the cv argument is the first place to look.

Tracing an Unexpected Output

When an output does not match your expectation, the useful question is where the divergence began. Rather than rereading the whole program, work through the chain in order. Each step narrows the search.

  1. 1
    Check the inputs you passed: the model, the data, and the labels.
  2. 2
    Check the value of cv, either the default or the value you set.
  3. 3
    Count the number of values in the returned array and compare it with the number of folds.
  4. 4
    Only if the length is correct, examine the values themselves.

Why Heat Maps Summarize a Grid Search

A grid search tries many parameter settings and records a cross-validation result for each one. It stores one row of results per setting, including the score from every split, along with the mean and standard deviation across those splits. When the search covers two parameters, the natural picture is a heat map: one axis holds one parameter, the other axis holds the second parameter, and each cell is colored by its mean score. The heat map turns a long table of numbers into a picture you can scan for patterns.

Light colors stand for high accuracy and dark colors stand for low accuracy. Each cell is one cross-validation result for one parameter setting. Reading the heat map therefore means asking where the light cells are, where the dark cells are, and how those regions are arranged relative to the two axes.

What do you think happens?

If a heat map is the picture of a 6 by 6 grid search, how many mean scores must be available to draw it?

  • 6

  • 12

  • 36

  • 6 squared plus 6

Reveal answer
Answer:

36

A 6 by 6 grid has 36 cells, so the flat list of mean scores must contain exactly 36 values for the reshape step to work.

Finding the Best and Worst Cells

Worked example

Locating the best setting on a heat map

A heat map shows mean cross-validation accuracy for a two-parameter grid. The lightest cell is in the top right corner, and the darkest cell is in the bottom left. Where do the best and worst settings appear, and what should you check next?

  1. 1
    Map the axes

    Identify which parameter runs along the rows and which runs along the columns, so each cell can be traced back to a pair of settings.

  2. 2
    Locate the lightest cell

    The lightest cell marks the highest mean accuracy, so the top right corner is the best setting in this grid.

  3. 3
    Locate the darkest cell

    The darkest cell marks the lowest mean accuracy, so the bottom left corner is the worst setting.

  4. 4
    Check the border

    The best cell sits in a corner, which is on the edge of the grid. That is a warning: the true peak may lie beyond the range you searched.

Result

The best setting is at the top right, but because it touches the border, widen the search range before accepting the result.

Flat Heat Maps: Ranges Versus Parameters

Many learners see a uniform heat map and assume the whole experiment is broken, so they throw it away and start over with a different model. That reaction is often premature. A uniform picture is a clue, and it points to a small set of specific causes that you can check one at a time. A uniform heat map can signal poorly chosen ranges or scaling, or a parameter with little effect, so it is a prompt to investigate rather than proof of failure.

The patterns of color are the main evidence. A constant color across the whole grid suggests the search ranges or scaling need attention. Color that changes across columns but stays constant down each column suggests that one parameter drives the score while the other has little effect. Color that changes along both axes suggests that both parameters matter. Each pattern points toward a different next step.

Whole grid one colorCheck ranges and scalingColor changes acrosscolumnsOne parameter drives thescoreColor changes alongboth axesBoth parameters affect thescore
Which heat map pattern points to poorly chosen ranges, which points to one parameter dominating, and which points to both parameters mattering?
PatternWhat it suggestsNext step
Constant color everywherePoorly chosen ranges or scaling, or no parameter with much effectCheck the search ranges and scaling before anything else
Color changes across columns onlyOne parameter has a strong effect and the other has little effectFocus the search on the parameter that changes the score
Color changes along both axesBoth parameters influence the scoreLook at where the best region sits and whether it touches an edge

Reading flat and striped heat maps

The source compares three heat maps produced from deliberately misspecified search grids. Each has a different arrangement of colors, and each arrangement points to a different diagnosis. Naming the pattern is the first step toward deciding what to change. The same model and data can give very different pictures when the ranges change, which is why the spacing of the values matters as much as the choice of model.

Adjusting the Grid Without the Test Set

Adjusting the parameter grid after looking at cross-validation results is a legitimate and useful habit. The heat map guides those adjustments: it shows where accuracy changes, where it does not, and where the best region is pressing against the edge of the search. The adjustments should be made using cross-validation scores on the training data, which is where the heat map comes from. The final test set is kept out of this loop so that it still gives an honest estimate at the end.

  1. 1
    Read the heat map and name its pattern: constant color, striped, or changing along both axes.
  2. 2
    If the best region touches the border, widen the range on that side of the grid.
  3. 3
    If the whole grid is one color, check the spacing and scaling of the parameter values before concluding the model is wrong.
  4. 4
    If one parameter drives the score and the other does not, concentrate the next search on the parameter that matters.
  5. 5
    Rerun the search and evaluate the new grid using cross-validation scores on the training data, leaving the final test set untouched.

Common Mistakes With Cross-Validation Output

  • Common mistake

    Treating the returned array as a single overall score

    What it looks like

    Reporting the first value as the result of the whole evaluation.

    Why it fails

    Each value is the result of one held-out fold, so the array is a list of per-fold results rather than one overall score.

    Do this instead

    Read every value in the array, and summarize the list if you need one number, such as its mean.

  • Common mistake

    Expecting the array length to ignore the cv argument

    What it looks like

    Passing cv=5 and still expecting three values because that is the default.

    Why it fails

    The cv parameter sets the number of folds, and the length of the returned array matches that number.

    Do this instead

    Predict the length from the cv value before running the code, then compare.

  • Common mistake

    Discarding a uniform heat map immediately

    What it looks like

    Starting over with a new model when every cell has nearly the same color.

    Why it fails

    A uniform picture can come from poorly chosen ranges or scaling, or from a parameter with little effect, so it is a clue rather than proof of failure.

    Do this instead

    Check the ranges and scaling first, then look at which parameter, if any, changes the score.

  • Common mistake

    Accepting a best setting that sits on the edge of the grid

    What it looks like

    Choosing the lightest corner cell without questioning whether a better value lies beyond it.

    Why it fails

    A best region touching the border suggests the true peak may be outside the searched range.

    Do this instead

    Widen the search range in that direction before accepting the result.

Checking Your Understanding

EASY

A colleague calls cross_val_score with cv=10 and reports the first value of the returned array as the model's accuracy. Predict how many values the array contains, and explain why reporting only the first value is misleading.

Hints
  • Recall the rule that the array length matches the number of folds.
  • Recall that each value comes from a different held-out fold.
MEDIUM

A heat map of mean scores for two parameters is nearly one color everywhere, but the best cell sits on the bottom edge of the grid. Which two checks should you make before deciding the model is unsuitable, and why?

Hints
  • Consider whether the ranges and scaling could explain a uniform picture.
  • Consider what the edge location suggests about the search range.

Key Takeaways

  • cross_val_score takes a model, the data, and the target, and by default performs three-fold cross-validation, returning one accuracy value per fold.
  • The cv parameter sets the number of folds, and the length of the returned array always matches that number, so check the length first when an output looks wrong.
  • A heat map of mean cross-validation scores arranges one cell per parameter setting, with color showing accuracy, and it must be reshaped to match the grid size.
  • A constant-color heat map can point to poor ranges or scaling, a striped one to a single influential parameter, and a best region on the grid edge means the search range should be widened.
  • Adjust the parameter grid using cross-validation scores on the training data, and keep the final test set out of the loop.

Related concepts

More concepts starting with S