CertNote/ Commute Study Notes
Roadmap
KOEN
CLF-C02 · FoundationalCloud Practitioner - Foundational
DVA-C02 · AssociateDeveloper - Associate
SAA-C03 · AssociateSolutions Architect - Associate
SOA-C02 · AssociateCloudOps Engineer - Associate
SAP-C02 · ProfessionalSolutions Architect - Professional
DOP-C02 · ProfessionalDevOps Engineer - Professional
Linux Master 2 · 2급KAIT Linux Master - Level 2
SCS-C03 · SpecialtySecurity - Specialty
Linux Master 1 · 1급KAIT Linux Master - Level 1
MLA-C01 · AssociateMachine Learning Engineer - Associate
AIF-C01 · FoundationalAI Practitioner - Foundational
DEA-C01 · AssociateData Engineer - Associate
MLS-C01 · SpecialtyMachine Learning - Specialty
  • Week 1
    • 1.The ML Lifecycle (from a Specialty Perspective)
    • 2.Data Storage for ML: S3, EFS, FSx for Lustre, and Data Formats
    • 3.Data Ingestion: Kinesis, Glue, Batch vs. Streaming
    • 4.Data Labeling: SageMaker Ground Truth, Active Learning, Label Quality
    • 5.Week 1 Comprehensive Review: ML Overview & Data Engineering 1
  • Week 2
  • Week 3
  • Week 4
    • 1.Dimensionality Reduction: PCA, t-SNE, and the Curse of Dimensionality
    • 2.Feature Selection: Filter, Wrapper and Embedded Methods, Importance, and Multicollinearity
    • 3.Data Visualization: Distributions, Correlations, QuickSight, and Drawing Insights
    • 4.Handling Class Imbalance: Oversampling, Undersampling, SMOTE, Class Weights, Evaluation
    • 5.Week 4 Comprehensive Review: Dimensionality, Feature Selection, Visualization, Imbalance
  • Week 5
  • Week 6
  • Week 7
  • Week 8
  • Week 9
  • Week 10
  • Week 11
  • Week 12
SQLD · 개발자SQL Developer (SQLD)

© CertNote · 주간랩스

  • About
  • Changelog
  • Contact
  • Terms
  • Privacy
← MLS-C01/Week 4/Day 4

Based on the MLS-C01 exam guide·Report an error

MLS-C01· AssociateWeek 4 · Day 4~29 min read

Day 4 - Handling Class Imbalance: Oversampling, Undersampling, SMOTE, Class Weights, Evaluation

📌 Key Takeaways

  • Accuracy paradox: If positives are 2%, predicting "all negative" still gives 98% accuracy. On imbalanced data, accuracy is the most misleading metric.
  • Evaluate imbalance with precision, recall, F1, and PR-AUC. The rarer the positives, the more PR-AUC > ROC-AUC holds.
  • Data-level responses: oversampling (SMOTE) and undersampling. When the data is very large and speed matters, use undersampling.
  • Algorithm-level responses: class weights (class_weight="balanced", XGBoost scale_pos_weight) and threshold adjustment.
  • Resampling must be applied only to the training set after the split, and in cross-validation only inside the training portion of each fold, to avoid leakage.

The Imbalance Trap: The Accuracy Paradox

Most real-world classification problems are imbalanced. Fraud is 0.1%, disease positives are 2%, churn is 5% — the very thing you want to catch is the minority class. If you train on the raw imbalanced data, a model can predict the majority class for everything and still get high accuracy.

On data where positives are 2%, predicting "all negative" gives 98% accuracy. Yet it catches none of the positives you actually care about. This is the accuracy paradox.

                  Predicted
              Positive    Negative
          ┌───────────┬───────────┐
 Positive │    TP     │    FN     │ ← missed positives. Cuts recall
 Actual   ├───────────┼───────────┤
 Negative │    FP     │    TN     │ ← false alarms. Cuts precision
          └───────────┴───────────┘
                                    ↑
             With imbalance, TN is overwhelmingly large, so
             accuracy = (TP+TN)/total is dominated by TN
