GyaanStack. Blog

Articles / machine-learningsynthetic-datapython

Synthetic data for imbalanced datasets: SMOTE, a copula, class weights and a threshold, measured

SMOTE, a Gaussian copula, class_weight and plain threshold tuning on a real 2.3% positive dataset, with PR-AUC, recall at 80% precision and a fidelity check.

By Raghunath · · 17 min read

A fraud or disease model trained on data with 2% positives can score 98% accuracy by never predicting a positive. Everyone knows that part. The usual fix in tutorials is to oversample the rare class with SMOTE or a generative model until the classes are 50/50, retrain, and show a better F1. The step that gets skipped is checking whether the better F1 came from the synthetic rows or from something cheaper, such as moving the decision threshold.

This post runs that check on one real imbalanced table. It compares four setups with identical models: no resampling, class_weight="balanced", SMOTE from imbalanced-learn, and a Gaussian copula that generates new minority rows. Resampling happens only inside training folds. It reports PR-AUC, recall at a fixed 80% precision, and F1 at two thresholds, then tests how close the synthetic rows are to real ones. It also reproduces the most common mistake (oversampling before the split) so you can see the size of the lie it tells.

The results, in short: on a gradient-boosted model, none of the resampling methods moved test PR-AUC by more than the noise. They mostly moved the predicted probabilities, which changed F1 at a 0.5 cutoff by up to 0.27. Tuning the threshold closed almost all of that gap. Oversampling before cross-validation reported a PR-AUC of 0.989 for a model whose honest score was 0.701.

If you are working with text and want an LLM to write extra training examples, that is a different pipeline with different failure modes, covered in data augmentation with LLMs. This post is about numeric tabular data.

What each method does to the training set#

All four setups train the same HistGradientBoostingClassifier. They differ only in what the model sees during training.

  • No resampling. The model sees the real class ratio. It still learns to rank positives above negatives; its probabilities are just low, so a 0.5 cutoff flags few cases.
  • Class weights. No new rows. Each positive counts more in the loss. With class_weight="balanced", each class gets weight n_samples / (2 * n_in_class): about 21.5 for a positive and 0.51 for a negative on this training split, so one positive counts as much as 42 negatives. HistGradientBoostingClassifier has accepted class_weight since scikit-learn 1.2 (docs).
  • SMOTE. For each minority row, pick one of its k nearest minority neighbours (k=5 by default) and create a new point at a random spot on the line between them (Chawla et al., 2002; imbalanced-learn docs). The new rows live inside the convex hull of the real minority rows, so SMOTE cannot invent a region the real data never reached.
  • Gaussian copula. Fit each feature's marginal distribution from the real minority rows, fit the correlation between features in a transformed normal space, then sample new rows from that joint model. It is the simplest member of the generative family that includes CTGAN and TVAE. The SDV library ships a production version as GaussianCopulaSynthesizer (SDV docs). The one below is 20 lines of NumPy and SciPy so you can see every step.

Variants such as ADASYN, Borderline-SMOTE and SMOTE-Tomek move where SMOTE places its points. They do not change the conclusions below, so they are left out to keep the table readable. For tables with categorical columns, plain SMOTE averages category codes into values that do not exist; use SMOTENC instead.

The dataset and the split#

The data is the mammography dataset: 11,183 rows, 6 numeric features, 260 positives (2.32%). It comes from the benchmark collection that imbalanced-learn downloads with fetch_datasets, and it is also on OpenML as dataset 310. It is small, but it is real, and its minority class is a genuine medical label rather than a make_classification blob.

The run used scikit-learn 1.9.1, imbalanced-learn 0.14.2, SciPy 1.18.1, Python 3.15.

import numpy as np
import pandas as pd
from collections import Counter
from scipy import stats
from imblearn.datasets import fetch_datasets
from imblearn.over_sampling import SMOTE
from imblearn.pipeline import Pipeline
from imblearn import FunctionSampler
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.model_selection import (StratifiedKFold, cross_val_score,
                                     train_test_split)
from sklearn.metrics import (average_precision_score, f1_score,
                             precision_recall_curve, roc_auc_score)

SEED = 0

