How to Handle Imbalanced Datasets in Machine Learning: SMOTE, Class Weights and Evaluation Metrics

A student designs a classifier to flag rare equipment failures. In the observations, 95% of records show ordinary operation and only 5% are labelled failures. The student reports an impressive 95% accuracy. Yet when a teacher checks the individual predictions, the system has labelled every single failure as ordinary. It has found precisely zero of the events it was supposed to detect. A single percentage looked persuasive, but the underlying model was useless for this particular task.

This tutorial teaches you to recognize that problem, build a proper baseline, evaluate minority-class predictions, compare class weights against random resampling and SMOTE, and preserve an untouched test set. You will reproduce a complete Python experiment, interpret real model outputs, explore threshold and probability-calibration issues, and complete thirty practice questions. It continues the Notes for SHS lesson on Logistic Regression, Decision Trees and Random Forests (Topic 87), but concentrates on what happens when one target class is rare.

Verified experiment — 25 November 2026. This lesson uses a synthetic 5,000-record numerical classification dataset, random seed 88, Scikit-Learn 1.8.0 and imbalanced-learn 0.14.1. The observed labels are exactly 4,750 majority and 250 minority; the stratified 80/20 split preserves 3,800/200 for training and 950/50 for testing. We actually executed five-fold cross-validation for seven candidates. A class-weighted Random Forest won on training-only Average Precision (0.6152) and achieved test Average Precision 0.5817, test accuracy 95.8%, precision 64.29%, recall 36%, F1 46.15%, balanced accuracy 67.47% and ROC-AUC 0.9206. All results apply only to this synthetic experiment, not to real-world equipment.

What is class imbalance in machine learning?

Class imbalance occurs when some target labels appear far more frequently than others in a classification dataset. The more frequent label is the majority class; the less frequent label is the minority class. Our synthetic project uses Class 0 for ordinary events and Class 1 for the rare target. There are 4,750 Class 0 records (95%) and 250 Class 1 records (5%). These labels are choices for this exercise; in another application the positive class might be encoded differently. Always check the actual mapping.

Imbalance is not automatically a defect in data collection. Real events may simply occur rarely. Forcing every dataset into a 50:50 split can misrepresent the population. The relevant question is whether the amount, quality, representativeness and separability of minority examples allow a model to make decisions with acceptable errors. An uncommon class can be easy to detect if its features are distinctive; a moderately uncommon class can be difficult if the classes overlap.

ClassObservationsShareInterpretation
Class 04,75095%Majority / ordinary event
Class 12505%Minority / rare event
Total5,000100%Original synthetic population

Calculating imbalance ratios and interpreting severity

The imbalance ratio is the majority count divided by the minority count. Here 4,750 ÷ 250 = 19:1: nineteen majority records are available for every minority record. A class proportion is calculated as its count divided by the total. For Class 1 this is 250 ÷ 5,000 = 0.05, or 5%. Students should always report both percentages and absolute counts because they describe different aspects of the problem.

Informal terms such as mild, moderate and severe imbalance are useful descriptions, but there is no universal threshold separating them. One percent of a million examples still supplies 10,000 minority examples; one percent of a hundred provides only one. Multiclass problems add another complication: three or more categories may have very unequal counts, and different classes may need different handling. Label noise, subgroup differences, feature overlap and time variation may matter more than the imbalance ratio alone.

Why classifiers can struggle with rare labels

Many algorithms learn patterns by minimizing average training errors. When 95 of every 100 examples belong to one class, doing well on that class may dominate the objective, and minority mistakes may be masked in aggregate results. Rare labels also have fewer examples from which to learn variation. A few incorrect labels or unusual measurements can disproportionately affect the minority. Models may score uncommon cases correctly but use a threshold that produces almost no positive predictions.

Other challenges include weak features, shifting prevalence, overlapping class distributions and uncertain validation estimates. Imagine fifty test positives: missing ten changes recall by twenty percentage points. Consequently, model performance on rare classes should be interpreted with the sample size, confidence and use case in mind. Imbalance does not prove that a model is biased, broken or inaccurate; it tells us to inspect evaluation more carefully.

The 95% accuracy paradox

Use a 1,000-record test set with 950 negative and 50 positive cases. A classifier that predicts negative for everyone makes 950 correct predictions, giving accuracy 950/1,000 = 95%. But it identifies 0/50 true positives, giving minority recall 0%. Majority recall is 950/950 = 100%; balanced accuracy is (1 + 0)/2 = 50%. The baseline is therefore not evidence of useful rare-event discrimination.

