AI & Machine Learning Master Course — 039. Dataset imbalance and sampling strategies
Smartyfy AI & Machine Learning Master Course
Course ID: smartyfy-ai-ml-master-200
Lesson 039: Dataset imbalance and sampling strategies
Prerequisites: Lesson 038. Learning outcome: Compare class weighting and training-only resampling under suitable metrics.
1. An impressive accuracy can miss the entire problem
Imagine one hundred parcels, five of which are damaged. A predictor that always says undamaged is correct ninety-five times. Its accuracy is 95%, but it identifies none of the damaged parcels. The problem is not that accuracy is mathematically incorrect; it answers a question that hides the minority outcome relevant to this decision.
Class imbalance describes unequal class frequencies. Whether it requires intervention depends on the task, error costs, sample size, and available signal. A rare class with thousands of clear examples can be easier than a balanced problem with overlapping classes. Before changing training, inspect label quality, group structure, and whether the dataset prevalence matches the intended population.
2. Use metrics that expose the trade-off
Recall for damage is the fraction of truly damaged parcels detected. Precision is the fraction of damage alerts that are correct. Increasing alerts can improve recall while overwhelming reviewers with false positives. Report the underlying counts and denominators, not just a single score. With only five positive examples, one changed prediction moves recall by twenty percentage points.
Binary balanced accuracy averages positive-class recall and negative-class recall. For the always-undamaged classifier, these recalls are zero and one, producing 0.5. This reveals the baseline's failure more clearly than 95% accuracy, but it still assigns equal importance to both class recalls rather than encoding a particular operational cost.
Precision depends on prevalence as well as detection behavior. If positives become rarer while sensitivity and false-positive rate stay fixed, fewer alerts will be true positives. Therefore a score obtained on an artificially balanced evaluation set may not describe the workload in deployment. Preserve the intended evaluation distribution or explicitly account for the sampling design.