ds = fetch_datasets(filter_data=("mammography",))["mammography"]
X, y = ds.data, (ds.target == 1).astype(int)
print("rows:", X.shape, "classes:", Counter(y), f"positive rate: {y.mean():.2%}")

X_tr, X_te, y_tr, y_te = train_test_split(
    X, y, test_size=0.25, stratify=y, random_state=SEED)
print("train:", Counter(y_tr), "test:", Counter(y_te))
rows: (11183, 6) classes: Counter({np.int64(0): 10923, np.int64(1): 260}) positive rate: 2.32%
train: Counter({np.int64(0): 8192, np.int64(1): 195}) test: Counter({np.int64(0): 2731, np.int64(1): 65})

The test set is split off first and never resampled. It keeps the real 2.3% rate because production traffic will have the real rate. Note the size: 65 test positives. One extra caught positive moves recall by 1.5 points, which matters when reading the table later.

Where resampling sits in the pipeline#

 full table (2.3% positive)
        |
        +--> test split (25%) ---------------------------> scored once, at the end
        |
        v
 train split
        |
        +--> 5 stratified folds
               for each fold:
                 fit part ---> [resampler] ---> model.fit
                 val part  -----------------------> model.predict_proba
                                                       |
                                    out-of-fold scores -+--> CV PR-AUC
                                                       +--> pick threshold

The resampler only ever sees the "fit part" of each fold. The Pipeline from imblearn.pipeline (not the scikit-learn one) enforces this: samplers in it run during fit and are skipped during predict. The imbalanced-learn docs have a page on exactly this leak (common pitfalls).

The generative option: a Gaussian copula#

class GaussianCopula:
    """Fit marginals as empirical quantiles, dependence as a Gaussian copula."""

    def fit(self, Xm):
        self.sorted_ = np.sort(Xm, axis=0)
        n = len(Xm)
        ranks = stats.rankdata(Xm, axis=0) / (n + 1)       # uniform (0,1)
        z = stats.norm.ppf(ranks)                          # normal scores
        self.corr_ = np.corrcoef(z, rowvar=False)
        return self

    def sample(self, n, rng):
        d = self.sorted_.shape[1]
        z = rng.multivariate_normal(np.zeros(d), self.corr_, size=n)
        u = stats.norm.cdf(z)
        # map each uniform back through that column's empirical quantiles
        cols = [np.quantile(self.sorted_[:, j], u[:, j]) for j in range(d)]
        return np.column_stack(cols)


def copula_oversample(X, y, ratio=1.0, seed=SEED):
    rng = np.random.default_rng(seed)
    Xm = X[y == 1]
    need = int(ratio * (y == 0).sum()) - len(Xm)
    syn = GaussianCopula().fit(Xm).sample(need, rng)
    return np.vstack([X, syn]), np.concatenate([y, np.ones(need, dtype=int)])

Three steps. Turn each column into ranks, then into normal scores, and measure the correlation of those scores. To sample, draw correlated normals, push them back to uniforms, and read each uniform off that column's empirical quantile curve. Each synthetic column then has the same marginal shape as the real minority column, and the pairwise rank correlations roughly match. What it cannot capture is anything non-linear between features, such as two separate clusters of positives. That is where CTGAN-style models earn their training cost, and where they need thousands of minority rows rather than 195 to learn it.

FunctionSampler wraps the function so it can sit inside an imblearn pipeline like any other sampler (docs).

The four setups and the metrics#

def model(**kw):
    return HistGradientBoostingClassifier(random_state=SEED, **kw)


setups = {
    "no resampling": Pipeline([("clf", model())]),
    "class_weight": Pipeline([("clf", model(class_weight="balanced"))]),
    "SMOTE": Pipeline([("smote", SMOTE(random_state=SEED)), ("clf", model())]),
    "Gaussian copula": Pipeline([("cop", FunctionSampler(func=copula_oversample,
                                                         validate=False)),
                                 ("clf", model())]),
}


def recall_at_precision(y_true, score, target=0.80):
    p, r, _ = precision_recall_curve(y_true, score)
    ok = p >= target
    return r[ok].max() if ok.any() else 0.0


def best_threshold(y_true, score):
    p, r, t = precision_recall_curve(y_true, score)
    f1 = 2 * p * r / np.clip(p + r, 1e-12, None)
    return t[np.argmax(f1[:-1])]

