Artificial Intelligence Fundamentals / Check and Troubleshoot Models

Validate with cross-validation

Lesson 14 of 26. Open to read. No account needed.

Choosing Without Peeking

The last lesson found that a tree depth of about 4 generalised best, but it found that by looking at test scores, which uses the test set to make a decision. You need a way to compare settings using the training data alone, keeping the test set for one final, honest measurement.

One option is to split off part of the training data as a validation set and compare settings on it. That works, but the result depends on which samples happened to land in that one validation set. With a few hundred samples, a different split could favour a different setting.

Cross-Validation

Cross-validation uses the training data more thoroughly. In k-fold cross-validation the training data is divided into k equal parts, called folds. The model is trained k times; each time, one fold is held out for scoring and the other k − 1 folds are used for training. Every training sample is used for scoring exactly once, and you get k scores instead of one.

The training data is divided into five folds. In round 1, fold 1 is held out and folds 2 to 5 train the model; in round 2, fold 2 is held out; and so on to round 5. Each round produces one score, and the five scores are averaged. The test set sits apart and is not used.

Read the diagram row by row. Each row is one round of training. The shaded block moves one place to the right each round, so each fold is held out once. The five scores on the right are averaged into one. The test set, drawn separately, never takes part.

The mean of the k scores is a steadier estimate than any single split. Their spread, measured by the standard deviation, shows how much the estimate depends on which samples are held out: a large spread means the mean is uncertain, and small differences between settings may be noise.

cross_val_score

scores = cross_val_score(model, X_train, y_train)

cross_val_score runs the whole procedure and returns one score per fold. When you do not pass cv, it uses 5 folds; cv=10 uses ten. It fits fresh copies of the model each round, so the model you pass in stays unfitted. For classifiers it keeps the class proportions in each fold, as stratify does for a single split.

The routine is:

  1. Split off the test set and set it aside.
  2. For each candidate setting, run cross-validation on the training data.
  3. Choose the setting with the best mean score, considering the spread.
  4. Train that setting on all the training data.
  5. Score it once on the test set and report that score.

Exercise: Choose a Depth Fairly

You will choose a tree depth by 5-fold cross-validation on the training data and then measure it once on the test set.

Starting state: the course environment, active in your terminal. The script uses the same generated data as the overfitting lesson.

  1. Create the exercise folder. macOS and Linux:

    mkdir -p ~/ai-practice/choose-depth
    cd ~/ai-practice/choose-depth
    

    Windows PowerShell:

    mkdir $HOME\ai-practice\choose-depth
    cd $HOME\ai-practice\choose-depth
    

    Save this as choose_depth.py in that folder:

    """Choose a tree depth with cross-validation, then score it once on the test set."""
    from sklearn.datasets import make_classification
    from sklearn.model_selection import cross_val_score, train_test_split
    from sklearn.tree import DecisionTreeClassifier
    
    X, y = make_classification(n_samples=600, n_features=10, n_informative=4, flip_y=0.15, random_state=1)
    X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1, stratify=y)
    
    mean_scores = {}
    for depth in range(1, 13):
        tree = DecisionTreeClassifier(max_depth=depth, random_state=1)
        scores = cross_val_score(tree, X_train, y_train)  # 5 folds of the training data
        mean_scores[depth] = scores.mean()
        print(f"depth {depth:2}: mean {scores.mean():.3f}, spread {scores.std():.3f}")
    
    best = max(mean_scores, key=mean_scores.get)
    final = DecisionTreeClassifier(max_depth=best, random_state=1).fit(X_train, y_train)
    print("Chosen depth:", best)
    print(f"Test accuracy, measured once: {final.score(X_test, y_test):.3f}")
    
  2. Run it:

    python choose_depth.py
    

    Output, which should match exactly:

    depth  1: mean 0.693, spread 0.035
    depth  2: mean 0.684, spread 0.036
    depth  3: mean 0.762, spread 0.036
    depth  4: mean 0.767, spread 0.029
    depth  5: mean 0.760, spread 0.017
    depth  6: mean 0.736, spread 0.040
    depth  7: mean 0.751, spread 0.040
    depth  8: mean 0.753, spread 0.035
    depth  9: mean 0.731, spread 0.027
    depth 10: mean 0.744, spread 0.030
    depth 11: mean 0.729, spread 0.043
    depth 12: mean 0.729, spread 0.043
    Chosen depth: 4
    Test accuracy, measured once: 0.827
    