Accuracy answers What fraction of all labels were predicted correctly?, not How many rare events were found?. When failures are expensive to miss, an accurate majority-only classifier may be a poor operational choice. Conversely, predicting everything positive could attain 100% recall at the price of many false alarms. Evaluation should measure both sides and the consequences of each kind of mistake.

Start with a stratified and untouched test set

We generate 5,000 records and reserve 20% for final testing. A stratified random split maintains the original label proportions: training contains 3,800 negatives and 200 positives, while testing contains 950 negatives and 50 positives. Scikit-Learn’s train_test_split(X, y, test_size=0.20, stratify=y, random_state=88) accomplishes this for independent observations. Verify the counts in Python rather than assuming a split always matches an ideal table.

The evaluation set should represent the intended target population. Resampling it into a balanced set may inflate precision and Average Precision relative to real operation. Do not fit a scaler, generate SMOTE records, undersample, select features or tune a threshold using test labels. For grouped users, repeated machines, future predictions or chronological records, group-aware or time-respecting splits may be better than random stratification; splitting must reflect how the model will be used.

PartitionClass 0Class 1Total
Training3,8002004,000
Untouched test950501,000
Original4,7502505,000

Build a majority-only baseline before a complicated model

A DummyClassifier(strategy='most_frequent') predicts the training majority class for every new record. It uses no meaningful relationship between features and outcomes, making it a clear minimum comparison. In the experiment its held-out accuracy is 0.9500, positive recall is zero, F1 is zero and balanced accuracy is 0.5000. The observed Average Precision is 0.0500, equal to the test prevalence for a constant score ranking.

Positive precision is mathematically undefined if a system predicts no positives at all because its denominator is zero. Scikit-Learn reports precision as zero when explicitly told zero_division=0. That is a reporting convention, not a proof that the undefined fraction was mathematically equal to zero. The baseline shows why a candidate model must offer more than a superficially high accuracy score.

Understand the confusion matrix before computing metrics

For binary classification, a true positive (TP) is a correctly detected event, a false positive (FP) is an ordinary case incorrectly flagged, a false negative (FN) is a missed event, and a true negative (TN) is an ordinary case correctly dismissed. Confusion matrices expose the actual kinds of errors that a single summary measure conceals. Always declare which label is positive; we use Class 1 throughout.

Consider a separate, deliberately constructed arithmetic example: TP = 36, FP = 24, FN = 14 and TN = 926. It contains 50 actual positives, 950 actual negatives and 1,000 observations in total. It is not the output of our trained Random Forest or any specific SMOTE model. We use it only to verify formulas independently.

Actual classPredicted positivePredicted negativeTotal
Positive36 TP14 FN50
Negative24 FP926 TN950
Total609401,000

Precision, recall, specificity, F1 and balanced accuracy

Precision = TP/(TP + FP) asks how trustworthy positive alarms are. In our worked matrix this is 36/60 = 60%. Recall = TP/(TP + FN), also called sensitivity or true positive rate, asks how many actual positives were detected: 36/50 = 72%. Specificity = TN/(TN + FP) evaluates the actual negatives: 926/950 = 97.47%. The false-positive rate is FP/(FP + TN) = 24/950 = 2.53%.

F1 = 2PR/(P + R) is the harmonic mean of precision and recall, giving 2×0.60×0.72/(0.60+0.72) = 65.45%. Equivalently, 2TP/(2TP+FP+FN) = 72/110. Balanced accuracy = (recall + specificity)/2 = (0.72 + 926/950)/2 = 84.74%. Ordinary accuracy is (36+926)/1,000 = 96.2%. Each metric answers a different question; F1 omits true negatives and balanced accuracy is not a complete cost model.

Choose evaluation measures around the research question

If an alarm triggers a costly manual investigation, precision helps estimate how frequently alarms are justified. If failing to detect an event creates danger or delays necessary maintenance, recall receives more weight. Some applications require a minimum recall subject to an acceptable alert workload. Others need calibrated probabilities or a weighted cost model. A high F1 does not guarantee suitable decisions, and the optimal trade-off cannot be decided by a metric name alone.

The F-beta family adjusts the relative emphasis on recall: beta greater than one weights recall more, while beta less than one weights precision more. Yet even that family cannot encode every operational constraint. When reporting results, show the raw confusion-matrix counts, the positive prevalence, the chosen threshold and why the selected measures are relevant.

ROC curves, precision–recall curves and Average Precision

An ROC curve plots true-positive rate against false-positive rate as a score threshold changes. Its area, ROC-AUC, describes a ranking property of model scores. A precision–recall curve shows precision against recall over thresholds; it can be especially informative when positives are rare because its precision directly reflects the burden of false alarms. However, ROC-AUC is not universally useless for imbalanced data; it answers a different question.