Four numbers per setup, each answering a different question:

  • PR-AUC (average precision): how well the model ranks positives above negatives, across all thresholds. On rare-positive data it is more informative than ROC-AUC, because ROC-AUC rewards correctly ranking thousands of easy negatives (Saito and Rehmsmeier, 2015). A random model scores the positive rate, 0.023 here.
  • Recall at 80% precision: if the business accepts one false alarm per four true hits, how many real positives do you catch? This is closer to how a fraud or screening team sets an operating point than F1 is.
  • F1 at 0.5: what you get if you call predict() and never think about the threshold.
  • F1 at a tuned threshold: the threshold that maximised F1 on the out-of-fold training predictions, then applied unchanged to the test set. The test set plays no part in choosing it.
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=SEED)
rows, test_scores = [], {}
for name, pipe in setups.items():
    # out-of-fold scores on train: resampling runs only on each training fold
    oof = np.zeros(len(y_tr))
    cv_ap = []
    for fit_idx, val_idx in cv.split(X_tr, y_tr):
        pipe.fit(X_tr[fit_idx], y_tr[fit_idx])
        oof[val_idx] = pipe.predict_proba(X_tr[val_idx])[:, 1]
        cv_ap.append(average_precision_score(y_tr[val_idx], oof[val_idx]))
    cv_ap = np.array(cv_ap)
    # threshold picked on out-of-fold train predictions, never on test
    thr = best_threshold(y_tr, oof)
    pipe.fit(X_tr, y_tr)
    s = pipe.predict_proba(X_te)[:, 1]
    test_scores[name] = s
    rows.append({
        "setup": name,
        "CV PR-AUC": f"{cv_ap.mean():.3f}±{cv_ap.std():.3f}",
        "test PR-AUC": average_precision_score(y_te, s),
        "R@P80": recall_at_precision(y_te, s),
        "F1@0.5": f1_score(y_te, s >= 0.5),
        "tuned thr": thr,
        "F1@tuned": f1_score(y_te, s >= thr),
    })
print(pd.DataFrame(rows).round(3).to_string(index=False))
          setup   CV PR-AUC  test PR-AUC  R@P80  F1@0.5  tuned thr  F1@tuned
  no resampling 0.709±0.043        0.769  0.692   0.750      0.185     0.720
   class_weight 0.690±0.059        0.743  0.677   0.682      0.701     0.733
          SMOTE 0.701±0.040        0.775  0.646   0.642      0.803     0.754
Gaussian copula 0.706±0.059        0.771  0.646   0.480      0.948     0.700

With imbalanced-learn 0.14.2 on scikit-learn 1.9.1 the run also prints a UserWarning about sklearn.utils.parallel.delayed; it does not change the numbers.

Reading the table#

Ranking quality barely moved. Test PR-AUC sits between 0.743 and 0.775 for all four setups, and cross-validated PR-AUC between 0.690 and 0.709 with a fold-to-fold spread of 0.04 to 0.06. To check whether the 0.006 gain for SMOTE means anything, a paired bootstrap resamples the 2,796 test rows 1,000 times and recomputes the difference against no resampling:

boot = np.random.default_rng(SEED)
base = test_scores["no resampling"]
diffs = {k: [] for k in test_scores if k != "no resampling"}
for _ in range(1000):
    i = boot.integers(0, len(y_te), len(y_te))
    if y_te[i].sum() == 0:
        continue
    ap0 = average_precision_score(y_te[i], base[i])
    for k in diffs:
        diffs[k].append(average_precision_score(y_te[i], test_scores[k][i]) - ap0)
for k, d in diffs.items():
    lo, hi = np.percentile(d, [2.5, 97.5])
    print(f"  {k:16s} {np.mean(d):+.3f}  [{lo:+.3f}, {hi:+.3f}]")
test PR-AUC minus 'no resampling', 95% bootstrap interval
  class_weight     -0.027  [-0.064, +0.010]
  SMOTE            +0.005  [-0.034, +0.044]
  Gaussian copula  +0.001  [-0.050, +0.054]

