Artificial Intelligence Fundamentals / Prepare Data for Learning

Split training and test data

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

Why Some Data Is Held Back

A model is useful only if it works on cases it has never seen: next month's emails, tomorrow's orders, a flower picked today. You cannot measure that by scoring the model on the examples it learned from. A model can fit its training examples very closely, even memorise them, and still fail on new ones. Its score on its own training data says how well it learned those examples, not how well it will do in use.

The standard answer is to divide the labelled data before training:

  • The training set is what the model learns from.
  • The test set is held back and used once, at the end, to estimate how the model will do on new cases.

The test set plays the part of the future. That only works if nothing about it influences the model: not its labels, not its statistics, not your choices of settings. The moment you adjust something because of the test score, the test set has become part of training and its score turns optimistic.

One dataset of 150 flowers is shuffled and divided: 112 go to the training set and 38 to the test set. The training set goes into fit to produce a model. The test set is used once, at the end, to score the model. A dashed line marks that nothing from the test set flows back into training.

Follow the diagram from top to bottom. The split happens first, before any learning. Only the training set reaches fit. The test set waits at the side and meets the model once, for the final score. The dashed barrier is the rule this lesson is about: no information travels back from the test set.

train_test_split

scikit-learn's train_test_split divides samples and labels in one call:

X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)

X holds the features and y the labels. The function returns four parts in this order: training features, test features, training labels and test labels. Getting the order wrong is a common mistake, because Python will happily assign any four values to any four names.

Three settings matter:

  • Test share. Without test_size or train_size, a quarter of the samples, 0.25, goes to the test set. For 150 flowers that is 38 test and 112 training samples, because the test count is rounded up. Use test_size=0.2 for a fifth, and so on.
  • Shuffling and random_state. By default the samples are shuffled before splitting, because datasets are often stored in order, for example all setosa flowers first. Shuffling is random, so each run would choose different test samples. random_state fixes the random choices: the same number gives the same split every time, which makes results repeatable. The number itself has no meaning; 0 and 42 are equally good.
  • stratify. A random split can leave the classes unevenly represented, especially with few samples. stratify=y keeps each class's share the same in both parts.

What a Test Score Estimates

A test score estimates performance on new data like the test data. If the test samples come from the same source and period as the training samples, the estimate says nothing about a different hospital, country or year. It is also only an estimate: with 38 test flowers, one mistake changes accuracy, the share of correct predictions, by almost three percentage points. Small test sets give rough answers.

Exercise: Split the Iris Data

You will split the iris flowers with and without stratification and check that a fixed random_state repeats the split.

Starting state: the course environment, active in your terminal. The iris data ships with scikit-learn.

  1. Create the exercise folder. macOS and Linux:

    mkdir -p ~/ai-practice/split-iris
    cd ~/ai-practice/split-iris
    

    Windows PowerShell:

    mkdir $HOME\ai-practice\split-iris
    cd $HOME\ai-practice\split-iris
    

    Save this as split_iris.py in that folder:

    """Split the iris flowers into training and test sets and compare class counts."""
    import numpy as np
    from sklearn.datasets import load_iris
    from sklearn.model_selection import train_test_split
    
    X, y = load_iris(return_X_y=True)
    print("All flowers:", len(y), "| per species:", np.bincount(y))
    
    X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
    print("Plain split: train", len(y_train), "test", len(y_test), "| test per species:", np.bincount(y_test))
    
    X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0, stratify=y)
    print("Stratified:  train", len(y_train), "test", len(y_test), "| test per species:", np.bincount(y_test))
    
    y_test_again = train_test_split(X, y, random_state=0, stratify=y)[3]
    print("Same test flowers again:", bool((y_test_again == y_test).all()))
    
  2. Run it:

    python split_iris.py
    

    Output, which should match exactly:

    All flowers: 150 | per species: [50 50 50]
    Plain split: train 112 test 38 | test per species: [13 16  9]
    Stratified:  train 112 test 38 | test per species: [13 13 12]
    Same test flowers again: True
    

How the Script Works

load_iris(return_X_y=True) returns just the features and labels, without the names. np.bincount(y) counts how many labels equal 0, 1 and 2, giving the number of flowers of each species in one short list.

The first split uses only random_state=0. It still produces 112 and 38 flowers, but the test set holds 13, 16 and 9 flowers of the three species: by chance, virginica is under-represented. A model judged on this test set would be judged mostly on the other two species.

The second split adds stratify=y. The test set now holds 13, 13 and 12 flowers, as close to equal as 38 allows.

The last line splits again with the same settings and takes item [3] of the result, which is the test labels. Comparing them with the earlier test labels gives True for every flower, so .all() is True: the same random_state chose the same flowers. With random_state=1 you would get a different selection, and the counts would change.

Success: the output matches; you can explain why the plain split's counts are uneven and why the last line prints True.

If something differs:

What you seeLikely causeNext step
The per-species counts differ from the listingrandom_state was changed or removedRestore random_state=0
ValueError: not enough values to unpackFewer than four names on the left of =Use the four names in the order shown
Same test flowers again: FalseThe two stratified calls use different settingsMake both calls identical
ModuleNotFoundErrorThe course environment is not activeActivate it and rerun
  1. Clean up. macOS and Linux:

    cd ~/ai-practice
    ls
    rm -rf split-iris
    ls
    

    Windows PowerShell:

    cd $HOME\ai-practice
    ls
    Remove-Item -Recurse split-iris
    ls
    

    Check that the first ls shows split-iris before removing it. Do the independent task first.

Independent task: write a short script that splits the wine data from the inspection lesson with a test share of 0.2, stratify and random_state=0, and prints the number of training and test wines and the count per grower in each part. Predict the sizes before running it.

Check Your Understanding

A team trains a model, scores it on the test set, changes a setting, scores it on the test set again, and repeats this twenty times. They report the best of the twenty test scores.

  1. Why is the reported score likely to be too optimistic?
  2. What should they have used to compare the twenty settings?

Answer and Reasoning

Independent task

import numpy as np
from sklearn.datasets import load_wine
from sklearn.model_selection import train_test_split

X, y = load_wine(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0, stratify=y)
print(len(y_train), len(y_test), np.bincount(y_train), np.bincount(y_test))

It prints 142 36 [47 57 38] [12 14 10]. A fifth of 178 is 35.6, rounded up to 36 test wines, leaving 142 for training. Each grower keeps roughly its share of the 59, 71 and 48 wines in both parts.

Understanding check

  1. Choosing the best of twenty test scores uses the test set to make a decision, so the test set is no longer unseen. Some of the improvement will be luck that happens to suit these particular test samples, and it will not repeat on new data.
  2. Data split off from the training set for that purpose, or cross-validation on the training set, which a later lesson teaches. The test set should be used once, after the setting has been chosen.

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