Machine Learning Academy · درس

إعادة أخذ العينات العشوائية الزائدة وSMOTE

سيطبّق المتعلمون RandomOverSampler وSMOTE من imbalanced-learn لزيادة عينات الفئة الأقلية، ثم يقيّمون ما إذا كان الاسترجاع-الدقة قد تحسّن.

الدرس 2 من 413 خطوة

إعادة أخذ العينات العشوائية الزائدة وSMOTE درس مجاني في Machine Learning Academy على CoddyKit. هذا هو الدرس 2 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في Machine Learning Academy، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة Machine Learning Academy 4 دروس في المجموع.

بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.

Why Oversampling Helps Imbalanced Models

Many classifiers learn a biased decision boundary when training data is dominated by one class — they effectively ignore the minority class. Oversampling increases the representation of the minority class in the training data, forcing the model to pay more attention to it. Two popular approaches are random oversampling (duplicating existing minority samples) and SMOTE (synthesising new ones).

Random Oversampling: Duplicate Minority Samples

RandomOverSampler from the imbalanced-learn library randomly duplicates examples from the minority class until the desired class ratio is achieved. It is simple and effective, but the duplicate samples add no new information — the model may overfit to the repeated minority examples if not regularised carefully.

from imblearn.over_sampling import RandomOverSampler
from sklearn.datasets import make_classification
import numpy as np

X, y = make_classification(n_samples=1000, weights=[0.95, 0.05],
                            n_features=10, random_state=42)

print('Before resampling:', np.bincount(y))

ros = RandomOverSampler(random_state=42)
X_res, y_res = ros.fit_resample(X, y)

print('After resampling: ', np.bincount(y_res))

Installing imbalanced-learn

imbalanced-learn is a scikit-learn compatible library for handling class imbalance. Install it with pip install imbalanced-learn. It follows the sklearn API — samplers have fit_resample instead of fit_transform. It integrates with sklearn Pipelines via imblearn.pipeline.Pipeline, which is a drop-in replacement that supports samplers as pipeline steps.

# pip install imbalanced-learn

from imblearn import __version__ as imb_version
from imblearn.over_sampling import RandomOverSampler, SMOTE
from imblearn.under_sampling import RandomUnderSampler
from imblearn.pipeline import Pipeline as ImbPipeline

print('imbalanced-learn version:', imb_version)

SMOTE: Synthetic Minority Oversampling

SMOTE (Synthetic Minority Oversampling TEchnique) creates new synthetic minority examples rather than duplicating existing ones. For each minority sample, SMOTE finds its k nearest minority neighbours and creates new points along the line segments connecting them. These synthetic samples occupy the interior of the minority feature space, giving the classifier richer information about the minority class boundary.

SMOTE in Practice

Use imblearn.over_sampling.SMOTE. Key parameters: k_neighbors (default 5) — how many minority neighbours to consider. The sampling_strategy parameter controls the target ratio: 'auto' oversamples all minority classes to match the majority class count.

from imblearn.over_sampling import SMOTE
from sklearn.datasets import make_classification
import numpy as np

X, y = make_classification(n_samples=1000, weights=[0.95, 0.05],
                            n_features=10, random_state=42)

print('Before SMOTE:', np.bincount(y))

smote = SMOTE(k_neighbors=5, random_state=42)
X_res, y_res = smote.fit_resample(X, y)

print('After SMOTE:', np.bincount(y_res))
print('New shape:', X_res.shape)

Comparing Random Oversampling vs SMOTE

Random oversampling simply copies existing data and is faster; SMOTE synthesises new data and tends to generalise better. However, SMOTE can create unrealistic samples if the minority class is very sparse or if features have complex interactions. On highly non-linear problems, borderline-SMOTE or ADASYN (Adaptive Synthetic Sampling) may work better than standard SMOTE.

from imblearn.over_sampling import RandomOverSampler, SMOTE
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import f1_score
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
import numpy as np

X, y = make_classification(n_samples=1000, weights=[0.95, 0.05], random_state=42)
X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y, random_state=42)

sc = StandardScaler()
X_train_s = sc.fit_transform(X_train)
X_test_s = sc.transform(X_test)

for name, sampler in [('None', None), ('ROS', RandomOverSampler(random_state=0)),
                      ('SMOTE', SMOTE(random_state=0))]:
    if sampler:
        X_r, y_r = sampler.fit_resample(X_train_s, y_train)
    else:
        X_r, y_r = X_train_s, y_train
    lr = LogisticRegression().fit(X_r, y_r)
    f1 = f1_score(y_test, lr.predict(X_test_s))
    print(f'{name:6s}: F1={f1:.4f}')

Using imbalanced-learn Pipeline

The critical rule: apply SMOTE only to the training fold, never to the test fold. The imblearn.pipeline.Pipeline enforces this automatically — SMOTE's fit_resample is called during fit but not during predict or transform. This is why you must use imblearn.pipeline.Pipeline, not sklearn's, when including a sampler.

from imblearn.pipeline import Pipeline as ImbPipeline
from imblearn.over_sampling import SMOTE
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.datasets import make_classification
import numpy as np

X, y = make_classification(n_samples=1000, weights=[0.95, 0.05], random_state=42)

pipe = ImbPipeline([
    ('sc', StandardScaler()),
    ('smote', SMOTE(random_state=42)),  # applied only during fit
    ('lr', LogisticRegression())
])

scores = cross_val_score(pipe, X, y, cv=5, scoring='f1')
print(f'CV F1: {np.mean(scores):.4f} +/- {np.std(scores):.4f}')