3. Weighting changes the training objective
Class weighting gives examples different contributions to the fitted loss. A balanced weighting rule assigns each class total equal weight: for class k, weight = n/(K × n_k), where n is the training count, K is the number of classes, and n_k is that class’s count. With 95 negatives and five positives, negative weight is about 0.5263 and positive weight is ten. Each class then contributes total weight fifty.
Weights do not create new information. They express a chosen emphasis during optimization and can change the decision boundary. Balanced weighting is a heuristic, not an automatically correct cost model. It may improve minority recall while reducing precision. Probabilities from a weighted classifier may need separate calibration on representative development data before being used as real-world event probabilities.
The demonstration compares ordinary and balanced logistic regression at their default decision rule. Logistic regression is introduced formally later. Here it is simply a controlled way to observe the effect of changing one training choice. The synthetic example is deliberately small and cannot establish that weighting is universally superior.
4. Resample only the training portion
Random oversampling repeats minority training observations. Random undersampling removes some majority observations, potentially discarding useful structure. Synthetic methods interpolate or otherwise create training examples under additional assumptions; mixed categories, scarce groups, and sparse text require care. None of these operations should alter the final evaluation set to make scores look more favorable.
Split before resampling. Within cross-validation, perform resampling separately inside each training fold. Duplicating rows before a random split can place copies in both training and validation. Synthetic construction before splitting can also use held-out neighbors. An appropriate resampling pipeline is needed; an ordinary transformer pipeline is not automatically suitable for steps that change the number of rows.
Stratification can preserve class proportions when a random split is appropriate, but cannot manufacture rare examples or fix temporal dependence. If a fold contains no positive cases, some metrics become undefined or uninformative. Plan the evaluation size around the rare class, report uncertainty, and prefer a group- or time-respecting design when the application requires it.
CPU lab: compare one weighting choice
Run locally with NumPy and scikit-learn; no external dataset or extra imbalance package is needed. The first section verifies the 95% accuracy, 0.5 balanced accuracy, zero recall, and class weights by arithmetic. The next section makes five hundred synthetic observations and reserves thirty percent as development validation before fitting either pipeline.
In the checked run, the ordinary classifier predicts no positives: recall is zero and precision is reported as zero by the chosen zero_division convention. Balanced weighting gives precision about 0.2093, recall 0.6, and balanced accuracy 0.6741. These are validation observations for two prespecified examples. If they guide a deployment choice, a separate final evaluation is still needed.
import numpy as np
from sklearn.metrics import accuracy_score, balanced_accuracy_score, precision_score, recall_score
from sklearn.utils.class_weight import compute_class_weight
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.datasets import make_classification
truth = np.array([0]*95 + [1]*5)
guess = np.zeros(100, dtype=int)
print('Majority baseline:', accuracy_score(truth, guess),
balanced_accuracy_score(truth, guess), recall_score(truth, guess))
weights = compute_class_weight(class_weight='balanced', classes=np.array([0,1]), y=truth)
print('Weights:', weights.round(4).tolist())
assert np.allclose(weights, [100/190, 100/10])
X, y = make_classification(n_samples=500, n_features=5, n_informative=3,
n_redundant=0, weights=[.9,.1], flip_y=0, random_state=8)
X_train, X_valid, y_train, y_valid = train_test_split(X, y, test_size=.3,
stratify=y, random_state=9)
for weighting in [None, 'balanced']:
model = make_pipeline(StandardScaler(), LogisticRegression(class_weight=weighting, max_iter=1000))
model.fit(X_train, y_train)
p = model.predict(X_valid)
print(weighting, 'precision/recall/balanced accuracy',
round(precision_score(y_valid,p,zero_division=0),4),
round(recall_score(y_valid,p),4), round(balanced_accuracy_score(y_valid,p),4))
Four practice questions with worked answers
Practice 1
A model finds four of five damaged parcels but raises twenty alerts. Calculate recall and precision.
Answer: Recall is 4/5 = 0.8. Precision is 4/20 = 0.2. Sixteen alerts are false positives and one damaged parcel is missed. Whether that is acceptable depends on inspection cost and the consequence of a missed damaged parcel; neither metric alone decides the operational policy.
Practice 2
Compute balanced class weights for ninety negatives and ten positives in one hundred rows.
Answer: There are two classes. The negative weight is 100/(2×90) = 5/9, about 0.5556. The positive weight is 100/(2×10) = 5. Their total contributions are ninety times 5/9 = fifty and ten times five = fifty.
Practice 3
A team duplicates each rare-class row ten times and then splits randomly. Explain the failure and repair.
Answer: Copies of the same observation can appear on both sides of the split, allowing apparent generalization to duplicates. Split the original independent units first. Duplicate only rows belonging to a training partition, and repeat that process separately inside each cross-validation training fold. Leave validation and final test distributions untouched.
Practice 4
Why is a precision of 80% on a balanced test set insufficient for a population with 1% positives?
Answer: Precision depends on how many true positives are available relative to false positives. A balanced test set has far more positive opportunities than the deployment population. Estimate sensitivity and false-positive behavior on an appropriate design, account for target prevalence when justified, and evaluate on representative data rather than transporting the precision number unchanged.
Five multiple-choice questions
Question 1
Always predicting the majority class guarantees what?
- A. High accuracy when the majority is large
- B. Useful minority recall
- C. Good calibrated probabilities
Correct: A. Accuracy can be high while minority recall is zero. The other properties do not follow.
Question 2
Balanced accuracy averages what?
- A. Class recalls
- B. Predicted probabilities
- C. Feature means
Correct: A. Each class contributes its recall equally, which differs from weighting every observed row equally.
Question 3
Where should oversampling occur in cross-validation?
- A. Before all splits
- B. In the held-out fold
- C. Only in each training fold
Correct: C. This keeps copied or synthetic observations from importing information across evaluation boundaries.
Question 4
Does weighting guarantee better calibration?
- A. Only for rare classes
- B. Yes
- C. No
Correct: C. Weighting changes optimization emphasis and can change probability interpretation; calibration needs its own evidence.
Question 5
What does zero_division=0 do here?
- A. Chooses a reporting convention when there are no positive predictions
- B. Makes undefined precision perfect
- C. Creates positive predictions
Correct: A. The convention avoids an undefined printed ratio. It does not repair the classifier or provide evidence of positive predictive value.
Common pitfalls
Do not describe synthetic examples as new independent evidence. Do not choose a threshold on the final test set, and do not report only accuracy when the costly errors concern a rare class. Preserve class counts and error counts so readers can see when a metric rests on very little data.
Summary
Treat imbalance as a data-and-decision problem. Compare meaningful baselines, report complementary metrics, choose weighting or training-only resampling deliberately, and keep evaluation representative. More minority emphasis can trade precision for recall without creating additional signal.