Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 58

Dataset Splitting for Model Evaluation

Recommended resources

Hello! Welcome to the second lesson in our "Foundations of Machine Learning" module.

In our last lesson, you learned to distinguish between the three main paradigms of machine learning: supervised, unsupervised, and reinforcement learning. We established that supervised learning, a core focus of your GATE syllabus, involves training a model on labeled data to make predictions.

This raises a crucial question: How can we be sure that our model has truly learned the underlying patterns, rather than just memorizing the training examples? If a student only studies past exam papers, they might do well on those specific questions but fail when faced with new ones. A machine learning model is no different.

This lesson directly addresses that challenge. Your learning outcome is to split a dataset into training, validation, and test sets for model evaluation. This is a non-negotiable, foundational step for building reliable supervised learning models.

Why We Can't Use All Our Data for Training

The primary goal of a machine learning model is to generalize—to perform well on new, unseen data. If we train our model on our entire dataset and then evaluate it on that same data, we get a misleadingly optimistic score. The model might have simply memorized the "answers" without learning the general principles. This phenomenon is called overfitting.

To get a true measure of performance, we need to test the model on data it has never seen before. This leads to the most basic data split: a training set and a test set.

However, the process of building a good model isn't just a one-shot train-and-test cycle. We often need to:

  • Compare different types of models (e.g., Linear Regression vs. a Decision Tree).
  • Tune the model's settings, called hyperparameters (e.g., the complexity of a model).

If we use the test set to make these decisions, we are indirectly using it to guide our model-building process. Our choices will start to become tailored to that specific test set, and it will no longer be a truly "unseen" dataset. The performance estimate we get will again be over-optimistic.

This is where a third dataset becomes essential.


The Three Essential Datasets: Train, Validate, Test

The standard practice in machine learning is to split your data into three distinct subsets.

To understand the specific role of each, let's watch a short, insightful video that uses a great analogy.

Validation data: How it works and why you need it - Machine Learning Basics Explained

This video from Galaxy Inferno Codes explains the purpose of each data split using an analogy of a teacher preparing students for a competition. It brilliantly clarifies why three sets are better than two.

Please watch the entire video (around 5 minutes). Pay close attention to: The role of the 'training questions' (Training Set). The role of the 'new questions' used to select the best student (Validation Set). The role of the 'competition' itself (Test Set). The concept of 'data leakage' mentioned at the end.

As the video explained, each dataset has a unique and critical purpose:

  1. Training Set (The Textbook):

    • This is the largest portion of the data.
    • Its sole purpose is to train the model. The model learns the relationships between the input features and the output labels from this data.
  2. Validation Set (The Practice Exam):

    • This is a medium-sized portion of the data.
    • Its purpose is to tune the model and select the best one. You use this set to:
      • Adjust hyperparameters.
      • Compare the performance of different algorithms.
    • The model never learns from this data, it is only evaluated on it during the development phase.
  3. Test Set (The Final Exam):

    • This is a smaller portion of the data that is held out until the very end.
    • Its purpose is to provide an unbiased evaluation of the final, chosen model.
    • You should only use this set once. After you have trained and tuned your model using the training and validation sets, you use the test set to estimate how well it will perform in the real world.
Dataset Splitting for Machine Learning Model Development
This flowchart shows the complete process. You train multiple models on the **training set**, use the **validation set** to compare them and pick the best one, and finally, evaluate your single best model on the **test set** to get a final performance score.
Data Splitting into Training, Validation, and Test Sets
Visually, you can think of it as taking your original dataset and partitioning it into three separate buckets, each containing a different subset of the original data points.
Test your understanding!

You are building a model to predict house prices. After splitting your data into training, validation, and test sets, which set would you use for each of the following tasks?

  1. Teaching the model the relationship between a house's square footage and its price.
  2. Deciding whether a simple model or a very complex model performs better on data it wasn't trained on.
  3. Reporting the final, expected error of your chosen model to your boss before deploying it.
Show answer
  1. Training Set. This is the learning phase, where the model's internal parameters are adjusted.
  2. Validation Set. This is the model selection and hyperparameter tuning phase. You evaluate different model configurations on the validation set to see which one generalizes better.
  3. Test Set. You use this for the final, one-time evaluation to get an unbiased estimate of real-world performance.

A Practical Walkthrough: Seeing the Splits in Action

Now that you understand the "why," let's move to the "how." The best way to see the importance of this process is to walk through a coding example. We'll use Python, the pandas library you're familiar with, and scikit-learn, the most important machine learning library in Python.

