Zero Labs
Industry News / AI

A Practical Guide to imbalanced-learn: The Python Library Built to Fix What Scikit-learn Leaves…

Source · Towards AI By R_Talks

From the publisher’s feed, collected in the ZeroLabs newsroom.

A Practical Guide to Imbalanced-Learn: The Python Library Built to Fix What Scikit-learn Leaves Broken“A chain is only as strong as its weakest link.” — Thomas ReidIn machine learning, your weakest link in imbalanced dataset is almost always the minority class.Introduction: One Library to Rule the Imbalance ProblemYou have a fraud detection dataset. 0.3% of transactions are fraud. You know the problem — accuracy is meaningless, your model ignores the minority class, and you need SMOTE, under sampling, and careful evaluation to get anything useful.You also know the tooling ecosystem is fragmented. SMOTE is not in scikit-learn. Borderline-SMOTE is somewhere else. ADASYN is in a different package. Each one has a slightly different API. Combining them into a pipeline that does not leak data requires careful, manual wiring.imbalanced-learn (imported as imblearn) solves all of this. It is the official, scikit-learn compatible Python library for handling class imbalance — a single, coherent package that implements every major resampling method, integrates directly into sklearn Pipelines, and follows the same fit/transform interface you already know.This guide covers the full library: its architecture, every major method, how to build leak-proof pipelines, and how to choose between approaches for your specific problem.Part 1: What imbalanced-learn Is and How It Fits Inimbalanced-learn is a third-party library maintained as part of the scikit-learn ecosystem. It extends sklearn with a new type of object: a sampler — something that resamples training data rather than fitting a model.Installation:pip install imbalanced-learnThe library structure:imblearn├── over_sampling → Create more minority samples│ ├── RandomOverSampler│ ├── SMOTE (and variants)│ ├── ADASYN│ └── BorderlineSMOTE│├── under_sampling → Remove majority samples│ ├── RandomUnderSampler│ ├── TomekLinks│ ├── EditedNearestNeighbours (ENN)│ ├── NearMiss│ └── ClusterCentroids│├── combine → Over + under together│ ├── SMOTETomek│ └── SMOTEENN│├── ensemble → Imbalance-aware ensemble models│ ├── BalancedBaggingClassifier│ ├── BalancedRandomForestClassifier│ ├── EasyEnsembleClassifier│ └── RUSBoostClassifier│└── pipeline → Leak-proof Pipeline with samplers └── PipelineThe sampler API is identical to sklearn transformers — fit_resample(X, y) does the work. Every sampler also integrates cleanly into imblearn.pipeline.Pipeline, which handles the critical detail of applying resampling only to the training fold during cross-validation.Part 2: Over-sampling MethodsOver-sampling creates more minority class examples to balance the distribution.RandomOverSamplerThe baseline. Duplicates minority samples randomly.from imblearn.over_sampling import RandomOverSamplerros = RandomOverSampler(sampling_strategy=0.5, random_state=42)# sampling_strategy=0.5 → minority : majority = 1:2 after resamplingX_res, y_res = ros.fit_resample(X_train, y_train)The sampling_strategy parameter is flexible:sampling_strategy = 'auto' → balance to equal classessampling_strategy = 0.5 → minority/majority = 0.5 after resamplingsampling_strategy = {0: 500} → resample class 0 to exactly 500 samplesSMOTE — The WorkhorseGenerates synthetic samples by interpolating between minority neighbours.SMOTE formula for each synthetic sample: x_new = x_i + λ × (x_nn − x_i)Where: x_i = a minority sample x_nn = one of its k nearest minority neighbours λ ~ Uniform(0, 1) — random interpolation weightfrom imblearn.over_sampling import SMOTEsmote = SMOTE( sampling_strategy='auto', k_neighbors=5, random_state=42)X_res, y_res = smote.fit_resample(X_train, y_train)SMOTE Variants — Choosing the Right FlavourVariant Key Idea When to Use──────────────────────────────────────────────────────────────────────────────SMOTE Interpolate between minority neighbours General purpose, start hereBorderlineSMOTE Focus on minority samples near boundary When boundary is the problemSVMSMOTE Focus near SVM support vectors When SVM is your classifierADASYN More synthesis in harder regions Adaptive, non-uniform densityKMeansSMOTE SMOTE within minority clusters When minority has sub-clustersADASYN (Adaptive Synthetic Sampling):r_i = number of majority neighbours of minority sample i / k_neighboursd_i = r_i / Σ r_i (normalised density — harder samples get higher weight)Number of synthetic samples for sample i: g_i = d_i × GWhere G = total number of synthetic samples to generateSamples surrounded by majority neighbours (harder to classify correctly) receive more synthetic copies than samples already deep in minority territory.from imblearn.over_sampling import ADASYN, BorderlineSMOTE, SVMSMOTEadasyn = ADASYN(sampling_strategy='auto', n_neighbors=5, random_state=42)borderline = BorderlineSMOTE(kind='borderline-1', k_neighbors=5, random_state=42)Part 3: Under-sampling MethodsUnder-sampling removes majority class examples to balance the distribution.RandomUnderSamplerThe fastest approach. Randomly removes majority samples.from imblearn.under_sampling import RandomUnderSamplerrus = RandomUnderSampler(sampling_strategy=0.5, random_state=42)X_res, y_res = rus.fit_resample(X_train, y_train)Tomek Links — Cleaning the BoundaryA Tomek Link is a pair of samples from opposite classes that are each other’s nearest neighbour. These are the most ambiguous, borderline examples.A Tomek Link exists between samples (xᵢ, xⱼ) when: class(xᵢ) ≠ class(xⱼ) AND there is no sample xₖ such that d(xᵢ, xₖ) or d(xⱼ, xₖ) Removing the majority sample from each Tomek Link cleans the decision boundary without drastically reducing the dataset size.from imblearn.under_sampling import TomekLinks, EditedNearestNeighbourstl = TomekLinks(sampling_strategy='majority')X_clean, y_clean = tl.fit_resample(X_train, y_train)# ENN removes samples whose class label differs from majority of k neighboursenn = EditedNearestNeighbours(n_neighbors=3)X_clean, y_clean = enn.fit_resample(X_train, y_train)NearMiss — Targeted Majority RemovalInstead of removing randomly, NearMiss selects majority samples based on their proximity to minority samples.NearMiss-1: Keep majority samples closest to minority samples (on average)NearMiss-2: Keep majority samples whose k farthest minority neighbours are closestNearMiss-3: For each minority sample, keep m closest majority neighboursfrom imblearn.under_sampling import NearMissnm = NearMiss(version=1, n_neighbors=3)X_res, y_res = nm.fit_resample(X_train, y_train)Part 4: Combined Methods — The Best of BothCombining over and under-sampling captures the benefits of both: generate informative minority samples, then clean the noisy majority boundary.from imblearn.combine import SMOTETomek, SMOTEENN# SMOTE + Tomek Links cleaningsmt = SMOTETomek(random_state=42)X_res, y_res = smt.fit_resample(X_train, y_train)# SMOTE + Edited Nearest Neighbours (more aggressive cleaning)smote_enn = SMOTEENN(random_state=42)X_res, y_res = smote_enn.fit_resample(X_train, y_train)SMOTETomek is generally the safer starting point — it generates synthetic samples then removes Tomek Links. SMOTEENN is more aggressive and produces a cleaner boundary but removes more samples.Part 5: Imbalance-Aware Ensemble MethodsThese combine resampling with ensemble modelling into single estimators — often the most powerful approach for severe imbalance.from imblearn.ensemble import ( BalancedRandomForestClassifier, BalancedBaggingClassifier, EasyEnsembleClassifier, RUSBoostClassifier)# Balanced Random Forest: undersamples each bootstrap samplebrf = BalancedRandomForestClassifier( n_estimators=200, sampling_strategy='auto', random_state=42)brf.fit(X_train, y_train)# EasyEnsemble: trains multiple AdaBoost on balanced subsetsee = EasyEnsembleClassifier(n_estimators=20, random_state=42)ee.fit(X_train, y_train)When to use each:BalancedRandomForestClassifier → Drop-in replacement for RF on imbalanced dataBalancedBaggingClassifier → Any base estimator with balanced baggingEasyEnsembleClassifier → Strong performer on severe imbalance (ratio > 50:1)RUSBoostClassifier → Boosting + undersampling for highly skewed dataPart 6: The Leak-Proof PipelineThis is where imbalanced-learn earns its place. Using imblearn.pipeline.Pipeline — not sklearn.pipeline.Pipeline — ensures resampling happens only inside each cross-validation fold, on training data only.from imblearn.pipeline import Pipeline # NOT sklearn.pipelinefrom imblearn.over_sampling import SMOTEfrom sklearn.preprocessing import StandardScalerfrom sklearn.ensemble import GradientBoostingClassifierfrom sklearn.model_selection import StratifiedKFold, cross_validatefrom sklearn.metrics import make_scorer, f1_score, roc_auc_score# Build the full pipelinepipe = Pipeline([ ('scaler', StandardScaler()), ('smote', SMOTE(k_neighbors=5, random_state=42)), # Applied only to training fold ('classifier', GradientBoostingClassifier(n_estimators=200, random_state=42))])# Cross-validate — SMOTE only sees training data in each foldcv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)scores = cross_validate( pipe, X, y, cv=cv, scoring={ 'f1': make_scorer(f1_score), 'roc_auc': 'roc_auc', 'pr_auc': make_scorer(roc_auc_score, needs_proba=True) })print(f"F1: {scores['test_f1'].mean():.4f} ± {scores['test_f1'].std():.4f}")print(f"ROC-AUC: {scores['test_roc_auc'].mean():.4f} ± {scores['test_roc_auc'].std():.4f}")If you use sklearn.pipeline.Pipeline instead, SMOTE is applied to the full training dataset before splitting — a subtle data leakage that inflates validation metrics.Method Selection GuideSituation Recommended Method──────────────────────────────────────────────────────────────────────────────General starting point SMOTE + StratifiedKFold + class_weightMinority has clear sub-clusters KMeansSMOTE or ADASYNNoisy boundary / overlapping classes SMOTEENN or SMOTETomekVery large datasets (speed matters) RandomUnderSampler or BalancedRandomForestExtreme imbalance (> 100:1) EasyEnsembleClassifier or ADASYN + ENNNeed interpretability BalancedRandomForest (feature_importances_)Neural networks Class weights in loss function + oversamplingConclusion: One Library, Every Toolimbalanced-learn wraps a decade of research into a clean, sklearn-compatible API. You no longer need to implement SMOTE from scratch, manually wire resampling into cross-validation, or hunt across packages for Borderline-SMOTE versus ADASYN.The practical recommendation: start with SMOTE inside imblearn.pipeline.Pipeline. Evaluate with F1 and PR-AUC, not accuracy. If SMOTE is not enough, try SMOTEENN or BalancedRandomForestClassifier. Reserve EasyEnsembleClassifier for severe imbalance where nothing else works.The minority class matters. Now you have the tools to make your model treat it that way.Found this useful? Follow for more applied data science guides. What imbalance ratio does your current problem have — and which method will you try first?A Practical Guide to imbalanced-learn: The Python Library Built to Fix What Scikit-learn Leaves… was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.