How to do class balancing in Python for data: step by step
Balancing classes in datasets is essential when one class is much more frequent than another: it helps avoid biased models and improves metrics like recall and F1. This tutorial shows how to do class balancing in Python for data with simple and popular techniques, explaining why and showing example code. I will also show concrete numbers so you can understand the impact of the transformations and when each technique is preferable.
Prerequisites
- Python 3.8+ with pip
- pandas, scikit-learn, imbalanced-learn (install with pip)
- Basic knowledge of DataFrame and classification
Step 1: Understand the imbalance and why to address it
Before applying any technique, let’s look at the class distribution. A severe imbalance can lead to models that always predict the majority class: for example, in a dataset with 85% class 0 and 15% class 1, a classifier that always predicts 0 already achieves 85% accuracy — but without practical value.
Use per-class metrics like precision, recall and F1, and examine the confusion matrix to understand false positives and false negatives. The recall of the minority class is often critical (for example, fraud or disease detection).
import pandas as pd
from sklearn.model_selection import train_test_split
# Minimal example: create simulated DataFrame with 200 rows
df = pd.DataFrame({
'feature1': range(200),
'feature2': [x * 0.5 for x in range(200)],
'target': [0]*170 + [1]*30 # class 1 is minority (15%)
})
# Check distribution
print(df['target'].value_counts()) # 0:170, 1:30
# Split train/test keeping proportions (30% test)
train_df, test_df = train_test_split(df, test_size=0.3, stratify=df['target'], random_state=42)
print(train_df['target'].value_counts()) # expected: ~119 of 0 and 21 of 1
print(train_df['target'].value_counts(normalize=True))
Step 2: Simple undersampling (reduce majority)
Undersampling removes examples from the majority class to equalize classes. It’s fast and useful when you have many majority examples and limited training resources. The downside is you lose information: if you reduce from 119 to 21 examples, you are using only ~18% of the majority data.
Practical example: from the training set with 119 majority examples and 21 minority ones, you will reduce the majority to 21. The new set will have 42 examples.
from sklearn.utils import resample
# Separate classes in training
major = train_df[train_df['target'] == 0]
minor = train_df[train_df['target'] == 1]
# Subsample the majority class to the size of the minority
major_down = resample(major, replace=False, n_samples=len(minor), random_state=42)
train_down = pd.concat([major_down, minor])
print(train_down['target'].value_counts()) # 0:21, 1:21
Step 3: Simple oversampling (duplicate minority)
Oversampling duplicates examples of the minority class to balance. It avoids data loss and is simple: from 21 minority examples you duplicate until you have 119. The final set will have 238 examples. The downside is the risk of overfitting, because the model may memorize repeated examples.
# Resample the minority with replacement to match the majority
minor_up = resample(minor, replace=True, n_samples=len(major), random_state=42)
train_up = pd.concat([major, minor_up])
print(train_up['target'].value_counts()) # 0:119, 1:119
Step 4: SMOTE (create synthetic examples)
SMOTE generates synthetic examples by interpolating between nearby minority points. It preserves more diversity than duplication and reduces some overfitting. In our case it will create 98 synthetic examples to turn 21 into 119, ending with 238 rows in training.
SMOTE works best when features are numerical and when the minority class has sufficiently representative examples (usually >10 examples). If you have very few samples (e.g., < 10), consider alternative techniques or collect more data.
from imblearn.over_sampling import SMOTE
X_train = train_df[['feature1', 'feature2']]
y_train = train_df['target']
sm = SMOTE(random_state=42)
X_res, y_res = sm.fit_resample(X_train, y_train)
print(pd.Series(y_res).value_counts()) # 0:119, 1:119
Step 5: Integrate with pipeline and evaluate models
It’s good practice to apply balancing only to the training set and evaluate on the original untouched test set. Use a pipeline to ensure the process is repeatable and that there is no data leakage. Evaluate with per-class metrics and consider stratified cross-validation for robustness.
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report, confusion_matrix
from imblearn.pipeline import Pipeline
pipeline = Pipeline([
('smote', SMOTE(random_state=42)),
('clf', RandomForestClassifier(random_state=42))
])
X_test = test_df[['feature1', 'feature2']]
y_test = test_df['target']
pipeline.fit(X_train, y_train)
y_pred = pipeline.predict(X_test)
print(classification_report(y_test, y_pred))
print(confusion_matrix(y_test, y_pred))
Check the result
Confirm that you applied balancing only to the training set and that the distribution in training changed (e.g., from 119/21 to 119/119 after SMOTE). In testing keep the real distribution (e.g., ~85/15). Observe the indicators: if the minority class recall rises from 0.20 to 0.70, that is a relevant gain even if overall accuracy drops slightly.
Use the confusion matrix to see false negatives (very important in fraud/disease detection). If you need more robustness, do stratified cross-validation and try tuning classifier hyperparameters or use class_weight='balanced' in models that support that option.
Conclusion
You learned to identify imbalances and apply undersampling, oversampling and SMOTE in Python for data, as well as how to integrate SMOTE in a pipeline with scikit-learn. Examples with numbers (200 rows, training with ~119/21) help see the practical effect: undersampling reduces large sets to few examples, oversampling duplicates the minority and SMOTE creates synthetic examples for balance without direct repetition. Next steps: test ADASYN, try hyperparameter tuning and evaluate with stratified cross-validation. Remember: balancing only the training set avoids data leakage — always check this point in your workflow.