MetricDefinitionMeaning under imbalance
Accuracy(TP+TN)/totalBiased toward the majority class, so it misleads
PrecisionTP/(TP+FP)Share of predicted positives that are actually positive
RecallTP/(TP+FN)Share of actual positives that were caught
F1Harmonic mean of precision and recallBalance of the two in a single number
PR-AUCArea under the precision-recall curveMore sensitive than ROC under imbalance

Interpreting Metrics: What to Look at in Which Situation

MetricWhat it means when it risesSituation for choosing itPitfall
AccuracyA high share of all predictions is correctOnly when classes are roughly balancedUnder imbalance, "all negative" gets the top score
PrecisionFew false alarmsFP cost is high (blocking legitimate mail as spam, unnecessary detailed inspections)If you call only the near-certain ones positive, recall collapses
RecallFew missed positivesFN cost is high (missed cancer diagnosis, undetected fraud)Calling everything positive gives recall 1.0 and rock-bottom precision
F1Precision and recall are both decentWhen you cannot give up on eitherDoes not tell you which one is more expensive
ROC-AUCPositive and negative ranks separate well across thresholdsWhen classes are relatively balancedWhen negatives are overwhelming, FPR is diluted and looks optimistic
PR-AUCPositive detection performance is good across thresholdsWhen positives are rareValues cannot be compared across datasets with different class ratios

For reference, regression metrics are a separate matter.

MetricPropertyWhen
RMSESquares errors before summing → a bigger penalty for large errorsWhen you especially need to avoid big mistakes
MAEMean of the absolute errorsWhen there are outliers and you do not want to be oversensitive to large errors

On imbalanced data, PR-AUC is more useful than ROC-AUC. The ROC x-axis (false positive rate) has all negatives (TN+FP) in its denominator, so the minority class's errors get diluted. The PR curve focuses on the positives, so it is sensitive to changes in minority-class performance. That is why "when positives are rare, as in fraud, evaluate with PR-AUC" is the standard answer.

⚠️ Pitfall: Work backward from the business cost to choose the metric. In fraud detection, a miss (FN) translates directly into losses, while a false alarm (FP) just needs a person to check once more → prioritize recall. Conversely, in mass marketing, a false alarm is itself a cost, so prioritize precision. Read "which mistake is more expensive?" first, not "which metric is good?"

Data-Level Responses: Resampling

Oversampling (increase the minority class)

  • Random oversampling: Duplicate minority samples → the same points repeat, so there is overfitting risk
  • SMOTE: Generate synthetic samples by interpolating between minority samples → preserves diversity

Undersampling (reduce the majority class)

  • Random undersampling: Remove some majority samples → risk of information loss
  • When the data is very large, undersampling speeds up training
from imblearn.over_sampling import SMOTE
from imblearn.under_sampling import RandomUnderSampler
from imblearn.pipeline import Pipeline
 
# Oversample with SMOTE, then undersample the majority class (hybrid)
pipe = Pipeline([
    ("over", SMOTE(sampling_strategy=0.3, random_state=42)),
    ("under", RandomUnderSampler(sampling_strategy=0.5, random_state=42)),
])
X_res, y_res = pipe.fit_resample(X_train, y_train)

Choosing a Resampling Technique

TechniqueChange in data sizeStrengthWeaknessWhen to choose
Random oversamplingIncreasesSimple, no information lossThe same points repeat → overfittingWhen the data is small and you cannot afford to discard any
SMOTEIncreasesGeneralizes around the decision boundaryCreates unrealistic samples in noisy or overlapping regionsWhen there are a fair number of minority samples and you need diversity
Random undersamplingDecreasesTraining gets fasterLoses majority-class informationWhen the data is very large and speed matters
Hybrid (SMOTE + under)AdjustableCompromises between both weaknessesTwo ratios must be tunedWhen finding a balance point under extreme imbalance

SMOTE (Synthetic Minority Over-sampling Technique) finds the k-nearest neighbors of a minority-class sample and interpolates between them to create new points. Unlike plain duplication, it has the effect of generalizing around the decision boundary, but it has drawbacks too — in noisy or overlapping regions it can produce unrealistic samples, it does not apply directly to categorical features (the SMOTE-NC variant is needed), and in high dimensions interpolation loses meaning.

⚠️ Pitfall: Resampling must be applied after the train/test split, only to the training set. If you apply SMOTE before splitting, synthesized positives get mixed into both the training and validation sets, causing data leakage and inflated performance. In cross-validation, use imblearn's Pipeline so that resampling happens inside each fold.

