Skip to main content

Welcome to a Grasp lesson

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

Lesson 17

Data Splitting for Machine Learning

This lesson is built with resources from youtube.com, dzone.com and 1 more site.

Hello! Welcome to the second lesson in our module on the Fundamentals of Model Training.

In our last lesson, we established the core concept of supervised learning: training a model on labeled data to learn a function that can make predictions. We explored the two main tasks, classification and regression. This raised a crucial question: how do we know if our model has truly learned the underlying patterns, rather than just memorizing the training data?

This lesson directly addresses that question and covers the learning outcome: Split datasets into training, validation, and test sets to prevent data leakage. This is one of the most fundamental and non-negotiable practices in machine learning for building models that you can trust to work in the real world.

1. The Need for an Unbiased Evaluation

Imagine you were a student preparing for a major exam. If the teacher gave you the exact exam questions and answers to study beforehand, you would likely get a perfect score. But would that score reflect your actual understanding of the subject? Of course not. You'd have simply memorized the answers.

Machine learning models can do the same thing. If we evaluate a model on the same data it was trained on, we'll get an overly optimistic and misleading sense of its performance. This is because the model might be overfitting—learning the noise and specific quirks of the training data, rather than the general pattern we want it to capture.

To get a true measure of a model's ability to generalize to new, unseen data, we need separate datasets for training and evaluation. In fact, we need two separate datasets for evaluation, each with a distinct purpose.


2. The Three-Way Split: Training, Validation, and Test Sets

The standard practice is to split your data into three distinct sets:

  1. Training Set: The largest part of your data, used by the model to learn. This is the "textbook" the model studies.
  2. Validation Set: A separate dataset used to tune the model and make development decisions. This is the "practice exam."
  3. Test Set: A final, held-out dataset that is used only once to get a final, unbiased measure of the model's performance. This is the "final exam."

To understand the roles of each, let's watch a video that uses a helpful analogy.

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

This video from Galaxy Inferno Codes provides an excellent explanation of why we need three separate data splits, using a clear teacher-student analogy.

Watch the entire video (about 5.5 minutes). As you watch, focus on the distinct purpose for each of the three datasets: Training: For the model to learn its parameters. Validation: For you, the developer, to choose the best model or tune its settings (hyperparameters). Testing: To get a final, true estimate of performance on unseen data.

Let's summarize this workflow:

  • You train several different models (or one model with different settings) on the training set.
  • You evaluate each of these models on the validation set.
  • You select the single best-performing model based on its validation score.
  • Finally, you take this chosen model and evaluate it one last time on the test set to report its expected real-world performance. You do not go back and tweak the model after this step.

This process ensures that your final performance metric is not biased by the choices you made during model development.

Training, Validation, and Test Set Workflow
This flowchart illustrates the model development process. The model is trained on the training set and iteratively improved by evaluating it on the validation set. The test set is only used once at the very end to confirm the final model's performance.

3. Data Leakage: The Silent Model Killer

The most critical reason for maintaining this strict separation is to prevent data leakage.

Data leakage occurs when information from outside the training dataset is used to create the model. This is a subtle but severe bug in a machine learning pipeline. It gives you a false sense of high performance, and your model will fail unexpectedly when deployed.

From your perspective as a software engineer, think of it as a contaminated test environment. Imagine your unit tests pass because they accidentally rely on a specific configuration or database entry that only exists on your local machine. When the code is pushed to a clean CI/CD environment, the tests fail. Data leakage is the machine learning equivalent of this problem.

A common source of leakage is performing data preprocessing steps (like scaling, imputation, or feature selection) on the entire dataset before splitting it. This allows the model to "peek" at the validation and test data, influencing how it learns.

The core principle to prevent this is: Any decision or learned parameter in your pipeline must be derived only from the training data.

Common pitfalls and recommended practices

The scikit-learn documentation has an excellent page on common pitfalls that explains data leakage with clear code examples. This is essential reading for any practitioner.

Read the following sections from the documentation: Data leakage: Focus on the definition and the general rule: never call fit on the test data. How to avoid data leakage: Pay close attention to the distinction between fit_transform (used on training data) and transform (used on test data). Data leakage during pre-processing: Study the 'Wrong' vs. 'Right' code examples. This demonstrates how applying feature selection before splitting gives a misleadingly high accuracy.

The key takeaway from the scikit-learn documentation is the fit vs. transform paradigm:

  • You call .fit() or .fit_transform() on the training data to learn the parameters of the transformation (e.g., the mean and standard deviation for a scaler).
  • You then call .transform() on the validation and test data to apply the same transformation that was learned from the training data.