Every interval contains zero. On this data, synthetic rows did not teach the model to rank positives any better than the 195 real ones did. That matches a larger study: across many tabular datasets, balancing helped weak learners but did not improve strong classifiers such as gradient-boosted trees (Elor and Averbuch-Elor, 2022).

Recall at 80% precision went slightly down with resampling: 45 of 65 positives caught with no resampling, 42 with SMOTE or the copula. Three cases is within noise, but it is the opposite of the "SMOTE boosts recall" story.

F1 at 0.5 is where the methods look different, from 0.750 down to 0.480. That spread is mostly about probabilities. A model trained on a 50/50 set learns that half of everything is positive, so its scores shift upward and a 0.5 cutoff now flags many negatives. The tuned thresholds show it directly: 0.185 for the model that saw the real ratio, 0.803 for SMOTE, 0.948 for the copula. The resampled models were not better or worse rankers; they were miscalibrated in different directions.

After tuning the threshold, F1 lands between 0.700 and 0.754 for all four setups. The no-resampling model's F1 dropped slightly with tuning (0.750 to 0.720), because a threshold picked on 195 out-of-fold positives does not transfer perfectly to 65 test positives. That is the honest cost of tuning on small data, and still better than never tuning.

The classic mistake: oversample, then split#

Here SMOTE runs on the whole training split first, and cross-validation runs on the balanced result:

X_bad, y_bad = SMOTE(random_state=SEED).fit_resample(X_tr, y_tr)
leaky = cross_val_score(model(), X_bad, y_bad, cv=cv, scoring="average_precision")
print(f"SMOTE before CV split : CV PR-AUC {leaky.mean():.3f}")
print(f"SMOTE inside each fold: CV PR-AUC {rows[2]['CV PR-AUC']}")
SMOTE before CV split : CV PR-AUC 0.989
SMOTE inside each fold: CV PR-AUC 0.701±0.040

0.989 against 0.701, for the same model on the same data. Two things inflate the leaky number. First, a synthetic point is an interpolation between two real points, so a validation fold contains synthetic rows whose parents sit in the training fold. The model scores near-copies of what it trained on. Second, the validation folds are now 50% positive instead of 2.3%, and PR-AUC rises with the positive rate whatever the model does. Both effects are what you would report to your team if you did this, and neither survives contact with production. The same rule applies to any preprocessing that learns from the data; the data leakage post measures several other versions of it.

Fidelity: do the synthetic rows look real?#

A synthetic row can help training and still be unrealistic, or look realistic and add nothing. The check below compares 2,000 synthetic minority rows from each generator (fitted on the 195 training positives) against the 65 test-set positives the generators never saw. As a baseline, the real training positives get the same comparison: that row shows how different two real samples of this class are by chance.

real_fit = X_tr[y_tr == 1]
real_hold = X_te[y_te == 1]
n_syn = 2000
rng = np.random.default_rng(SEED)
Xs_smote, ys_smote = SMOTE(random_state=SEED,
                           sampling_strategy={1: len(real_fit) + n_syn}
                           ).fit_resample(X_tr, y_tr)
syn = {
    "SMOTE": Xs_smote[len(X_tr):],
    "Gaussian copula": GaussianCopula().fit(real_fit).sample(n_syn, rng),
}


def fidelity(fake, real):
    ks = [stats.ks_2samp(fake[:, j], real[:, j]).statistic
          for j in range(real.shape[1])]
    corr_gap = np.abs(np.corrcoef(fake, rowvar=False)
                      - np.corrcoef(real, rowvar=False)).max()
    # discriminator: can a model tell synthetic rows from real ones?
    Xd = np.vstack([fake[:len(real)], real])
    yd = np.r_[np.zeros(len(real)), np.ones(len(real))]
    auc = cross_val_score(model(), Xd, yd, cv=StratifiedKFold(5, shuffle=True,
                          random_state=SEED), scoring="roc_auc").mean()
    return max(ks), np.mean(ks), corr_gap, auc


for name, fake in [("real (train)", real_fit), *syn.items()]:
    mx, mn, cg, auc = fidelity(fake, real_hold)
    print(f"{name:16s} {mx:.3f}  {mn:.3f}   {cg:.3f}       {auc:.3f}")