Scikit-Learn’s average_precision_score summarizes the precision–recall sequence using changes in recall as weights. This Average Precision is not identical to the trapezoidal area under the plotted curve. A constant-score no-information baseline in our 5% positive test sample has AP = 0.05. A much higher score indicates a more useful ranking in this experiment, but it is not the same as recall at a particular threshold. Both prevalence and sampling design affect interpretation.

Random oversampling: repeat existing minority examples

Random oversampling creates a larger training sample by repeatedly selecting existing minority examples, ordinarily with replacement. In our 4,000-row training data, balancing to 3,800 examples per class produces 7,600 training rows. Some of the original 200 positive observations appear multiple times. This simple method can help models that otherwise neglect the minority but it does not provide newly collected, independent positive observations.

The strengths are simplicity and preserving feature values; its limitations include repeated noise, potential overfitting and increased training size. It is an appropriate experimental comparator, not an automatic improvement. In a pipeline, RandomOverSampler(random_state=88) should operate only on the fitting portion of each cross-validation fold.

Random undersampling: discard majority examples

Random undersampling instead reduces the more common class. Balancing this training partition by retaining 200 negative and 200 positive observations gives only 400 fitting rows; 3,600 of the original majority examples are omitted. This can accelerate training on large datasets and make a classifier attend to positives, but the discarded cases may contain important boundaries, rare normal behaviours or other useful diversity.

An undersampled learner may therefore lose specificity or produce unstable results, especially when the starting data are small. The method can also change probability calibration because training prevalence differs from the target population. Use RandomUnderSampler(random_state=88) inside cross-validation, and test performance on the original untouched prevalence rather than on the small balanced sample.

What is SMOTE and how are synthetic examples created?

SMOTE means Synthetic Minority Over-sampling Technique. Rather than merely duplicating minority rows, standard SMOTE interpolates numerical feature vectors between existing minority examples and selected minority nearest neighbours. Its basic expression is x_new = x_i + λ(x_neighbour − x_i), where x_i and x_neighbour are vectors, and λ lies between zero and one. The synthetic vector lies on a line segment in feature space; it is not a newly observed real-world event.

For example let A = (2,4), B = (6,8) and λ = 0.25. The difference B−A is (4,4). A quarter of it is (1,1); adding to A yields the synthetic point (3,5). This two-dimensional demonstration explains the arithmetic, but it is not represented as a point returned by the main experiment. In the training dataset, standard SMOTE with a fully balanced target grows the positive class from 200 to 3,800: 3,600 synthetic vectors are added and the resampled training sample contains 7,600 rows.

How SMOTE works in a training fold

First identify the minority observations in the current training fold. Next, for a selected minority observation, find nearby minority-class neighbours using the chosen distance space. Select a neighbour, choose an interpolation factor, construct a new numerical feature vector and repeat as needed. Finally fit the classifier on those transformed and augmented training observations. During cross-validation, each fold fits its own scaler and SMOTE model; the validation examples are neither used to generate synthetic samples nor resampled themselves.

The neighbour parameter k_neighbors determines which nearby examples may be chosen. A setting of five needs enough minority observations in each fitting fold; even a valid numerical setting is no guarantee of meaningful synthetic cases. Since distance is sensitive to feature magnitude, scaling belongs before SMOTE when different numeric variables have unlike scales. This does not mean standard scaling is best for every physical or statistical dataset.

When SMOTE helps, and when it creates problems

SMOTE may be worth testing when there are reasonably numerous and diverse positive examples, numerical distances are meaningful and the synthetic interpolation stays within plausible feature regions. It can sometimes improve recall, but it may simultaneously decrease precision or Average Precision. In our experiment the SMOTE-plus-Logistic-Regression candidate did not outperform the class-weighted Random Forest on cross-validated Average Precision. One experiment is evidence about one setup, not an argument that SMOTE is generally inferior.

Common hazards include neighbour interpolation across overlapping classes, synthetic points inconsistent with real constraints, amplification of mislabeled positives, sparse samples, unreliable high-dimensional distances and costly extra rows. Standard SMOTE should not be naïvely used on raw documents, images, sequences, geographic identifiers, arbitrary category codes or highly constrained physical values. With mixed numerical and categorical features, investigate SMOTENC; with entirely categorical features, investigate SMOTEN. Each method still requires validation and appropriate preprocessing.

Class weights: change the learning objective without adding rows