How the Script Works

Only training data in the loop. cross_val_score(tree, X_train, y_train) never sees X_test or y_test. With 450 training samples, each of the 5 folds holds 90; each round trains on 360 and scores on 90.

Collecting results. mean_scores is a dictionary from depth to mean score. scores.mean() and scores.std() give the mean and standard deviation of the five fold scores.

Choosing. max(mean_scores, key=mean_scores.get) returns the depth whose mean score is highest: 4. Then a fresh tree with that depth is trained on all 450 training samples, and only now is the test set used, once, giving 0.827.

What the results show. Depths 3, 4 and 5 have means of 0.762, 0.767 and 0.760, within a fraction of their spreads of 0.017 to 0.036. Cross-validation cannot really tell them apart; any of them would be a sensible choice, and choosing the simplest, depth 3, would also be defensible. What it shows clearly is that very shallow trees (0.69) and deep ones (0.73) are worse. Cross-validation agreed with the test-set pattern from the last lesson, but this time the test set played no part in the choice, so 0.827 is an honest estimate.

Success: the output matches; you can explain why the test set is used only after the depth is chosen, and why depths 3 to 5 are practically tied.

If something differs:

What you seeLikely causeNext step
Different numbersrandom_state or the data settings were changedRestore the values shown
ValueError mentioning n_splits or the number of members in a classToo few samples for the number of foldsUse fewer folds or more data
The test accuracy line appears inside the loopIndentation of the last lines was changedRestore the indentation shown
ModuleNotFoundErrorThe course environment is not activeActivate it and rerun
  1. Clean up. macOS and Linux:

    cd ~/ai-practice
    ls
    rm -rf choose-depth
    ls
    

    Windows PowerShell:

    cd $HOME\ai-practice
    ls
    Remove-Item -Recurse choose-depth
    ls
    

    Check that the first ls shows choose-depth before removing it. Do the independent task first.

Independent task: change the cross_val_score call to use ten folds by adding cv=10, and predict whether the chosen depth will change. Run it and explain the result.

Check Your Understanding

A colleague chooses a tree depth by trying twelve depths and picking the one with the best test score, 0.827, which they report as the expected accuracy.

  1. Why is 0.827 likely to be an optimistic estimate in their workflow?
  2. In your workflow the same number, 0.827, came out. Why is yours an honest estimate while theirs is not?

Answer and Reasoning

Independent task

With cv=10, each round trains on 405 samples and scores on 45, and the means and spreads change slightly, but the chosen depth stays 4 and the final test accuracy is again 0.827. When the choice does not depend on the number of folds, you can be more confident in it. If the choice had changed between neighbouring depths with nearly equal means, that would confirm that they are practically tied.

Understanding check

  1. They chose the best of twelve test scores. Some of that best score is luck that happens to suit these particular test samples, and choosing it builds that luck into the reported number.
  2. In your workflow the test set played no part in the choice: the depth was fixed by cross-validation on the training data first. The test score was measured once afterwards, so nothing was tuned to it. Equal numbers can carry different meanings depending on how they were obtained.

References

Study this course with an account

Course access adds revision notes, the Quick Reference, saved progress, bookmarks and your own notes.

INR 199 plus 18% GST. 90 days of online access. No auto-renewal.

See course access

This website is operated by VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED, operating as Vectametric.

Corporate Identity Number (CIN): U85499KA2026OPC229822. GSTIN: 29AAMCV8281D1ZS. Registered office: RS NO/38/2A/1 BASTAND, ROAD MAHANTESH NAGAR, Ramdurg, Ramdurg, Belgaum- 591123, Karnataka.

Queries and grievances: Prajval Honnungar, Grievance Officer and Data Protection Contact.

Telephone: +91 94800 09310. Support: support@vectametric.com. Grievances: support@vectametric.com.

Copyright 2026 VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED. All rights reserved.

Vectametric home · Roadmaps · Vecta IT Exams · Vecta Government Exams · Vecta Banking & Finance Exams · Vecta Entrance Exams · About us · Contact · Privacy Policy · Terms and Conditions · No-Refund Policy