How to split data on balanced training set and test set on sklearn
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.
Introduction
In machine learning, preparing your dataset is a crucial step before building any model. One common task is splitting the dataset into training and testing sets. However, in cases where your dataset is imbalanced—meaning some classes are underrepresented compared to others—it's important to maintain this imbalance proportionately in both your training and test sets. The scikit-learn library (sklearn), a powerful Python library for machine learning, provides efficient utilities for this task.
Understanding Imbalanced Datasets
An imbalanced dataset is one where the distribution of classes is not uniform. For example, in a disease detection dataset, there might be many more healthy samples compared to diseased ones. Training a model on an imbalanced dataset can lead to a biased model that is overly optimistic about predicting the majority class, thereby underperforming on the minority class.
Why Balanced Splitting is Important
Balanced splitting ensures that the model:
- Learns to identify patterns related to the minority class.
- Can be evaluated properly during testing across both the majority and minority classes.
- Remains robust and generalizes well on unseen data.
Splitting Data with sklearn
The train_test_split function from the sklearn.model_selection module is widely used for dataset splitting. When dealing with imbalanced datasets, the stratify parameter comes in handy.
Steps to Split Data
- Loading Data: Use any dataset you'd like, ensuring it's loaded into a pandas dataframe or NumPy array.
- Identify Features and Labels: Separate your feature set (X) from your labels (y).
- Invoke
train_test_splitwithstratify: Pass in theylabels to thestratifyparameter.
Code Example
Below is a basic example using a synthetic dataset:
Explanation
make_classification: Generates a synthetic dataset with an imbalance (90% Class 0 and 10% Class 1).train_test_split: Thestratify=yparameter ensures the class distribution in the training and test sets remains proportional to the original dataset.
Key Points
Here is a summary of the steps and their outcomes:
| Step | Function/Method | Outcome |
| Load Dataset | datasets.load_* | Loads data into applicable structures such as NumPy arrays or pandas dataframes. |
| Separate Features and Labels | N/A | X for features, y for labels derived from the dataset. |
| Split with Stratification | train_test_split | Ensures the training and testing set maintain the class distribution from the original dataset. |
| Verify Distribution | np.bincount | Utilized to display class counts in the training and testing datasets. |
Additional Considerations
Handling Multi-Class Imbalance
The stratify parameter in train_test_split can be used with multi-class datasets as well. Just pass the y array, and sklearn will handle the distribution proportionality across all classes.
Advanced Techniques
For more complex datasets, consider:
- Resampling Techniques: Implementing oversampling (e.g., SMOTE) or undersampling methods.
- Cost-Sensitive Training: Using algorithms that consider class weights to focus more on the minority class during training.
Conclusion
Balanced splitting of datasets is a vital step, particularly in scenarios with imbalanced classes. Leveraging the stratify parameter in sklearn's train_test_split can ensure that your analyses remain robust and meaningful by retaining the imbalance ratio. This practice not only aids in the effective training of machine learning models but also ensures balanced evaluation, making your model applicable and reliable in real-world scenarios.
Related reading
- How to split data raw text into test/train sets with scikit crossvalidation module?
- How to split duplicate samples to train test with no overlapping?
- How to Split the Input into different channels in Keras
- How to stack multiple lstm in keras?
- How to store a hash table in a file?
- How to store arrays in MySQL?
- How to stop training when it hits a specific validation accuracy?
- How to store best models checkpoints, not only newest 5, in Tensorflow Object Detection API?

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.