Class weighting increases or decreases the training contribution of examples depending on their label. For algorithms that support it, class_weight='balanced' uses the formula n_samples/(n_classes × n_samples_in_class). With 4,000 training examples and two classes, the majority weight is 4,000/(2×3,800) = 0.5263; the minority weight is 4,000/(2×200) = 10.0. A minority error therefore receives much greater relative weight under this convention.

Weighted Logistic Regression modifies the contribution of examples to its fitted loss, while Random Forest class weights can affect the impurity-based training procedure. Weights generally do not add samples or create synthetic feature values. They can be useful when numeric interpolation is inappropriate, but may worsen precision, calibration or some ranking measures. During cross-validation the balanced weight calculation should be based on each fitting fold and should never use labels in the held-out test set.

AspectClass weightsRandom oversamplingSMOTERandom undersampling
Adds synthetic vectorsNoNoYesNo
Changes fit rowsNoYesYesYes, fewer
Needs numeric neighbour distancesNoNoYesNo
Typical hazardUnhelpful cost trade-offRepeated noisy casesImplausible synthetic featuresLost majority information
Where appliedTraining fold objectiveTraining fold samplerTraining fold samplerTraining fold sampler

The most important rule: prevent data leakage

An invalid workflow is full dataset → SMOTE → train/test split. In that order, feature information from would-be test observations can influence synthetic examples that later enter training. The test class balance can also become artificially equal, producing scores that do not represent deployment. Even if a separate test split is made first, applying SMOTE to all training rows and then cross-validating the resampled data risks highly related source and synthetic samples appearing on opposite sides of validation boundaries.

The correct procedure is original data → train/test split → cross-validated pipeline that fits scaling and sampling inside each training fold → model selection → final training fit → untouched test evaluation. Use imblearn.pipeline.Pipeline when a sampler is present; a plain Scikit-Learn Pipeline does not implement that sampler interface. Leakage can also enter through feature selection, normalization, duplicate records, time-related features and target-derived variables.

A safe preprocessing and cross-validation architecture

For our entirely numerical example, an imbalanced-learn pipeline contains StandardScaler, then SMOTE(random_state=88), then LogisticRegression(max_iter=1500). During each cross-validation fit, the scaler learns parameters only from the fitting subset, SMOTE creates training-only synthetic examples in that scaled space and Logistic Regression fits the resulting data. At validation time, the model transforms and predicts on natural, unresampled observations.

We use a shuffled, stratified five-fold splitter with seed 88. Each fold supplies its own estimate of Average Precision; their mean ranks candidates. All model selection happens using training data. After a winning candidate is chosen, it is refitted on the entire 4,000-row training partition, and only then are final predictions and scores computed for the 1,000-row test. A genuinely independent final test cannot be reused repeatedly to decide which approach looks best.

Install and generate the reproducible Python dataset

In Python 3, install the numerical and machine-learning packages with python -m pip install numpy pandas scikit-learn imbalanced-learn matplotlib. Run the notebook or script in Jupyter, Google Colab or a local environment. Record the library versions because numerical results and APIs can change between releases. The fixed seed improves reproducibility within an environment, although different platform/library versions can still produce small differences.

The following code creates the synthetic 95:5 dataset, prints class counts, builds an 80/20 split and verifies all observed totals. flip_y=0.0 ensures the generator does not randomly flip the supplied target labels; n_informative=5 and n_redundant=2 describe how the ten numeric feature columns are constructed. No customer, equipment or medical records are used.

import numpy as np
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
X, y = make_classification(
    n_samples=5000, n_features=10, n_informative=5,
    n_redundant=2, n_repeated=0, n_clusters_per_class=2,
    weights=[0.95, 0.05], flip_y=0.0,
    class_sep=1.0, random_state=88
)
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, stratify=y, random_state=88
)
print("Original:", np.bincount(y))
print("Training:", np.bincount(y_train))
print("Test:", np.bincount(y_test))
# [4750  250] / [3800  200] / [950  50]

Build a complete model comparison without leaking validation data

The next reproducible program compares an unweighted Logistic Regression, a weighted Logistic Regression, a weighted Random Forest, SMOTE with Logistic Regression, repeated minority samples and undersampled majority cases against a majority-only baseline. Each classifier is evaluated on the same five training-only folds with Average Precision. A sampler appears only inside an imbalanced-learn Pipeline. The independent test is not consulted during comparison or candidate selection.

This design is deliberately modest: a handful of transparent models and a fixed experimental plan. In a research project you would extend the process to nested tuning, temporal or group splits where needed, class-specific uncertainty estimates, calibration and threshold policies. Do not assume combining weights with SMOTE is beneficial: it may overcompensate. The right comparison asks whether an intervention improves the actual chosen validation objective and the resulting trade-offs.

