Data Splitting
The final step before training a model is to split the data into different sets for training, testing, and evaluation. Proper data splitting is necessary for training models that perform well on unseen data (i.e., actually doing the job they were trained for).
This Lesson Will Cover
- ✂️ Different data splitting strategies for machine learning
- 📊 Train-test-eval split ratios and when to use them
- 🔄 Cross-validation techniques including K-Fold, Stratified K-Fold, and Time Series CV
- 🛠️ How to implement these splitting strategies using scikit-learn
Train-Test-Eval Split
The train-test-eval (or train-validation-test) split is a fundamental strategy for evaluating machine learning models.
It involves dividing our dataset into three parts:
- Training set (60-70%): Used to train our model. This is where the model learns patterns and relationships from the data.
- Validation/Test set (15-20%): Used during development to evaluate model performance and tune hyperparameters. This helps prevent overfitting to the training data.
- Evaluation set (15-20%): Held out from training and hyperparameter tuning, then used to compare candidate models in this course. Once these scores influence model selection, the winning score can be optimistically biased. A final assessment needs fresh data held out from selection too.
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_iris
# Load dataset
X, y = load_iris(return_X_y=True)
# First split: training (70%) vs test+eval (30%)
X_train, X_temp, y_train, y_temp = train_test_split(X, y, test_size=0.3, random_state=42)
# Second split: test (15%) and eval (15%) from the temp set
X_test, X_eval, y_test, y_eval = train_test_split(X_temp, y_temp, test_size=0.5, random_state=42)
print("Training set size:", len(X_train))
print("Testing set size:", len(X_test))
print("Evaluation set size:", len(X_eval))
# Outputs:
# Training set size: 105
# Testing set size: 22
# Evaluation set size: 23
The percentages here are approximations. Here are some example train-test split ratios based on dataset size:
| Dataset Size | Training Set | Test Set | Validation Set | Notes |
|---|---|---|---|---|
| Small (<1,000 samples) | 60-70% | 20% | 10-20% | Larger test sets needed for statistical significance |
| Medium (1,000-100,000) | 70-80% | 10-15% | 10-15% | Standard split ratios work well |
| Large (100K-1M) | 80-90% | 5-10% | 5-10% | Can reduce test size while maintaining significance |
| Very Large (>1M) | 95-99% | 0.5-2% | 0.5-2% | Even tiny test sets provide enough samples |
This is only meant to give us a general idea of what might be a good ratio based on the number of records in the training dataset. There are statistical tests that can provide more accurate numbers based on the details of the features and target variable.
CV (Cross-Validation) Techniques
CV (Cross-Validation) provides a more robust way to evaluate models by splitting the data into multiple training and testing subsets, and then training and evaluating the model multiple times on different combinations of these subsets.
In terms of the train-test-eval framework, we can think of CV as follows:
- CV set (80%-85%): Used to train and test our model with cross-validation.
- Evaluation set (15-20%): Held out from training and tuning for later candidate comparison; final assessment of the selected winner requires data excluded from selection too.
Again, these numbers are just rough estimates. What’s important to keep in mind is that we still have set aside an evaluation set for later (we’ll come back to this in the Model Selection lesson, at the end of the next section on Model Training and Evaluation).
In the examples below, we’re working within our CV set.
Common Cross-Validation Methods
K-Fold Cross-Validation
The dataset is divided into k subsets (folds). In each iteration, the model is trained on k-1 folds and tested on the remaining fold.
For example, with k=5:
- Iteration 1: Train on folds 2,3,4,5; Test on fold 1
- Iteration 2: Train on folds 1,3,4,5; Test on fold 2
- Iteration 3: Train on folds 1,2,4,5; Test on fold 3
- Iteration 4: Train on folds 1,2,3,5; Test on fold 4
- Iteration 5: Train on folds 1,2,3,4; Test on fold 5
This process ensures each data point appears in the test set exactly once and in the training set k-1 times.
from sklearn.model_selection import KFold
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
kf = KFold(n_splits=5, shuffle=True, random_state=42)
model = LogisticRegression()
for train_index, test_index in kf.split(X):
X_train, X_test = X[train_index], X[test_index]
y_train, y_test = y[train_index], y[test_index]
model.fit(X_train, y_train)
predictions = model.predict(X_test)
print("Accuracy:", accuracy_score(y_test, predictions))
# Outputs:
# Accuracy: 1.0
# Accuracy: 1.0
# Accuracy: 0.9333333333333333
# Accuracy: 0.9666666666666667
# Accuracy: 0.9666666666666667
Stratified K-Fold
Stratified K-Fold is a variation of K-Fold cross-validation that maintains the same proportion of samples for each class in the training and test sets.
This is important when dealing with class imbalance - where some classes have significantly more samples than others (e.g., 90% negative cases and 10% positive cases in a binary classification problem).
For example, if our dataset has:
- Class A: 900 samples (90%)
- Class B: 100 samples (10%)
Regular K-Fold might create splits where the minority class (B) is underrepresented or missing entirely.
Whereas stratified K-Fold* ensures that each fold maintains the 90:10 ratio, making it more reliable for imbalanced datasets.
from sklearn.model_selection import StratifiedKFold
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
# Initialize stratified k-fold
skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
model = LogisticRegression()
# Perform stratified k-fold cross validation
for train_index, test_index in skf.split(X, y):
X_train, X_test = X[train_index], X[test_index]
y_train, y_test = y[train_index], y[test_index]
model.fit(X_train, y_train)
predictions = model.predict(X_test)
print("Accuracy:", accuracy_score(y_test, predictions))
# Outputs:
# Accuracy: 1.0
# Accuracy: 0.9666666666666667
# Accuracy: 0.9333333333333333
# Accuracy: 1.0
# Accuracy: 0.9333333333333333
Time Series Cross Validation
Time Series Cross-Validation is specifically designed for temporal data, where the order of samples matters.
Unlike standard K-Fold, which randomly splits data, Time Series CV maintains the temporal order and uses past data to predict future values.
Using regular K-Fold for time series data can lead to data leakage, where future information is used to predict the past, resulting in unrealistic performance metrics.
Think about a real-world scenario where we want to use historical data to forecast future events.
The most common approach is the “expanding window” or “forward chaining” method, where each training set consists of all data up to a point, and the test set is the subsequent time period. For example:
- Iteration 1: Train [1-100], Test [101-120]
- Iteration 2: Train [1-120], Test [121-140]
- Iteration 3: Train [1-140], Test [141-160]
from sklearn.model_selection import TimeSeriesSplit
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
# Initialize time series split
tscv = TimeSeriesSplit(n_splits=5)
model = LinearRegression()
# Perform time series cross validation
for i, (train_index, test_index) in enumerate(tscv.split(X)):
X_train, X_test = X[train_index], X[test_index]
y_train, y_test = y[train_index], y[test_index]
model.fit(X_train, y_train)
predictions = model.predict(X_test)
print(f"Fold {i+1}:")
print(f"Training set size: {len(X_train)}, Test set size: {len(X_test)}")
print(f"MSE: {mean_squared_error(y_test, predictions)}\n")
# Outputs:
#
# Fold 1:
# Training set size: 25, Test set size: 25
# MSE: 0.0
#
# Fold 2:
# Training set size: 50, Test set size: 25
# MSE: 1.0
#
# Fold 3:
# Training set size: 75, Test set size: 25
# MSE: 0.018868056956335345
#
# Fold 4:
# Training set size: 100, Test set size: 25
# MSE: 0.3483620695449156
#
# Fold 5:
# Training set size: 125, Test set size: 25
# MSE: 0.12217397712069693
Note: the above example was run on the Iris dataset (loaded at the top of the lesson, used for all examples above) which is not temporal data.
Therefore, the MSE results above are meaningless. Instead, notice how the training window expands while the test set size remains fixed.
Conclusion
In order to lock in your conceptual understanding of data splitting for ML, I suggest checking out the figures from Andreas Mueller’s blog post on Data Splitting Strategies[1]. They demonstrate nicely how each technique works. Sometimes a picture is worth a thousand words.
Key Takeaways
📊 Train-test-eval split: Use 70-15-15 ratios for medium datasets; adjust based on size.
📈 Dataset size matters: Larger datasets can use smaller test/eval splits.
🔄 K-Fold CV: Best for robust evaluation, especially with small datasets.
⚖️ Stratified K-Fold: Essential for imbalanced class distributions.
⏳ Time Series CV: Required for temporal data to prevent data leakage.
🔑 Golden rule: Keep evaluation data separate from training and tuning; reserve fresh data for final assessment if evaluation scores guide model selection.
Next: Model Training and Evaluation
So now that we’ve got our data in good shape, it’s time to make the magic happen. We’re going to talk about training, optimizing (hyperparameters) and evaluating ML models.
Footnotes
Data Splitting Strategies by Andreas Mueller ↩︎
Comments (0)
No comments yet.