Independent Data Cleaning and Enhancement for Training, Validation, and Test Sets
This diagram correctly shows that data preprocessing steps like cleaning and enhancement must be applied independently to each data split to prevent leakage.

4. Implementing Data Splits in Code

Now, let's see how to perform this split in practice using Python's scikit-learn library. The most common function for this is train_test_split.

Data Splits in ML: Training, Validation, and Test Sets

This article from DZone provides a clear walkthrough of data split types and includes practical code snippets for implementation.

Read the section 'Data Split Types'. Focus on the Python code examples that show how to use train_test_split. Notice how a three-way split is typically done in two steps.

To create a train/validation/test split, we usually apply train_test_split twice. Common ratios are 80/10/10 or 70/15/15. Here's how you'd achieve an 80/10/10 split:

import numpy as np
from sklearn.model_selection import train_test_split

# Assume X are your features and y are your labels
# Create a sample dataset for demonstration
X = np.arange(100).reshape(50, 2)
y = np.arange(50)

# Step 1: Split data into training (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
)

# Step 2: Split the temporary set into validation (10%) and test (10%)
# The new test_size is 0.5 because we want to split the 20% into two equal 10% halves.
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 shape: {X_train.shape}")
print(f"Validation set shape: {X_val.shape}")
print(f"Test set shape: {X_test.shape}")

Note: The random_state parameter is crucial. It's a seed for the random number generator, ensuring that you get the exact same split every time you run the code. This makes your work reproducible, which is as important in machine learning as it is in software engineering.


5. Beyond Random Splitting: A Real-World Caveat

Is a simple random split always the right approach? Not necessarily. The assumption behind random splitting is that every data point is independent. In many real-world scenarios, this is not true.

Should You Stop Splitting Your Data Like This?

This video from the channel 'Underfitted' makes a compelling case against naively using random splits and introduces the critical concept of 'group leakage'.

Watch from 02:02 to 05:31. The video uses a flight delay example to demonstrate how correlations between data points can break a random split strategy.

This idea of group leakage is critical. If your dataset contains correlated groups, you must ensure that all data points from a single group end up in the same split.

Consider these examples relevant to your background in Fintech:

  • Credit Fraud Prediction: If you have multiple transactions for the same user, you can't have some of their transactions in the training set and others in the test set. The model might learn to identify the user, not the fraudulent behavior. You must split by user_id.
  • Loan Default Prediction: Data from the same geographical region or loan officer might be correlated. A simple random split could lead to an overly optimistic model.
  • Time-Series Data: When predicting stock prices or transaction volumes, your data is ordered by time. You cannot randomly shuffle it, as that would let the model see the future. You must train on past data and test on future data.

For these cases, scikit-learn provides more advanced splitting strategies like GroupKFold, StratifiedKFold (for imbalanced classification), and TimeSeriesSplit. We'll explore these as we encounter relevant problems, but it's vital to be aware that "how you split" is a decision that requires understanding your data.

Test your understanding!

You are tasked with building a model to predict the sentiment (positive/negative) of user reviews for different products on an e-commerce site. Your dataset contains review_text, product_id, and sentiment. A single user can leave reviews for multiple products, and a single product can have many reviews.

What is a potential source of data leakage if you use a simple train_test_split? What would be a better splitting strategy?

Show answer

A potential source of leakage comes from the products. Certain products might have unique characteristics that influence the language of their reviews. If reviews for the same product_id appear in both the training and test sets, the model might simply memorize product-specific phrases rather than learning general sentiment patterns.

A better strategy would be to perform a group split based on product_id. This ensures that all reviews for any given product are entirely in either the training, validation, or test set, forcing the model to generalize across different products.


Conclusion

You've now learned one of the most important operational skills in machine learning. Properly splitting your data isn't just a best practice; it's the foundation of building trustworthy and reliable models.

Key Takeaways:

  • Always split your data into training, validation, and test sets.
  • The training set is for the model to learn its parameters.
  • The validation set is for you to tune the model and select the best one.
  • The test set is for a final, unbiased evaluation of your chosen model.
  • Data leakage is a critical bug where the model learns from data it wouldn't see in production. Prevent it by splitting your data first, before any preprocessing.
  • The choice of splitting strategy (e.g., random, grouped, time-series) depends on the underlying structure and dependencies within your data.

Next up:
With our understanding of how to prepare data for training, we're ready to build our first model. In the next lesson, we will use our training set to implement linear regression using gradient descent from scratch. This will make the purpose of the training set tangible and introduce you to the core mechanics of how a model actually "learns."