from sklearn.base import clone
from sklearn.dummy import DummyClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import StratifiedKFold, cross_val_score
from imblearn.pipeline import Pipeline as ImbPipeline
from imblearn.over_sampling import SMOTE, RandomOverSampler
from imblearn.under_sampling import RandomUnderSampler

def lr(weight=None):
    return LogisticRegression(
        class_weight=weight, max_iter=1500, random_state=88
    )

models = {
    "Baseline": DummyClassifier(strategy="most_frequent"),
    "Unweighted Logistic Regression":
        Pipeline([("scale", StandardScaler()), ("model", lr())]),
    "Weighted Logistic Regression":
        Pipeline([("scale", StandardScaler()),
                  ("model", lr("balanced"))]),
    "Weighted Random Forest":
        RandomForestClassifier(n_estimators=150, min_samples_leaf=3,
                               class_weight="balanced",
                               random_state=88, n_jobs=-1),
    "SMOTE + Logistic Regression":
        ImbPipeline([("scale", StandardScaler()),
                     ("smote", SMOTE(k_neighbors=5, random_state=88)),
                     ("model", lr())]),
    "Random Oversampling + Logistic Regression":
        ImbPipeline([("scale", StandardScaler()),
                     ("ros", RandomOverSampler(random_state=88)),
                     ("model", lr())]),
    "Random Undersampling + Logistic Regression":
        ImbPipeline([("scale", StandardScaler()),
                     ("rus", RandomUnderSampler(random_state=88)),
                     ("model", lr())])
}
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=88)
cv_ap = {}
for name, estimator in models.items():
    values = cross_val_score(
        estimator, X_train, y_train,
        cv=cv, scoring="average_precision"
    )
    cv_ap[name] = values.mean()
    print(name, round(values.mean(), 4))
winner = max((n for n in models if n != "Baseline"),
             key=lambda n: cv_ap[n])
final_model = clone(models[winner]).fit(X_train, y_train)
print("Selected by training CV:", winner)

The real five-fold model comparison: what actually won?

We executed the full experiment with Scikit-Learn 1.8.0 and imbalanced-learn 0.14.1. Five-fold means are shown below, rounded to four decimals. Weighted Random Forest scored 0.6152 in training-only cross-validation, compared with 0.1944 for SMOTE plus Logistic Regression and 0.3123 for unweighted Logistic Regression. For this synthetic feature structure, the weighted ensemble ranked minority examples better than the other tested candidates. This is not evidence that SMOTE always underperforms or that forests are universally optimal.

The exercise demonstrates why comparing interventions matters: oversampling and class weights are hypotheses, not performance guarantees. These are measured results of a specific dataset, random state, algorithm family, preprocessing and evaluation design. They should not be copied into another study or presented as expected performance on real fraud, maintenance or customer data.

Candidate modelMean five-fold training AP
Majority baseline0.0500
Unweighted Logistic Regression0.3123
Weighted Logistic Regression0.1874
Weighted Random Forest — selected0.6152
SMOTE + Logistic Regression0.1944
Random Oversampling + Logistic Regression0.1875
Random Undersampling + Logistic Regression0.1589

Report held-out predictions, not invented accuracy

The preselected weighted Random Forest made 18 true-positive predictions, missed 32 actual positives, flagged 10 negatives incorrectly and correctly rejected 940 negatives. Consequently, test accuracy is (18+940)/1,000 = 95.8%, precision is 18/(18+10) = 64.29%, recall is 18/50 = 36.00%, F1 is 36/(36+10+32) = 46.15%, and balanced accuracy is (18/50 + 940/950)/2 = 67.47%.

The held-out Average Precision was 0.5817 and ROC-AUC was 0.9206. These ranking measures are high relative to the 0.05 constant-score baseline, yet recall at the model’s default decision threshold was only 36%. That difference makes threshold selection a substantive decision, not a minor formatting detail. Note that the separate 36/24/14/926 arithmetic example earlier is fictional classroom practice; the real model’s counts are 18/10/32/940.

