Lesson 7 of 9
Imbalanced Learning: Cost-Sensitive Weighting, SMOTE & Tomek Links
When dealing with severe class imbalance (fraud, medical diagnosis), standard empirical risk minimization fails. There are two primary paradigms to counter imbalance: Algorithmic Modification (cost-sensitive loss weighting via `class_weight='balanced'`) and Data Resampling (synthetic minority oversampling via SMOTE, majority undersampling via Tomek Links or RandomUnderSampler). Cost-sensitive weighting is typically preferred in production for latency and reproducibility.
Comparing Cost-Sensitive Class Weighting vs SMOTE
import numpy as np
import pandas as pd
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report, average_precision_score
# Generate heavily imbalanced dataset (98% negative, 2% positive)
X, y = make_classification(
n_samples=5000, n_features=10, weights=[0.98, 0.02],
flip_y=0.01, random_state=42
)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42, stratify=y)
print(f"Training split: {np.bincount(y_train)[0]} negative, {np.bincount(y_train)[1]} positive")
# 1. BASELINE UNWEIGHTED MODEL (Fails on minority class)
clf_unweighted = LogisticRegression(random_state=42)
clf_unweighted.fit(X_train, y_train)
y_pred_unweighted = clf_unweighted.predict(X_test)
print("\n--- UNWEIGHTED MODEL (Default 1:1 penalty) ---")
print(classification_report(y_test, y_pred_unweighted, target_names=['Normal', 'Fraud'], digits=3))
# 2. COST-SENSITIVE WEIGHTED MODEL (class_weight='balanced')
# Penalizes minority classification errors proportionally: w_j = n_samples / (n_classes * n_samples_j)
clf_balanced = LogisticRegression(class_weight='balanced', random_state=42)
clf_balanced.fit(X_train, y_train)
y_pred_balanced = clf_balanced.predict(X_test)
print("--- COST-SENSITIVE BALANCED MODEL ---")
print(classification_report(y_test, y_pred_balanced, target_names=['Normal', 'Fraud'], digits=3))
# 3. PROBABILITY PR-AUC BENCHMARK
pr_auc_unweighted = average_precision_score(y_test, clf_unweighted.predict_proba(X_test)[:, 1])
pr_auc_balanced = average_precision_score(y_test, clf_balanced.predict_proba(X_test)[:, 1])
print(f"Unweighted PR-AUC: {pr_auc_unweighted:.4f} | Balanced PR-AUC: {pr_auc_balanced:.4f}")Pro Tip: Why `class_weight='balanced'` Beats Oversampling in Production
Using `class_weight='balanced'` modifies the gradient loss function mathematically without altering training data geometry or adding synthetic samples. This avoids increasing training runtime, eliminates the risk of synthesizing noisy outlier points in feature space, and works natively inside Scikit-Learn without requiring external imbalanced-learn dependencies.
MlHandlingImbalancedData Visual Representation
Hands-On Challenge: Threshold Tuning for Recall Targets
Write an optimization function that takes predicted probabilities from `clf_balanced`, sweeps the classification threshold from 0.01 to 0.99, and selects the exact threshold that achieves 90% Recall on the positive class with maximum possible Precision.
Quick Quiz & Key Concept Checks
Common Pitfall: Using SMOTE Inside Standard Scikit-Learn Pipelines
Scikit-Learn's native `Pipeline` does not support resampling because transformers must implement `.transform()`, which cannot change sample row count. If you use SMOTE, you must use `imblearn.pipeline.Pipeline` instead.