[Wrong order — leakage]           [Correct order]
 Entire dataset                    Entire dataset
      │                                │
   Apply SMOTE                      Split (train / valid)
      │                                │
   Split (train / valid)            SMOTE on train only
      │                                │
 ✗ Synthetic points from the       ✓ valid keeps the original distribution
   same originals end up split        → the performance estimate is honest
   across train and valid
   → validation score is inflated

Algorithm-Level Responses: Class Weights

Without changing the data, you give a larger penalty to minority-class errors in the loss function.

from sklearn.linear_model import LogisticRegression
 
# Weight automatically by the inverse of class frequency
clf = LogisticRegression(class_weight="balanced")
 
# XGBoost: set scale_pos_weight from the negative/positive ratio
# scale_pos_weight = (number of negatives) / (number of positives)
import xgboost as xgb
model = xgb.XGBClassifier(scale_pos_weight=49)  # negative:positive = 49:1
MethodChanges the dataStrengthWeakness
ResamplingYesIntuitive, applies to any modelWatch for leakage, overfitting, and information loss
Class weightsNoData stays as is, fastThe model must support it
Threshold adjustmentNoAdjusted after training, possible even in productionRequires work to find an appropriate threshold

Classifiers usually use a probability of 0.5 as the threshold, but this default does not work under imbalance. Threshold moving lets you adjust the recall-precision trade-off by looking at the PR curve or a cost matrix, without retraining. When the cost of a miss (missing fraud) is high, lower the threshold to raise recall.

Moving the probability threshold moves the two metrics in opposite directions

 Lower threshold ←─────────── 0.5 ───────────→ Raise threshold
 Range called positive widens          narrows
      Recall ↑  Precision ↓          Recall ↓  Precision ↑
      Missed positives ↓  False alarms ↑   Missed positives ↑  False alarms ↓
      (fraud detection · disease screening)   (mass mailing · automatic blocking)
How to set the thresholdWhat it doesWhen
The F1-maximizing point on the PR curvePicks the precision-recall balance pointWhen neither side is especially expensive
Fix a target recallThe lowest threshold that satisfies "catch 90% of positives"When the detection rate is set by regulation or policy
Cost-matrix basedAssign costs to FP and FN to minimize expected costWhen the cost of mistakes can be converted into money
Operating-capacity basedTake only the top N cases to match how many can be reviewed per dayWhen people must do the follow-up review

The threshold must be set on the validation set and confirmed on the test set. If you pick the threshold by looking at the test set, that score is no longer a generalization estimate. It is the same kind of leakage as with resampling or scaling.

Choosing Among the Techniques Overall

SituationMethod to chooseWhy
The data is small and minority samples are preciousSMOTE (oversampling)Gains diversity without discarding anything
Hundreds of millions of records, training speed mattersRandom undersamplingSpeeds things up by reducing the amount of data itself
The data must not be touched (audit, reproducibility)Class weightsOriginal data stays as is
Adjusting an already-trained model in productionThreshold movingTakes effect immediately without retraining
Many categorical featuresClass weights or SMOTE-NCBasic SMOTE cannot be applied directly to categorical features
Feature dimensionality is very highClass weightsInterpolation loses meaning in high dimensions
The cost of a miss is overwhelmingly largeLower the threshold and prioritize recallReflects the cost asymmetry through the threshold

When Imbalance Goes to the Extreme, the Approach Itself Changes

Positive ratioApproachWhy
30-50%Plain supervised learningEffectively balanced. Accuracy is usable too
1-10%Supervised learning + class weights/resampling, evaluate with PR-AUCThe typical imbalance range
0.1-1%Same as above, but threshold adjustment carries more weightFew minority samples, so resampling has limited effect
Under 0.1% or almost no labelsReframe as anomaly detectionModel the positives not as a "class" but as "what deviates from normal"

Approaches in SageMaker

  • Several built-in algorithms provide imbalance-related hyperparameters (e.g., XGBoost scale_pos_weight)
  • Before training, check class distribution and bias in advance with SageMaker Clarify
  • Set the monitoring metric to F1/PR-AUC instead of accuracy