Observed test classPredicted Class 0Predicted Class 1Total
Actual Class 0940 TN10 FP950
Actual Class 132 FN18 TP50
Total972281,000
Test metricMajority-only baselineSelected weighted forest
Accuracy95.00%95.80%
Positive precision0% (zero_division=0)64.29%
Positive recall0%36.00%
Positive F10%46.15%
Balanced accuracy50.00%67.47%
Average Precision0.05000.5817
ROC-AUC0.50000.9206
from sklearn.metrics import (
    accuracy_score, precision_score, recall_score, f1_score,
    balanced_accuracy_score, average_precision_score,
    roc_auc_score, confusion_matrix
)
pred = final_model.predict(X_test)
pos_index = list(final_model.classes_).index(1)
scores = final_model.predict_proba(X_test)[:, pos_index]
print("Confusion:", confusion_matrix(y_test, pred, labels=[0, 1]))
print("Accuracy:", accuracy_score(y_test, pred))
print("Precision:", precision_score(y_test, pred, zero_division=0))
print("Recall:", recall_score(y_test, pred))
print("F1:", f1_score(y_test, pred, zero_division=0))
print("Balanced accuracy:", balanced_accuracy_score(y_test, pred))
print("Average Precision:", average_precision_score(y_test, scores))
print("ROC-AUC:", roc_auc_score(y_test, scores))

Why the threshold changes positive predictions

A classifier can return a continuous score for the positive event; applying a threshold converts the score into a yes/no decision. If the estimated probability is 0.65, threshold 0.50 produces a positive label while threshold 0.70 produces a negative label. Neither outcome changes the underlying score. Lowering a threshold often finds more positives but generates additional false alarms. Increasing it often does the reverse. The specific curve depends on the model and dataset.

Precision, recall, specificity, F1 and balanced accuracy can change when you move the decision threshold. ROC-AUC and Average Precision, calculated from the unchanged continuous scores, do not change merely because you apply another reporting threshold. The standard default of 0.50 is not a universally optimal rule, especially in imbalanced or asymmetric-cost applications.

Select thresholds with validation, never the final test labels

A responsible threshold policy starts by defining a target such as minimum recall, acceptable false-alarm volume or documented relative costs. Obtain out-of-fold training scores or a separate validation partition, compare thresholds on those scores, choose the policy and fit the final model. Apply that chosen threshold only once to the untouched test data. Selecting the most flattering threshold from test labels and then claiming an independent evaluation would make the performance estimate optimistic.

If the cost of false negatives is five illustrative units and false positives is one unit, the constructed teaching confusion matrix has total cost 14×5 + 24×1 = 94 hypothetical units. These are teaching assumptions, not actual equipment, medical or financial costs. A serious decision policy needs reliable domain estimates, stakeholder input and monitoring.

Ranking ability is different from calibrated probability

A model can order positive cases ahead of negatives fairly well while reporting probability values that do not match observed frequencies. A calibrated model predicts probabilities consistent with outcomes over suitable groups of observations—for example, cases assigned approximately 0.20 risk should be positive roughly 20% of the time across a sufficiently representative group. Calibration can be inspected with reliability diagrams and measures such as the Brier score.

SMOTE, random oversampling, undersampling and class weighting alter the effective training balance or objective. A model trained on an artificial 50:50 sample should not automatically have its raw positive probabilities interpreted as real-world risk when the application prevalence is only 5%. Check calibration on unresampled, representative validation observations, and consider explicit recalibration. Neither resampling nor weights automatically destroys calibration in every model; they create a reason to measure it.

Changing event prevalence changes what alarms mean

Suppose a hypothetical model has recall of 80% and a false-positive rate of 5%, with those conditional rates held fixed. In 1,000 cases with 5% actual positives, it would find about 40 of 50 positives and falsely flag roughly 48 of 950 negatives; precision would be about 40/(40+48) = 45%. If prevalence drops to 1%, the same rates would yield about 8 true positives and approximately 50 false alarms; precision becomes roughly 8/(8+50) = 14%.

These are rounded hypothetical counts, not outcomes from the trained forest. They illustrate why prevalence matters for operational positive predictive value. Changes in equipment, customers, sensors, label definitions, geography or time can also change the conditional error rates themselves. A synthetic benchmark cannot establish generalization or calibrated risk for any production environment.

Multiclass imbalance, categorical predictors and specialized methods

In multiclass classification, several classes may be rare, each with different importance and error structure. Use per-class confusion matrices and averages appropriate to the question; macro recall or macro F1 prevents the largest class from automatically dominating the summary. In data with arbitrary categorical codes, interpolation can be meaningless: a code of 2 lying between categories 1 and 3 is not necessarily a valid semantic category.

Imbalanced-learn provides SMOTENC for mixed numeric/categorical data and SMOTEN for categorical-only features. Other optional candidates include ADASYN, Borderline-SMOTE, SMOTE-Tomek, SMOTE-ENN and specialized balanced ensembles. They involve different neighbourhood, generation or cleaning assumptions and must be cross-validated like the simpler methods. None should be regarded as an automatic improvement.

Real dataset extension: UCI Bank Marketing