lo, hi = real_fit.min(0), real_fit.max(0)
for name, fake in syn.items():
    print(f"{name}: rows outside real min/max on any feature:",
          f"{np.mean(((fake < lo) | (fake > hi)).any(1)):.1%}")
fidelity vs 65 held-out real minority rows
source           maxKS  meanKS  max|dcorr|  disc AUC
real (train)     0.159  0.114   0.506       0.624
SMOTE            0.189  0.114   0.482       0.630
Gaussian copula  0.167  0.118   0.381       0.659
SMOTE: rows outside real min/max on any feature: 0.0%
Gaussian copula: rows outside real min/max on any feature: 0.0%

The columns:

  • maxKS / meanKS: the two-sample Kolmogorov-Smirnov statistic per feature, the largest gap between two cumulative distributions. 0 means identical marginals.
  • max|dcorr|: the largest difference in any pairwise correlation.
  • disc AUC: train a classifier to tell synthetic rows from real ones. 0.5 means it cannot. This is the most useful single test, because it catches combinations of features that no per-column check sees.

Both generators sit close to the real-versus-real baseline on every column. The discriminator AUC of 0.624 for two real samples shows how noisy the check is with only 65 held-out positives; the synthetic rows at 0.630 and 0.659 are not clearly worse. Neither generator produced rows outside the observed range. SMOTE cannot by construction, and the copula cannot because it maps back through empirical quantiles.

That result explains the training table. The synthetic rows are faithful copies of the minority distribution the model could already see, so they carry no new information. They shift the class prior, which a threshold also does, at no cost. Fidelity is necessary for synthetic data to help, and it is not enough.

When threshold tuning beats all of it#

On this experiment, the cheapest option tied or beat every resampler: train on the real data, then choose the threshold from out-of-fold predictions. scikit-learn has this built in as TunedThresholdClassifierCV (added in 1.5), which cross-validates the cutoff for a metric you choose; the user guide page explains the trade-offs. Threshold tuning wins when:

  • The model is a strong learner on tabular data (gradient-boosted trees, a well-regularised linear model). These rank well at the real class ratio.
  • You need calibrated probabilities downstream, for example to rank cases for review or to compute expected loss. Resampling distorts them; you would need to recalibrate afterwards.
  • The operating point is set by the business ("at most 20% false alarms"). That is a threshold decision, and recall at fixed precision measures it directly.

Resampling or class weights are worth testing when:

  • The learner is weak or has no threshold you can tune easily, such as k-nearest neighbours with a majority vote.
  • The minority class is tiny in absolute terms (a few dozen rows) and the model will not split on it at all without help. Try class weights before synthetic rows; they do the same job with no new data to validate.
  • You have enough minority rows (thousands) and evidence of structure a simple model misses, which is the case for a CTGAN-style generator. Run the discriminator test before trusting it.

Failure modes to check for#

  • Resampling outside the pipeline. Any fit_resample call before cross_val_score or before the train/test split. Search the codebase for it.
  • Reporting F1 at 0.5 for resampled models. The comparison then measures calibration, not skill. Report PR-AUC plus a metric at an operating point you chose.
  • Choosing the threshold on the test set. It inflates every number in the table. Use out-of-fold predictions on training data.
  • SMOTE on categorical or integer columns. It produces 2.4 children or a zip code that is the average of two zip codes. Use SMOTENC, or a generator that models categories.
  • Synthetic rows in the test set. The test set should look like production. If production has 2% positives, so does the test set.
  • One split, one seed. With 65 positives, differences of 0.02 to 0.03 in PR-AUC are noise. Bootstrap the test set or repeat the split before you claim a winner.

Checklist#

  1. Split off a test set at the real class ratio before anything else.
  2. Put every sampler inside an imblearn.pipeline.Pipeline, so it runs on training folds only.
  3. Baseline first: no resampling, then class_weight, with a tuned threshold for each.
  4. Add SMOTE or a generator only if it beats that baseline on PR-AUC or recall at your target precision, by more than a bootstrap interval.
  5. For any generator, run the discriminator test against held-out real minority rows, and compare to a real-versus-real baseline.
  6. Choose the final threshold on out-of-fold predictions, and recalibrate if anything downstream uses the probabilities.

Sources#

Found this useful? You can buy me a coffee or support with any amount. It pays for hosting and keeps new articles coming.