← retour aux snippets

imblearn SMOTE: suréchantillonnage synthétique

équilibrer une classe minoritaire avec SMOTE

imblearn SMOTE: suréchantillonnage synthétique

objectif

Expliquer et montrer comment équilibrer une classe minoritaire avec SMOTE.

code minimal

from sklearn.datasets import make_classification
from imblearn.over_sampling import SMOTE
from collections import Counter

X, y = make_classification(n_samples=2000, weights=[0.95, 0.05], n_features=10, random_state=0)
print(Counter(y))
X_res, y_res = SMOTE(random_state=0).fit_resample(X, y)
print(Counter(y_res))

utilisation

# pipeline: SMOTE avant le classifieur
from sklearn.linear_model import LogisticRegression
from imblearn.pipeline import Pipeline
pipe = Pipeline(steps=[("smote", SMOTE(random_state=0)), ("clf", LogisticRegression(max_iter=1000))]).fit(X, y)

variante(s) utile(s)

# SMOTE k_neighbors et sampling_strategy ajustables
SMOTE(k_neighbors=3, sampling_strategy=0.3, random_state=0)

notes

  • À utiliser uniquement sur l’ensemble d’entraînement pour éviter la fuite.
  • Essayer des variantes comme BorderlineSMOTE.