For a more realistic follow-up, use the official UCI Bank Marketing dataset. Define the target as whether a historical contact resulted in a subscription, verify frequencies and inspect its data dictionary before modelling. It contains mixed feature types, so ordinary SMOTE on naively integer-coded categories is inappropriate. Assess class prevalence, unknown categories, duplicates, sampling design and the representation of the available records.

A particularly important leakage feature is duration, the duration of the relevant phone contact. If the goal is deciding whom to contact before the call, the future duration cannot be known and should be excluded. Depending on the selected data file and research goal, chronological evaluation may also be more meaningful than a random split. Historical marketing responses can reflect selection bias; never present a model built from this dataset as applicable to every banking customer worldwide.

Fairness, data quality, privacy and responsible AI

A minority class means an uncommon target label; it does not automatically refer to a demographic minority or socially marginalized group. Nonetheless, class imbalance can interact with measurement bias, underrepresentation, labelling errors and unequal false-positive or false-negative rates across groups. Improving overall rare-event recall does not guarantee equitable performance for individuals or population subgroups.

Use only information you are authorized to process, minimize personal data, document the purpose of prediction and evaluate subgroup performance when it is lawful, appropriate and statistically meaningful. A rare-event flag should usually prompt proportionate investigation, not automatic punishment or exclusion. Particularly in healthcare, education, finance and employment, independent validation, governance and human review matter far more than a classroom metric.

A ten-task capstone: detecting rare events

Task 1: Generate the 5,000-record synthetic dataset and verify its ten numeric features. Task 2: Calculate class percentages and the 19:1 ratio. Task 3: Preserve a stratified 80/20 test set and report both class distributions. Task 4: Train and evaluate the majority-only baseline. Task 5: Train unweighted Logistic Regression with a fold-fitted scaler.

Task 6: Fit weighted Logistic Regression and a class-weighted Random Forest. Task 7: Fit SMOTE, random oversampling and random undersampling pipelines using training-only cross-validation. Task 8: Compare Average Precision, recall, precision, F1, balanced accuracy and confusion matrices. Task 9: Propose a validation-selected threshold and justify its error trade-off. Task 10: Write a short reproducibility report naming the dataset, seed, versions, final candidate, test results, limitations and responsible-use safeguards.

In your report distinguish the selected candidate’s cross-validation metric from its held-out metric; do not choose a new winner after looking at test scores. Include at least one chart and explain what its axes represent. Remember that every example here is synthetic and no claim about real equipment reliability follows.

Thirty original practice questions with worked answers

1. What is class imbalance?

The situation in which target classes have substantially different observed frequencies.

2. Identify the minority count in 4,750:250 data.

250 observations.

3. What proportion is 250 of 5,000?

250/5,000 = 5%.

4. Find the imbalance ratio for 4,750 and 250.

4,750/250 = 19:1.

5. Is every 95:5 dataset invalid?

No. Rare events may naturally have a 5% prevalence.

6. What accuracy does an all-negative classifier get with 950 negatives of 1,000?

950/1,000 = 95%.

7. What recall does that classifier have for 50 positives?

0/50 = 0%.

8. What balanced accuracy does it attain?

(100% + 0%)/2 = 50%.

9. Why is majority accuracy alone misleading?

It can hide the failure to find any minority observations.

10. What is a false negative?

An actual Class 1 event predicted as Class 0.

11. Calculate precision for TP=36 and FP=24.

36/(36+24)=60%.

12. Calculate recall for TP=36 and FN=14.

36/(36+14)=72%.

13. Calculate specificity for TN=926 and FP=24.

926/950≈97.47%.

14. Calculate F1 for TP=36, FP=24 and FN=14.

72/(72+24+14)≈65.45%.

15. Calculate accuracy for TP=36 and TN=926 among 1,000.

962/1,000=96.2%.

16. Calculate balanced accuracy for recall .72 and specificity 926/950.

(.72+926/950)/2≈84.74%.

17. What is Average Precision?

A precision–recall summary weighted by increments in recall, not generally identical to trapezoidal PR area.

18. What is the constant-score AP baseline at 5% prevalence?

0.05 in the standard binary setting.

19. Does changing only a classification threshold change ROC-AUC?

No, the continuous scores and their ordering are unchanged.

20. What does random oversampling add?

Additional copies or selections of already observed minority rows.

21. How many synthetic minority rows does balancing 3,800:200 with SMOTE add?

3,800−200=3,600.

22. How many rows are in that fully oversampled training sample?

3,800+3,800=7,600.

23. How many majority rows does balancing by undersampling remove?

3,800−200=3,600.

