Resampling and Class Weighting
Explore methods for managing imbalanced datasets in classification tasks by applying resampling and class weighting. Understand the risks of data leakage, how to properly split datasets, and methods like undersampling, oversampling, SMOTE, and class weighting. Learn to evaluate models reliably using untouched validation data and interpret the impact of these techniques on recall and precision.
Oversampling a rare-event dataset before a train/test split can produce a validation score that looks excellent while the model has already seen duplicates of its test examples. The score is wrong because evaluation data must represent unseen cases. After diagnosing imbalance with recall and average precision, we can help a classifier find positives in two different ways without contaminating that evaluation.
Resampling changes the class balance of the training data. Class weighting leaves the training rows unchanged but makes mistakes on the minority class count more during fitting. Neither option is automatically better. The right choice depends on the data, the model, and whether generated or duplicated examples would distort the problem.
Change the training distribution
Random undersampling removes some majority-class rows. If a fraud training set contains 90 legitimate transactions and 10 fraud cases, undersampling can retain all 10 fraud cases while dropping many legitimate rows. The resulting training set is smaller, so fitting becomes faster, but the classifier loses information about legitimate transaction patterns.
Random oversampling duplicates minority-class rows. The same 10 fraud cases may appear repeatedly until the training classes have similar counts. Oversampling preserves every majority-class row, but repetition can make a flexible model fit peculiarities of the few original positive examples.
The counts and predicted positive rates below show how changing the training distribution can change a logistic regression model’s decisions on the same untouched test inputs.
Lines 4–6: The code imports
RandomOverSamplerandRandomUnderSamplerfrom imbalanced-learn andLogisticRegressionfrom scikit-learn.Lines 12–24: The train and ...