2.1.11 · D4Data Preprocessing & Feature Engineering

Exercises — Handling imbalanced datasets (SMOTE, undersampling)

2,136 words10 min readBack to topic

This page is a self-test ladder. Each problem is stated cleanly, then a fully worked solution hides inside a collapsible callout — try first, then reveal. Difficulty climbs from "do you recognise the idea?" to "can you design a whole pipeline?".

Everything here builds on the parent topic. We reuse two formulas from there. Both are re-explained the moment they appear so you never need to flip back.


Level 1 — Recognition

Exercise 1.1

A dataset has 9 700 "normal" emails and 300 "spam" emails. State (a) which class is the minority, and (b) the imbalance ratio written as majority : minority, rounded to a whole number.

Recall Solution 1.1

The minority is the smaller class → spam (300 samples). Imbalance ratio . Divide both sides by 300: , so about . Answer: (a) spam; (b) .

Exercise 1.2

Fill the blank: A model that always predicts the majority class on a dataset scores about ___ % accuracy but has a minority-class recall of ___.

Recall Solution 1.2

means majority is 99 out of every 100 samples → predicting majority every time is correct 99% of the time → 99% accuracy. Recall = (rare cases caught) / (rare cases that exist). It catches zero rare cases → recall . This is exactly the "lazy model" trap. See 3.2.4-Precision-recall-and-F1-score for why recall exposes it.


Level 2 — Application

Exercise 2.1

You have 8 000 majority and 200 minority samples. You undersample to (three majority per minority). How many majority samples do you keep, and what is the total dataset size after?

Recall Solution 2.1

Keep majority samples. Minority is untouched → 200 stay. Total .

Exercise 2.2

For the same dataset in 2.1, compute the information loss as a fraction of majority data. Recall the loss formula measures discarded majority over original majority:

Recall Solution 2.2

. So we threw away 92.5% of majority samples. Even keeping is brutal here — the majority was 40× the minority.

Exercise 2.3

SMOTE step. A minority point is , its chosen neighbour is , and . Compute .

Figure — Handling imbalanced datasets (SMOTE, undersampling)
Recall Solution 2.3

Step 1 — direction vector: . Step 2 — scale by : . Step 3 — add to : . Look at the figure: the new point sits one-quarter of the way along the segment (the orange dot), exactly where places it.


Level 3 — Analysis

Exercise 3.1

A dataset is (majority:minority). Compare two plans:

  • Plan A: undersample majority to .
  • Plan B: SMOTE the minority up to match the majority.

State the final size of each class under each plan, and which plan risks overfitting the minority and why.

Recall Solution 3.1

Plan A: keep majority. Final: 5 majority + 5 minority = 10 samples total. We discarded 495 majority points — catastrophic loss. Plan B: synthesise new minority points. Final: 500 majority + 500 minority = 1000 total. Overfitting risk → Plan B. With only 5 real minority seeds, all 495 synthetic points are interpolations among those same 5. They cluster in a tiny region, so the model memorises 5 blobs instead of learning the true minority distribution. Validate this danger with 2.1.8-Cross-validation-and-holdout-methods — always apply SMOTE inside the training fold only.

Exercise 3.2

Explain why applying SMOTE before splitting into train/test corrupts your evaluation. Give the concrete leakage mechanism.

Recall Solution 3.2

SMOTE creates a synthetic point on the line between a real point and its neighbour. If SMOTE runs on the whole dataset first, a synthetic point can be built from a pair where one seed later lands in train and its interpolation lands in test (or vice-versa). The test point is then a near-copy of a training point → the model has effectively "seen" it → test scores are inflated. This is data leakage. Correct order: split first → SMOTE the training set only → evaluate on the untouched real test set.


Level 4 — Synthesis

Exercise 4.1

Design an end-to-end pipeline for a fraud problem (1 000 000 legit, 1 000 fraud). You want (a) manageable size, (b) no leakage, (c) a metric that reflects catching fraud. Combine techniques and justify each choice.

Recall Solution 4.1

A defensible pipeline:

  1. Split first (stratified, so both folds keep the ratio) — prevents leakage, per Exercise 3.2 and 2.1.8-Cross-validation-and-holdout-methods.
  2. Moderate undersample the majority on the train fold to, say, : keep legit. This drops size from 1M to a workable ~11 000 while a ratio still leaves rich majority variety (unlike ).
  3. SMOTE the minority on the train fold up to match: synthesise fraud points → 10 000 fraud. Now .
  4. Scale features (2.1.3-Feature-scaling-and-normalization) — SMOTE uses Euclidean distance, so unscaled features would let one large-range feature dominate the neighbour search.
  5. Train a model robust to remaining imbalance, e.g. 4.1.2-Decision-trees-and-random-forests with class weights, or plug in 3.4.7-Cost-sensitive-learning.
  6. Evaluate on the untouched real test fold with F1 / recall / PR-AUC (3.2.4-Precision-recall-and-F1-score), never raw accuracy. The combo (undersample then SMOTE) shrinks the giant majority AND enriches the minority — cheaper and less overfit-prone than SMOTE alone on a 1M-row table.

Exercise 4.2

In Exercise 4.1's pipeline, after step 3 how many total training samples do you have, and what is the memory saving factor versus not undersampling at all (SMOTE-only would balance to each)?

Recall Solution 4.2

After step 3: legit fraud training samples. SMOTE-only balance would give samples. Saving factor smaller training set.


Level 5 — Mastery

Exercise 5.1

SMOTE geometry with a degenerate case. Minority points are , , and a lone outlier . You run SMOTE with (each point's single nearest neighbour). Using Euclidean distance, determine each point's nearest neighbour, then describe where synthetic points can and cannot appear — and why is dangerous.

Figure — Handling imbalanced datasets (SMOTE, undersampling)
Recall Solution 5.1

Distances (Euclidean, ):

  • : ; : . Nearest to is .
  • : ; : . Nearest to is .
  • : ; : . Nearest to is . Where synthetics appear: on segment (when or is seed) and on segment (when is seed). No synthetics land near the empty right side or off the segments. Why is dangerous: synthetics from stretch along the long line (see the red segment in the figure), sprinkling minority points through mostly-empty space that may actually be majority territory. SMOTE cannot tell an outlier from a real cluster — it faithfully interpolates noise. Fix: clean outliers first or use a variant (Borderline-SMOTE) that skips isolated points.

Exercise 5.2

Prove that every SMOTE point lies inside the convex hull of the minority samples, so SMOTE can never invent a point beyond the existing data spread.

Recall Solution 5.2

Take any synthetic point with . Rearrange: . The two weights and are each and sum to — this is a convex combination of two real minority points. A convex combination of points that are themselves in a set always lies within that set's convex hull. Therefore every synthetic point sits on a line segment between two real minority points, hence inside their convex hull. ∎ Consequence: SMOTE never extrapolates outward — it can only fill inside the minority cloud. That is why it cannot fix a minority class that is simply under-sampled in range (the true minority region is bigger than what you observed).

Recall Quick self-check

Undersample keep-count formula ::: How SMOTE achieves diversity across many synthetic points ::: each point draws a fresh random Why SMOTE runs after the train/test split ::: to prevent synthetic points leaking real neighbours across folds What convex-combination fact bounds SMOTE points ::: they lie inside the convex hull of real minority samples