The following video provides a fantastic, hands-on demonstration. It shows what happens when you only use a train/test split and why that's problematic, before introducing the correct train/validation/test workflow.

Train, Test, & Validation Sets | How to Train Machine Learning Models (Properly!!!)

This video by Greg Hogg is a practical coding session. It will guide you through the entire thought process of data splitting, from a naive approach to the correct one.

This is a longer, more detailed video. We'll break it down. You don't need to code along right now, but focus on understanding the steps and the reasoning. Setup and the Flawed Approach (00:00 - 14:25): Watch how the presenter first loads data and creates a training and testing set. He then trains two different models (Linear Regression and Random Forest) and tunes the Random Forest model's hyperparameters by repeatedly checking its performance on the test set. This demonstrates the problem we discussed: the test set is being used to make development decisions. The Correct Approach with a Validation Set (14:25 - 21:40): Now, watch how he introduces a third 'holdout' set by splitting the original test data. This new split creates a validation set and a final test (holdout) set. He then repeats the process correctly: models are evaluated and tuned on the validation set, and the final, untouched test set is used only at the very end for the true performance report.


Implementing the Split in Python

As you saw in the video, scikit-learn provides a very convenient function for this task: train_test_split.

Let's formalize the process. Since train_test_split only splits data into two sets at a time, we perform the split in two steps.

How to Split Your Data: A Practical Guide

This article from Medium provides a clear code snippet that demonstrates the standard two-step process for creating a train-validation-test split.

Read the section titled 'How to Split Your Data: A Practical Guide'. Focus on the Python code block. It shows exactly how to perform the two-step split.

Here is the common pattern, assuming X contains your features and y contains your labels:

from sklearn.model_selection import train_test_split

# Assume X are your features and y is your target
# First split: Create the training set (e.g., 80%) and a temporary set (20%)
X_train, X_temp, y_train, y_temp = train_test_split(X, y, test_size=0.2, random_state=42)

# Second split: Split the temporary set into validation and test sets (e.g., 50/50 split of the 20%)
# This results in 10% validation and 10% test of the original data
X_val, X_test, y_val, y_test = train_test_split(X_temp, y_temp, test_size=0.5, random_state=42)

print(f"Training set size: {len(X_train)}")
print(f"Validation set size: {len(X_val)}")
print(f"Test set size: {len(X_test)}")

Key Parameters:

  • test_size: Specifies the proportion of the data to be allocated to the test split. You can also use train_size.
  • random_state: This is a crucial parameter for reproducibility. By setting random_state to any integer (e.g., 42), you ensure that the same random split is generated every time you run the code. This is essential for debugging and getting consistent results. If you leave it out, you'll get a different split each time.

Splitting Ratios and Other Methods

  • Common Ratios: There's no single perfect ratio, but common splits are 80/10/10 (Train/Val/Test) or 70/15/15. For very large datasets (millions of records), you might even use something like 98/1/1, because 1% is still a huge number of data points for validation and testing.

  • Advanced Splitting: While random splitting is the default, some situations require different strategies.

    • Stratified Splitting: When you have a classification problem with imbalanced classes (e.g., 95% "not fraud" and 5% "fraud"), a random split might result in a validation or test set with very few or no examples of the minority class. Stratified splitting ensures that the proportion of each class is the same across the train, validation, and test sets. You can do this by setting the stratify parameter in train_test_split.
    • Time-Based Splitting: For time-series data (like stock prices), you cannot randomly shuffle the data, as that would destroy the temporal order. In these cases, you must split the data chronologically, for instance, using past data for training and more recent data for testing.

Conclusion

You have now mastered a fundamental practice in machine learning model development. Properly separating your data is the first line of defense against building models that look great on paper but fail in the real world.

Key Takeaways:

  • The goal of splitting data is to get an honest estimate of how your model will perform on unseen data.
  • Training Set: Used to teach the model its parameters.
  • Validation Set: Used to tune hyperparameters and compare different models.
  • Test Set: Used only once at the end for a final, unbiased performance evaluation.
  • Using the test set for tuning leads to data leakage and an over-optimistic performance estimate.
  • In Python, you can use sklearn.model_selection.train_test_split to perform the splits, typically in a two-step process.

Preview of the Next Lesson:
Splitting the data is a crucial organizational step. The next step is to prepare the data within those splits for the model to use effectively. In the next lesson, you will learn how to handle missing values and apply feature scaling (normalization, standardization). These are essential data preprocessing techniques that can significantly improve your model's performance.