SituationService/featureWhy
Check class distribution and bias before trainingSageMaker ClarifyComputes pre-training bias metrics
Give positives a weight in a boosting modelscale_pos_weight in SageMaker XGBoostAlgorithm-level imbalance correction
Put resampling in a pipeline to block leakageNotebook + imblearn PipelineResample only inside each fold's training portion
Watch for performance degradation in productionMonitor with F1/PR-AUC rather than accuracyUnder imbalance, accuracy cannot catch changes

Stem Clue → Answer Mapping

Stem clueAnswer to chooseWhy
"Positives are 1% but accuracy came out at 99%"Accuracy paradox → evaluate with PR-AUC and recallTN dominates the metric
"Positives are very rare, like fraud"PR-AUCROC's FPR is diluted by negatives
"Penalize minority errors without changing the data"class_weight="balanced" / scale_pos_weightAlgorithm-level response
"Negative:positive = 49:1 in XGBoost"scale_pos_weight = 49Number of negatives / number of positives
"Cross-validation together with SMOTE"Only inside each fold, using imblearn PipelineBlocks validation-set leakage
"The data is very large and training must be fast"Random undersamplingSpeeds up by reducing the amount of data
"Raise recall without retraining"Threshold movingCan be adjusted after training
"Check class distribution and bias before training"SageMaker ClarifyPre-training bias check
"The minority class was simply duplicated"Random oversampling (overfitting risk)SMOTE interpolates rather than duplicates

In the next post, we tie together the four topics of Week 4 into one workflow and compare and summarize them.

📖 Glossary

  • Class imbalance: A state in which the class you want to catch is only a few percent of the whole. Fraud, disease, and churn are typical examples.
  • Accuracy paradox: The illusion that a model looks good because accuracy comes out high even when it predicts the majority class for everything.
  • Confusion matrix: A table that crosses actual and predicted values into four cells: TP, FP, FN, and TN. It is the raw material for all classification metrics.
  • Precision: The share of "predicted positives that are truly positive." The fewer false alarms, the higher it is.
  • Recall: The share of "true positives that were caught." The fewer missed positives, the higher it is.
  • PR-AUC: The area under the precision-recall curve. When positives are rare, it reveals performance differences better than ROC-AUC.
  • SMOTE: An oversampling technique that creates new samples by interpolating between a minority-class sample and its neighbors. It is not duplication.
  • Undersampling: A method that balances the ratio by discarding part of the majority class. It is fast but loses information.
  • Class weights: A setting that makes the loss larger when the minority class is wrong. It does not touch the data.
  • Threshold moving: Shifting the probability cutoff away from 0.5 to change the balance between recall and precision. No retraining is needed.

📝 Practice Questions

Click a choice to reveal the answer and explanation.

Question 1

You want to evaluate model performance on fraud detection data in which positives are 1% of the total. Which single metric is the LEAST appropriate?

Question 2

Which statement about SMOTE is correct?

Question 3

Without changing the data, you want XGBoost to penalize misclassification of the minority (positive) class more heavily. Which setting is appropriate?

Question 4

When applying SMOTE together with cross-validation, what is the correct way to prevent data leakage?

Question 5

Positives are extremely rare in fraud detection. What is the MOST appropriate reason to prefer PR-AUC over ROC-AUC?

PreviousData Visualization: Distributions, Correlations, QuickSight, and Drawing InsightsWeek 4 · Day 3Next Week 4 Comprehensive Review: Dimensionality, Feature Selection, Visualization, ImbalanceWeek 4 · Day 5

Official references

  • MLS-C01 official exam page(opens in a new tab)
  • Amazon SageMaker AI documentation(opens in a new tab)

On this page

  • Key Takeaways
  • The Imbalance Trap: The Accuracy Paradox
  • Interpreting Metrics: What to Look at in Which Situation
  • Data-Level Responses: Resampling
  • Oversampling (increase the minority class)
  • Undersampling (reduce the majority class)
  • Choosing a Resampling Technique
  • Algorithm-Level Responses: Class Weights
  • Choosing Among the Techniques Overall
  • When Imbalance Goes to the Extreme, the Approach Itself Changes
  • Approaches in SageMaker
  • Stem Clue → Answer Mapping
  • Glossary
  • Practice Questions