24. Compute a SMOTE point between (2,4) and (6,8) for λ=.25.

(2,4)+.25(4,4)=(3,5).

25. Find the majority balanced class weight in 3,800:200 training data.

4,000/(2×3,800)≈0.5263.

26. Find the minority balanced class weight.

4,000/(2×200)=10.

27. Why is SMOTE before splitting unsafe?

It can leak test information into training and distort evaluation prevalence.

28. Which Pipeline should wrap a sampler for cross-validation?

imblearn.pipeline.Pipeline.

29. Which candidate achieved highest observed training CV AP here?

Weighted Random Forest, mean AP≈0.6152.

30. Why is its 95.8% test accuracy not sufficient alone?

It detected only 18 of 50 positives, giving 36% recall.

Four-week learning roadmap

Week 1 — Foundations: learn target labels, prevalence, ratios, majority baselines and all confusion-matrix formulas. Recalculate the 95% accuracy paradox and the constructed worked example without a computer. Week 2 — Python: run the synthetic dataset generator, preserve the test set, fit unweighted and weighted Logistic Regression and investigate model scores.

Week 3 — Resampling: compare random oversampling, undersampling and SMOTE, inspect nearest-neighbour assumptions and implement leakage-safe pipelines with stratified cross-validation. Week 4 — Evidence and communication: compare Average Precision and threshold-dependent metrics, create a precision–recall chart, assess calibration conceptually and write the ten-task capstone report. Your final conclusion should be based on verified results, not on which algorithm sounds most sophisticated.

Frequently asked questions

Should I always balance a dataset 50:50?

No. Original prevalence may be correct. Test class weighting and resampling against a baseline using a relevant validation objective.

What is the difference between SMOTE and random oversampling?

Random oversampling repeats observed minority examples; SMOTE interpolates synthetic numerical feature vectors.

Can SMOTE make performance worse?

Yes. It may create implausible points, blur class boundaries or lower precision and ranking quality.

Should I apply SMOTE before splitting data?

No. First reserve a representative test set, and apply the sampler only inside training folds.

Why did weighted Random Forest win this example?

Its five-fold Average Precision was highest among the seven tested models on this particular synthetic dataset.

Does 95.8% accuracy prove that the model detects most rare events?

No. The selected model’s minority recall was only 36% on the held-out sample.

Why is positive precision undefined for a majority-only classifier?

It predicts no positive labels, making TP+FP=0. The displayed zero uses an explicit software convention.

Does a high ROC-AUC guarantee high precision?

No. When positives are rare, even a small false-positive rate can produce numerous false alarms.

Can I apply SMOTE to categorical variables?

Do not interpolate arbitrary category codes with standard SMOTE. Assess SMOTENC or SMOTEN as appropriate.

Is class weighting equivalent to making synthetic samples?

No. It changes training contributions without generating feature vectors.

Does changing a threshold alter Average Precision?

Not if only the final labels change while underlying continuous scores remain fixed.

What if my data contain repeated customers or chronological records?

Use a split that respects group membership and time; ordinary random stratification may leak information.

Can model probabilities be trusted after oversampling?

Not automatically. Check calibration using representative, unresampled validation observations.

Does minority class mean a demographic minority?

No. It refers to the less frequent target label.

Can I use this model to make real safety decisions?

No. It is a synthetic educational benchmark; real use requires domain-specific validation and safeguards.

Related Notes for SHS lessons and authoritative sources

Continue with Accuracy, Precision, Recall and F1 (Topic 63), Training Decision Trees in Python (Topic 61), AI Bias in Machine Learning (Topic 62) and Free Datasets for Student Projects (Topic 84). These lessons expand the prerequisites without repeating this tutorial.

Technical documentation: imbalanced-learn: common pitfalls and leakage; SMOTE API; sampling Pipeline; Scikit-Learn Average Precision; balanced class weights; probability calibration. Original SMOTE research: Chawla et al. (2002), SMOTE: Synthetic Minority Over-sampling Technique.

Conclusion: evaluate the rare cases, not just the headline number

The strongest lesson is that balancing the training data is not the same as solving the learning problem. Start by understanding the labels and protecting an appropriate test set. Compare against a majority baseline, use metrics that reflect the class and the consequences of errors, and place every sampler inside cross-validation. Treat class weights, random oversampling, undersampling and SMOTE as experiments to evaluate, not promises of improvement. The verified project showed a useful increase in ranking ability under a weighted forest, yet its default threshold still missed 32 of 50 rare events. Responsible data science means reporting that limitation clearly and selecting any future thresholds, calibration changes or deployments using separate evidence.