Visualising SMOTE Samples

On a 2D dataset you can visualise where SMOTE places synthetic samples. The new points lie along line segments between existing minority samples in feature space. This confirms that SMOTE is interpolating within the minority class region — not extrapolating outside it.

import matplotlib.pyplot as plt
from imblearn.over_sampling import SMOTE
from sklearn.datasets import make_classification

X, y = make_classification(n_samples=200, weights=[0.9, 0.1],
                            n_features=2, n_redundant=0,
                            n_informative=2, random_state=42)

smote = SMOTE(random_state=0)
X_res, y_res = smote.fit_resample(X, y)

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4))
for ax, data, labels, title in [(ax1, X, y, 'Before SMOTE'),
                                  (ax2, X_res, y_res, 'After SMOTE')]:
    ax.scatter(data[labels==0, 0], data[labels==0, 1], label='Class 0', alpha=0.5)
    ax.scatter(data[labels==1, 0], data[labels==1, 1], label='Class 1', alpha=0.5)
    ax.set_title(title)
    ax.legend()
plt.tight_layout()
plt.show()

SMOTE Variants: Borderline and ADASYN

Borderline-SMOTE generates synthetic samples only near the decision boundary (borderline minority samples closest to the majority class), focusing the model's attention where classification is hardest. ADASYN adaptively generates more samples in regions where the class is densest, adding proportionally more synthetic examples where the classifier struggles most.

from imblearn.over_sampling import BorderlineSMOTE, ADASYN
from sklearn.datasets import make_classification
import numpy as np

X, y = make_classification(n_samples=1000, weights=[0.95, 0.05], random_state=42)

print('Before:', np.bincount(y))

bs = BorderlineSMOTE(random_state=0)
X_bs, y_bs = bs.fit_resample(X, y)
print('After BorderlineSMOTE:', np.bincount(y_bs))

adas = ADASYN(random_state=0)
X_ad, y_ad = adas.fit_resample(X, y)
print('After ADASYN:', np.bincount(y_ad))

Combining SMOTE with Undersampling (SMOTEENN)

SMOTE alone can introduce noisy samples near the majority-class boundary. SMOTEENN combines SMOTE with Edited Nearest Neighbours (ENN) cleaning: after SMOTE upsamples, ENN removes misclassified samples from both classes near the boundary. The result is a cleaner dataset with both oversampled minority and cleaned majority regions.

from imblearn.combine import SMOTEENN
from sklearn.datasets import make_classification
import numpy as np

X, y = make_classification(n_samples=1000, weights=[0.95, 0.05], random_state=42)
print('Before:', np.bincount(y))

smoteenn = SMOTEENN(random_state=42)
X_res, y_res = smoteenn.fit_resample(X, y)
print('After SMOTEENN:', np.bincount(y_res))

Evaluating SMOTE: Precision-Recall Trade-Off

After applying oversampling, always evaluate with metrics sensitive to the minority class — F1-score, ROC-AUC, or PR-AUC. SMOTE typically improves recall (fewer missed positives) but may reduce precision (more false alarms). Use the precision-recall curve to find the threshold that gives your desired operating point for the specific business cost of false positives vs false negatives.

Quick Check

Test your understanding of oversampling and SMOTE from this lesson.

Lesson Recap

In this lesson you learned: RandomOverSampler duplicates minority examples — simple but risks overfitting to repeated data, SMOTE synthesises new minority samples by interpolating between existing ones, giving the classifier richer information, and imblearn.pipeline.Pipeline ensures SMOTE is applied only to training folds, preventing data leakage. Next up we explore undersampling techniques that reduce the majority class instead of growing the minority.

البدء مجانًا

تعلم Python مع معلم ذكاء اصطناعي — مجانًا

اكتب وقم بتشغيل أكوادك الفعلية في المتصفح، واحصل على مساعدة فورية من معلم ذكاء اصطناعي متاح 24/7، واستمر من حيث توقفت على الويب أو في التطبيق.

الدورات
30
الدروس
120

الأسئلة الشائعة

هل درس «إعادة أخذ العينات العشوائية الزائدة وSMOTE» مجاني؟

نعم — نص درس «إعادة أخذ العينات العشوائية الزائدة وSMOTE» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة Machine Learning Academy، انتقل إلى CoddyKit PRO. تتضمن دورة Machine Learning Academy 4 دروس في المجموع.

ماذا ستتعلم في «إعادة أخذ العينات العشوائية الزائدة وSMOTE»؟

سيطبّق المتعلمون RandomOverSampler وSMOTE من imbalanced-learn لزيادة عينات الفئة الأقلية، ثم يقيّمون ما إذا كان الاسترجاع-الدقة قد تحسّن. تتمرن على Machine Learning Academy مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.

هل أحتاج إلى خبرة سابقة لأبدأ Machine Learning Academy؟

لا تُشترط خبرة سابقة. Machine Learning Academy على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 2 من أصل 4.

كم من الوقت يستغرق درس «إعادة أخذ العينات العشوائية الزائدة وSMOTE»؟

معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.

هل يمكنني كتابة وتشغيل أكواد في درس Machine Learning Academy هذا؟

نعم. كل درس في Machine Learning Academy يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.

جميع الدروس في هذه الدورة

  1. اكتشاف عدم التوازن: توزيع الفئات ومزالق خط الأساس
  2. إعادة أخذ العينات العشوائية الزائدة وSMOTE
  3. إعادة أخذ العينات العشوائية الناقصة ومراكز العناقيد
  4. أوزان الفئات وتحريك العتبة
← العودة إلى Machine Learning Academy