Class Imbalance in Machine Learning: Resampling, Class Weights & SMOTE
In real-world classification problems, target classes are rarely distributed equally. Credit card fraud may account for less than 0.1% of transactions, manufacturing defects may occur in only a few products, and rare medical conditions may affect a very small percentage of patients.
When a machine learning model is trained on a heavily imbalanced dataset, it can become biased toward predicting the majority class. As a result, it may achieve impressive overall accuracy while failing to identify the minority-class examples that matter most.
For example, imagine a fraud detection dataset containing 10,000 transactions:
- 9,990 legitimate transactions
- 10 fraudulent transactions
A model that predicts every transaction as legitimate achieves:
\[ Accuracy=\frac{9990}{10000}\times100=99.9\% \]
However, it detects zero fraudulent transactions.
This demonstrates why accuracy alone can be misleading when working with imbalanced classification datasets.
To improve minority-class detection, machine learning practitioners commonly use three strategies:
- Data Resampling: Adjusting the class distribution through undersampling or oversampling.
- SMOTE: Generating synthetic minority-class examples.
- Class Weights: Assigning greater penalties to mistakes involving important minority classes.
Let's understand each technique with examples, Python implementations, advantages, limitations, and best practices.
1. Understanding Class Imbalance
A classification dataset is imbalanced when one target class contains significantly more observations than another.
Consider a binary classification problem:
| Class | Meaning | Number of Samples | Percentage |
|---|---|---|---|
| 0 | Legitimate transaction | 9,900 | 99% |
| 1 | Fraudulent transaction | 100 | 1% |
| Total | 10,000 | 100% |
Here:
- Class 0 is the majority class.
- Class 1 is the minority class.
- The class distribution is 99:1.
The minority class is often the most important class because it represents rare events such as fraud, disease, defects, or security threats.
1.1 Why Does Class Imbalance Cause Problems?
Many classification algorithms learn by minimizing a loss function across training examples.
When the majority class dominates the dataset, errors on that class can dominate the total loss. A model may therefore learn a decision boundary that favors the majority class.
This can produce:
- Low minority-class recall.
- Many false negatives.
- Poor detection of rare events.
- Misleadingly high accuracy.
- Decision boundaries that fail to represent minority-class patterns.
Important: Class imbalance does not automatically make a model ineffective. Some algorithms can handle imbalanced datasets reasonably well, depending on the features, class separation, model objective, and evaluation strategy.
2. Data-Level Resampling: Undersampling and Oversampling
Resampling changes the class distribution in the training dataset before model training.
The two basic approaches are:
- Random Undersampling (RUS)
- Random Oversampling (ROS)
Consider the following original dataset:
Original Imbalanced Dataset
Majority Class: 10,000
Minority Class: 100
Class Ratio: 100:1
2.1 Random Undersampling
Random Undersampling reduces the number of majority-class examples.
For example:
Original Dataset:
Majority: 10,000
Minority: 100
|
v
Random Undersampling:
Majority: 100
Minority: 100
Result: Balanced Dataset
The algorithm randomly removes majority-class observations until the desired class ratio is reached.
Python Implementation
from sklearn.datasets import make_classification
from collections import Counter
from imblearn.under_sampling import RandomUnderSampler
# Create an imbalanced dataset
X, y = make_classification(
n_samples=10000,
n_features=10,
n_informative=5,
n_redundant=2,
weights=[0.99, 0.01],
random_state=42
)
print("Original Distribution:", Counter(y))
# Apply random undersampling
rus = RandomUnderSampler(random_state=42)
X_resampled, y_resampled = rus.fit_resample(X, y)
print("After Undersampling:", Counter(y_resampled))
Advantages
- Reduces training dataset size.
- Can speed up model training.
- Removes some majority-class redundancy.
- Useful when the majority class contains many observations.
Disadvantages
- Discards potentially useful information.
- May remove important majority-class patterns.
- Can make the model less representative of real-world data.
- Results may vary depending on which observations are removed.
When Should You Use It?
Random Undersampling can be useful when:
- The majority class is extremely large.
- Training time or memory is limited.
- There is substantial redundancy in majority-class observations.
- You have enough majority-class examples to retain a representative subset.
2.2 Random Oversampling
Random Oversampling increases the number of minority-class observations by randomly selecting existing minority examples and duplicating them.
For example:
Original Dataset:
Majority: 10,000
Minority: 100
|
v
Random Oversampling:
Majority: 10,000
Minority: 10,000
Result: Balanced Dataset
Unlike undersampling, this method does not discard majority-class observations.
Python Implementation
from imblearn.over_sampling import RandomOverSampler
from collections import Counter
# Original distribution
print("Original Distribution:", Counter(y))
# Apply random oversampling
ros = RandomOverSampler(random_state=42)
X_resampled, y_resampled = ros.fit_resample(X, y)
print("After Oversampling:", Counter(y_resampled))
Advantages
- Preserves all original majority-class examples.
- Increases the representation of the minority class.
- Simple to implement.
- Can improve minority-class recall.
Disadvantages
- Duplicates existing observations.
- Can increase overfitting.
- Increases training dataset size.
- Does not introduce genuinely new minority-class information.
When Should You Use It?
Random Oversampling can be useful when:
- The minority class contains relatively few examples.
- You do not want to discard majority-class information.
- You are training models that can benefit from repeated exposure to minority examples.
- You want a simple baseline before trying synthetic sampling techniques.
3. SMOTE: Synthetic Minority Over-sampling Technique
SMOTE (Synthetic Minority Over-sampling Technique) is an oversampling method that creates synthetic minority-class observations instead of simply duplicating existing ones.
It was introduced to improve minority-class representation while reducing the dependence on repeated copies of the same examples.
3.1 How Does SMOTE Work?
SMOTE identifies minority-class observations and finds their nearest neighbors within the minority class.
It then generates synthetic observations by interpolating between a selected minority example and one of its minority-class neighbors.
The synthetic sample is calculated using:
\[ X_{new}=X_i+\lambda(X_{neighbor}-X_i) \]
Where:
- \(X_i\) = Original minority-class observation.
- \(X_{neighbor}\) = One of its minority-class nearest neighbors.
- \(\lambda\) = Random number between 0 and 1.
- \(X_{new}\) = Newly generated synthetic observation.
Example
Suppose two minority-class observations have these feature values:
\[ X_i=[20,40] \]
\[ X_{neighbor}=[30,60] \]
If:
\[ \lambda=0.5 \]
Then:
\[ X_{new}=[20,40]+0.5([30,60]-[20,40]) \]
\[ X_{new}=[20,40]+[5,10] \]
\[ X_{new}=[25,50] \]
SMOTE generates a new observation between the two original minority-class examples.
3.2 SMOTE Workflow
Original Imbalanced Dataset
|
v
Identify Minority-Class Samples
|
v
Find k Nearest Minority Neighbors
|
v
Select a Neighbor
|
v
Generate Synthetic Samples
|
v
Create Resampled Training Dataset
|
v
Train Classification Model
3.3 Python Implementation
SMOTE is available through the imbalanced-learn library.
Install it:
pip install imbalanced-learn
Implementation:
from imblearn.over_sampling import SMOTE
from collections import Counter
# Original distribution
print("Original Distribution:", Counter(y))
# Create SMOTE object
smote = SMOTE(
sampling_strategy="auto",
random_state=42,
k_neighbors=5
)
# Generate synthetic minority samples
X_smote, y_smote = smote.fit_resample(X, y)
print("After SMOTE:", Counter(y_smote))
The default sampling_strategy="auto" oversamples the minority class to match the majority class in a binary classification problem.
The default k_neighbors=5 uses five nearest minority-class neighbors when generating synthetic examples.
3.4 Important SMOTE Parameters
| Parameter | Purpose |
|---|---|
sampling_strategy | Determines the desired resampled class distribution |
random_state | Controls reproducibility |
k_neighbors | Number of minority-class neighbors used |
n_jobs | Parallel processing in supported versions of the library |
3.5 Advantages of SMOTE
- Generates synthetic minority-class observations.
- Reduces repeated duplication compared with random oversampling.
- Can improve minority-class recall.
- Can help models learn more representative minority-class regions.
3.6 Limitations of SMOTE
SMOTE is useful, but it is not a universal solution.
1. Noisy Samples
If minority-class observations contain noise or incorrect labels, SMOTE can generate additional synthetic samples around those noisy observations.
2. Overlapping Classes
If majority and minority classes overlap, synthetic observations may be generated in regions where the classes are difficult to distinguish.
3. High-Dimensional Data
Distance calculations become less reliable in high-dimensional spaces. Consequently, nearest-neighbor-based synthetic generation may become less effective.
4. Categorical Features
Ordinary SMOTE is designed for numerical features. For mixed numerical and categorical data, use SMOTENC. For categorical-only data, consider SMOTEN.
5. Not All Synthetic Samples Are Realistic
Interpolation can create mathematically valid but practically unrealistic observations, particularly when features have complex relationships or constraints.
4. Cost-Sensitive Learning: Class Weights
Resampling modifies the training data. Class weighting instead modifies how much the model penalizes errors from different classes.
This approach is called Cost-Sensitive Learning.
The central idea is simple:
Mistakes involving an important minority class should receive a higher penalty during training.
For example, failing to identify a fraudulent transaction may be more expensive than incorrectly flagging a legitimate transaction.
4.1 How Do Class Weights Work?
A typical classification model minimizes a loss function.
Without class weights:
\[ L=\frac{1}{N}\sum_{i=1}^{N}L_i \]
With class weights:
\[ L=\frac{1}{N}\sum_{i=1}^{N}w_{y_i}L_i \]
Where:
- \(N\) = Number of training observations.
- \(L_i\) = Loss for observation \(i\).
- \(w_{y_i}\) = Weight assigned to the true class of observation \(i\).
A higher class weight makes mistakes involving that class contribute more to the training objective.
4.2 Calculating Balanced Class Weights
Scikit-learn provides a commonly used balanced weighting formula:
\[ w_c=\frac{N}{K\times N_c} \]
Where:
- \(N\) = Total number of observations.
- \(K\) = Number of classes.
- \(N_c\) = Number of observations belonging to class \(c\).
Consider a dataset:
| Class | Samples |
|---|---|
| Majority (0) | 9,900 |
| Minority (1) | 100 |
| Total | 10,000 |
There are two classes, so:
For the majority class:
\[ w_0=\frac{10000}{2\times9900} \]
\[ w_0\approx0.505 \]
For the minority class:
\[ w_1=\frac{10000}{2\times100} \]
\[ w_1=50 \]
The minority class receives a much larger weight.
4.3 Python Implementation with Logistic Regression
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.datasets import make_classification
from sklearn.metrics import classification_report
# Create imbalanced dataset
X, y = make_classification(
n_samples=10000,
n_features=10,
n_informative=5,
n_redundant=2,
weights=[0.99, 0.01],
random_state=42
)
# Split the data
X_train, X_test, y_train, y_test = train_test_split(
X,
y,
test_size=0.2,
stratify=y,
random_state=42
)
# Train with balanced class weights
model = LogisticRegression(
class_weight="balanced",
max_iter=1000
)
model.fit(X_train, y_train)
# Predict
y_pred = model.predict(X_test)
# Evaluate
print(classification_report(y_test, y_pred))
4.4 Class Weights in Other Algorithms
Scikit-learn supports class weights in several classification algorithms.
Decision Tree:
from sklearn.tree import DecisionTreeClassifier
model = DecisionTreeClassifier(
class_weight="balanced",
random_state=42
)
Random Forest:
from sklearn.ensemble import RandomForestClassifier
model = RandomForestClassifier(
n_estimators=100,
class_weight="balanced",
random_state=42
)
Support Vector Machine:
from sklearn.svm import SVC
model = SVC(
class_weight="balanced",
probability=True,
random_state=42
)
Always check the estimator's documentation because supported weighting options and their behavior vary by algorithm.
4.5 Advantages of Class Weights
- No need to generate synthetic samples.
- No need to discard majority-class observations.
- Easy to implement in many classification algorithms.
- Can be computationally cheaper than resampling.
- Allows the model to account for unequal class importance.
4.6 Limitations of Class Weights
- Excessively high weights can increase false positives.
- They do not create additional minority-class information.
- They may not solve problems caused by severe class overlap.
- Some algorithms do not support class weights directly.
- The best weights may require experimentation and validation.
5. Comparing Resampling, SMOTE, and Class Weights
These methods address class imbalance in different ways.
| Technique | How it works | Main advantage | Main limitation |
|---|---|---|---|
| Random Undersampling | Removes majority-class observations | Reduces dataset size | Loses information |
| Random Oversampling | Duplicates minority-class observations | Preserves majority data | Can overfit |
| SMOTE | Generates synthetic minority observations | Adds varied minority examples | Can create unrealistic or overlapping samples |
| Class Weights | Increases minority-class error penalties | No resampling required | Can increase false positives |
Which Technique Should You Choose?
| Situation | Technique worth trying |
|---|---|
| Very large majority class | Random Undersampling |
| Very small minority dataset | Random Oversampling |
| Numerical features with meaningful local neighborhoods | SMOTE |
| Model supports class weighting | Class Weights |
| Mixed numerical and categorical data | SMOTENC or class weights |
| Severe class overlap or noisy minority data | Carefully tuned class weights or alternative sampling strategies |
| Limited training memory | Class Weights or Undersampling |
These are starting points, not universal rules. Compare methods using the same validation strategy.
6. Evaluating Imbalanced Classification Models
When classes are imbalanced, accuracy alone does not reveal whether a model detects the minority class effectively.
Consider a fraud detection model that predicts:
| Actual Class | Predicted Legitimate | Predicted Fraud |
|---|---|---|
| Legitimate | 9,850 | 140 |
| Fraud | 5 | 5 |
The model correctly identifies 9,850 legitimate transactions and 5 fraudulent transactions.
Let's understand the metrics.
6.1 Confusion Matrix
A confusion matrix summarizes classification predictions.
| Term | Meaning |
|---|---|
| True Positive (TP) | Minority-class example correctly predicted as minority |
| True Negative (TN) | Majority-class example correctly predicted as majority |
| False Positive (FP) | Majority-class example incorrectly predicted as minority |
| False Negative (FN) | Minority-class example incorrectly predicted as majority |
For the example:
- TP = 5
- TN = 9,850
- FP = 140
- FN = 5
6.2 Accuracy
\[ Accuracy=\frac{TP+TN}{TP+TN+FP+FN} \]
Accuracy measures the proportion of correct predictions.
However, a high accuracy score does not necessarily indicate good minority-class detection.
6.3 Precision
\[ Precision=\frac{TP}{TP+FP} \]
Precision answers:
Of all the examples predicted as positive, how many were actually positive?
For the example:
\[ Precision=\frac{5}{5+140}\approx0.0345 \]
Precision is approximately 3.45%.
6.4 Recall
\[ Recall=\frac{TP}{TP+FN} \]
Recall answers:
Of all actual positive examples, how many did the model successfully identify?
\[ Recall=\frac{5}{5+5}=0.5 \]
Recall is 50%.
6.5 F1-Score
F1-score is the harmonic mean of precision and recall.
\[ F1=2\times\frac{Precision\times Recall}{Precision+Recall} \]
It provides a combined measure when both precision and recall matter.
6.6 Precision-Recall AUC
Precision-Recall analysis evaluates the trade-off between precision and recall across different classification thresholds.
PR-AUC or Average Precision is often particularly useful when the positive class is rare.
Unlike ROC-AUC, precision-recall metrics focus directly on the positive class's detection quality.
For highly imbalanced datasets, PR-AUC can provide a more informative picture of minority-class performance.
Python Evaluation
from sklearn.metrics import (
confusion_matrix,
accuracy_score,
precision_score,
recall_score,
f1_score,
average_precision_score,
classification_report
)
# Predicted labels
y_pred = model.predict(X_test)
# Predicted probabilities
y_prob = model.predict_proba(X_test)[:, 1]
print("Confusion Matrix:")
print(confusion_matrix(y_test, y_pred))
print("Accuracy:", accuracy_score(y_test, y_pred))
print("Precision:", precision_score(
y_test, y_pred, zero_division=0
))
print("Recall:", recall_score(
y_test, y_pred, zero_division=0
))
print("F1 Score:", f1_score(
y_test, y_pred, zero_division=0
))
print("Average Precision:", average_precision_score(
y_test, y_prob
))
print("\nClassification Report:")
print(classification_report(y_test, y_pred))
For imbalanced classification, examine the minority-class precision, recall, F1-score, confusion matrix, and PR-AUC rather than relying on accuracy alone.
7. Combining Resampling with Machine Learning Pipelines
Resampling must be applied carefully to avoid data leakage.
A common mistake is to apply SMOTE to the entire dataset before splitting it into training and testing sets.
Incorrect approach:
# Do not do this
X_resampled, y_resampled = SMOTE().fit_resample(X, y)
X_train, X_test, y_train, y_test = train_test_split(
X_resampled,
y_resampled,
test_size=0.2,
random_state=42
)
Why is this incorrect?
Synthetic samples may be generated using observations that later appear in the test set. This allows information from the test data to influence the training process, resulting in overly optimistic evaluation.
Correct Approach
- Split the original dataset.
- Apply resampling only to the training data.
- Train the model on the resampled training data.
- Evaluate on the untouched, naturally imbalanced test data.
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report
from imblearn.over_sampling import SMOTE
from imblearn.pipeline import Pipeline
# Split original data
X_train, X_test, y_train, y_test = train_test_split(
X,
y,
test_size=0.2,
stratify=y,
random_state=42
)
# Create pipeline
pipeline = Pipeline([
("smote", SMOTE(random_state=42)),
("model", RandomForestClassifier(
n_estimators=100,
random_state=42
))
])
# Train
pipeline.fit(X_train, y_train)
# Predict on original test data
y_pred = pipeline.predict(X_test)
# Evaluate
print(classification_report(y_test, y_pred))
The imblearn.pipeline.Pipeline applies SMOTE during fitting, not during prediction. Therefore, the test dataset retains its original class distribution.
Important: Cross-Validation
If you use cross-validation, place SMOTE or another resampling method inside the pipeline.
This ensures that each training fold is resampled independently while its validation fold remains untouched.
If your features require scaling before SMOTE, place the scaler before SMOTE in the pipeline. This is important because SMOTE uses nearest-neighbor distances.
For example:
from imblearn.pipeline import Pipeline
from imblearn.over_sampling import SMOTE
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
pipeline = Pipeline([
("scaler", StandardScaler()),
("smote", SMOTE(random_state=42)),
("model", LogisticRegression(max_iter=1000))
])
This pipeline learns scaling parameters from the training fold, transforms the training data, applies SMOTE, and then trains Logistic Regression.
8. Advanced SMOTE Variants
Ordinary SMOTE is not the only synthetic oversampling method.
Several variations address different dataset characteristics.
8.1 Borderline-SMOTE
Borderline-SMOTE focuses on minority-class observations near the decision boundary, where classification is more difficult.
It attempts to generate additional examples in these challenging regions.
8.2 SMOTE-ENN
SMOTE-ENN combines:
- SMOTE to generate synthetic minority observations.
- Edited Nearest Neighbors (ENN) to remove observations that appear inconsistent with their neighbors.
It can help reduce some noisy or overlapping examples, although it may also remove useful observations.
8.3 SMOTE-Tomek
SMOTE-Tomek combines oversampling with Tomek Links.
Tomek Links identify certain closely neighboring observations from different classes. Removing selected observations can help clean the boundary between classes.
Python Example
from imblearn.combine import SMOTEENN
smote_enn = SMOTEENN(random_state=42)
X_resampled, y_resampled = smote_enn.fit_resample(
X_train,
y_train
)
These techniques should be evaluated carefully because they can alter both class distribution and the composition of the training data.
9. Choosing the Right Decision Threshold
Class imbalance is not only a data-distribution problem. It is also a decision-making problem.
Many binary classifiers produce a probability score rather than an immediate class label.
By default, a classifier may predict the positive class when:
\[ P(y=1\mid X)\geq0.5 \]
However, 0.5 is not necessarily the best threshold for an imbalanced classification problem.
For example:
- A lower threshold may increase recall but also increase false positives.
- A higher threshold may improve precision but miss more minority-class examples.
Python Example
import numpy as np
# Get predicted probabilities
y_prob = model.predict_proba(X_test)[:, 1]
# Set a custom threshold
threshold = 0.30
# Convert probabilities into class predictions
y_pred_custom = (y_prob >= threshold).astype(int)
print(classification_report(
y_test,
y_pred_custom,
zero_division=0
))
The threshold should be selected using validation data based on the business objective and the cost of different mistakes.
Do not select the threshold using the final test set.
For applications such as medical screening, fraud detection, and cybersecurity, the relative cost of false negatives and false positives can be very different.
10. Real-World Applications of Class Imbalance Techniques
| Industry | Minority class | Possible strategy |
|---|---|---|
| Banking | Fraudulent transactions | Class weights, SMOTE, threshold tuning |
| Healthcare | Rare diseases | Class weights, careful oversampling, recall-focused evaluation |
| Manufacturing | Defective products | Undersampling, SMOTE, anomaly detection |
| Telecom | Customer churn | Class weights, random oversampling |
| Cybersecurity | Malicious network activity | Class weights, resampling, anomaly detection |
| E-commerce | Rare purchase or return events | Class weights, threshold tuning |
The most suitable method depends on the dataset, the cost of errors, and the operational requirements.
For example, a fraud detection system may prioritize recall to identify more fraudulent transactions, while also controlling false positives to avoid unnecessarily blocking legitimate customers.
11. Best Practices for Imbalanced Classification
- Inspect the class distribution: Understand the number and percentage of observations in each class.
- Use stratified splitting: Preserve approximate class proportions in training and test sets.
- Avoid accuracy-only evaluation: Include precision, recall, F1-score, confusion matrix, and PR-AUC.
- Establish a baseline: Evaluate the original dataset before applying resampling.
- Try class weights: They provide a useful baseline without modifying the data distribution.
- Compare resampling methods: Test undersampling, oversampling, and SMOTE when appropriate.
- Apply resampling only to training data: Keep validation and test data untouched.
- Use pipelines: Prevent leakage during training and cross-validation.
- Scale before distance-based SMOTE: Neighbor selection depends on feature distances.
- Tune the decision threshold: Choose a threshold based on the desired precision-recall trade-off.
- Preserve realistic evaluation data: Test on the naturally occurring class distribution.
- Consider business costs: The best model is not necessarily the one with the highest accuracy or recall.
12. Final Conclusion
Class imbalance is a common challenge in real-world classification problems. When one class dominates the training dataset, a model may learn to favor the majority class and fail to detect rare but important events.
Three widely used approaches help address this problem:
- Undersampling: Reduces the number of majority-class observations.
- Oversampling: Increases minority-class representation by duplicating existing examples.
- SMOTE: Creates synthetic minority-class examples using nearest-neighbor interpolation.
- Class Weights: Assigns higher penalties to mistakes involving important classes.
However, balancing the dataset does not automatically produce a better classifier. Resampling can introduce noise, remove useful information, or increase overfitting. Class weights can also change the precision-recall trade-off.
A reliable approach is to establish a baseline, compare appropriate imbalance-handling methods using cross-validation, tune the decision threshold, and evaluate the final model on an untouched dataset with its natural class distribution.
The ultimate goal is not simply to create a balanced dataset. It is to build a classifier that identifies important minority-class events reliably while controlling the cost of incorrect predictions.