🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Synthetic Data Generation for Training and Privacy

đŸŸĸ Free Lesson

Synthetic Data Generation

Artificial examples that look real, labeled for free, and rare exactly where you need them — if you check the distribution.

Data

Prerequisites

  • !Train/test splits and distribution thinking
  • !Generative models at a conceptual level
  • !Label noise and its effect on classifiers

What You'll Learn

  • 1Match a synthesis method to the data type and the privacy requirement
  • 2Measure fidelity without rewarding mode collapse
  • 3Build a generation-and-labeling loop that produces training-ready examples
  • 4Recognize when synthetic data will not transfer to the real task

The case for generating data

Real datasets are scarce, expensive, imbalanced and legally constrained — often all four at once. Fraud is rare by design, so a classifier trained on natural class ratios sees too few positives to learn. Medical records carry privacy obligations that make collection a multi-month process. New products have no historical interactions at all.

Synthetic generation addresses each problem differently. For imbalance, it manufactures minority-class examples until the classifier sees enough of them. For privacy, it produces records that carry statistical patterns without carrying any individual's actual values. For cold start, it simulates plausible usage before any users exist. And for testing, it creates edge cases deliberately — the midnight deployment that fails, the sensor that drifts, the account that exists for exactly three minutes.

The discipline that keeps the practice honest is refusing to treat generated data as ground truth by default. Synthetic examples inherit whatever biases and blind spots the generator learned, and they add new ones of their own. Every method below comes with a check, because the failure modes of synthetic data are subtle: a dataset can look statistically correct and still teach a model the wrong decision boundary.

There is also a governance angle worth deciding early. Once synthetic rows live in the same warehouse as real ones, every downstream consumer — analytics, training, compliance reporting — needs to know which is which. Carry a provenance column from the moment of generation and treat it as immutable. Teams that skip this step find themselves later unable to answer basic questions about what data their production model was actually trained on.

Tabular synthesis methods

Tabular data responds to several techniques, and the choice is governed by the column types you have and the privacy budget you must respect. Gaussian copulas capture linear correlations cheaply and are transparent enough to audit. Tree-based synthesizers handle mixed categorical and continuous columns well. Generative adversarial networks model nonlinear dependencies that simpler methods miss, at the cost of instability and collapse risk.

python
import numpy as np
import pandas as pd

def gaussian_copula_sample(correlation, marginals, n_samples, seed=0):
    """Sample a synthetic table preserving correlation and per-column marginals."""
    rng = np.random.default_rng(seed)
    latent = rng.multivariate_normal(
        mean=np.zeros(len(marginals)), cov=correlation, size=n_samples
    )
    from scipy.stats import norm
    uniform = norm.cdf(latent)                      # map to 0-1
    frame = pd.DataFrame({
        name: marginal.ppf(np.clip(uniform[:, i], 1e-6, 1 - 1e-6))
        for i, (name, marginal) in enumerate(marginals.items())
    })
    return frame

def compare_distributions(real, synthetic, columns):
    """Report per-column drift so synthetic data cannot quietly diverge."""
    report = {}
    for col in columns:
        ks = ks_2samp(real[col].dropna(), synthetic[col].dropna())
        report[col] = {
            "ks_statistic": float(ks.statistic),
            "p_value": float(ks.pvalue),
            "mean_shift": float(synthetic[col].mean() - real[col].mean()),
        }
    return report

For most business tables, start with a copula or tree-based method and only escalate to a GAN when the drift report shows meaningful nonlinear structure you cannot capture. Simpler generators are easier to audit, and auditability is the whole point of synthetic data programs.

Text generation for training sets

Text synthesis behaves differently because labels come from content. A common pattern is to prompt a strong model with a class description and a seed context, then keep only generations that pass a classifier check. Diversity must be forced explicitly — temperature alone produces variation in wording, not in scenario.

python
import random
from openai import OpenAI

client = OpenAI()

TEMPLATES = {
    "billing_dispute": [
        "I was charged twice for {item} this month.",
        "My invoice shows {amount} but the quote said {other}.",
        "Why is there a late fee when I paid on {date}?",
    ],
    "cancellation": [
        "Please cancel my subscription at the end of the period.",
        "I want to close account {account} effective immediately.",
        "How do I stop the renewal for {item}?",
    ],
}

def generate_examples(label, n, seed_contexts):
    """Generate labeled support tickets with controlled diversity."""
    rows = []
    for _ in range(n):
        template = random.choice(TEMPLATES[label])
        context = random.choice(seed_contexts)
        prompt = (
            f"Rewrite this as a short customer message, keeping all facts, "
            f"varying tone between frustrated and neutral:\n{context}\n"
            f"Template to follow: {template}"
        )
        completion = client.chat.completions.create(
            model="gpt-4o-mini",
            temperature=0.9,
            max_tokens=80,
            messages=[{"role": "user", "content": prompt}],
        )
        rows.append({
            "text": completion.choices[0].message.content.strip(),
            "label": label,
            "source": "synthetic",
        })
    return rows

seed_billing = [
    "charged 49.99 twice for Pro plan, invoice 8821",
    "annual renewal billed 299 instead of 249",
]
examples = generate_examples("billing_dispute", 200, seed_billing)

Grounding generation in real seed contexts matters more than temperature tuning. Seed facts anchor the examples to scenarios your production traffic actually contains, while the rewrites supply the surface variation that prevents memorization of your training rows.

The fidelity-privacy tension

Fidelity and privacy pull against each other directly. A generator that reproduces the training distribution perfectly is also the one most likely to reproduce individual records. Managing that tension is the central design decision.

MethodFidelityPrivacyNotes
Row resamplingPerfectNoneNot synthetic at all
Gaussian copulaMediumMediumBreaks exact values, keeps correlations
Tree-based synthesizerHighMediumGood for mixed column types
GAN-basedHighVariableAudit for memorized rows carefully
Differential privacyLowerStrongNoise is quantifiable and defensible

Whatever method you pick, run a membership inference check before shipping: try to distinguish training rows from generated rows with a strong classifier. If the attacker classifier wins easily, your generator memorized the data and the privacy claim is hollow.

Detecting mode collapse

Mode collapse is the GAN failure where the generator produces a narrow slice of the real distribution — a few templates, a few values, repeated with cosmetic variation. Accuracy metrics often improve on collapsed data, which is exactly what makes it dangerous.

python
from collections import Counter

def diversity_report(texts):
    """Surface-level diversity metrics that catch template repetition."""
    unigrams = Counter()
    bigrams = Counter()
    for t in texts:
        words = t.lower().split()
        unigrams.update(words)
        bigrams.update(zip(words, words[1:]))

    n = len(texts)
    unique_bigrams = len(bigrams)
    return {
        "n": n,
        "distinct_unigram_ratio": len(unigrams) / max(sum(unigrams.values()), 1),
        "distinct_bigram_ratio": unique_bigrams / max(sum(bigrams.values()), 1),
        "top_bigram_share": (bigrams.most_common(1)[0][1] / n) if bigrams else 0.0,
        "unique_examples_ratio": len(set(texts)) / n,
    }

def is_collapsed(report, bigram_ratio_floor=0.35, top_share_ceiling=0.15):
    """Flag synthetic corpora that repeat themselves."""
    reasons = []
    if report["distinct_bigram_ratio"] < bigram_ratio_floor:
        reasons.append("low_bigram_diversity")
    if report["top_bigram_share"] > top_share_ceiling:
        reasons.append("dominant_repeated_phrase")
    if report["unique_examples_ratio"] < 0.9:
        reasons.append("near_duplicate_rows")
    return reasons

Run these checks per class, not just globally. A corpus can look diverse overall while one minority class collapses entirely — the exact class you synthesized data to help with.

Collapse usually announces itself in the top-frequency statistics rather than the averages. Watch the share of the single most common bigram and the ratio of unique rows to total rows: a generator repeating one template with swapped entity names will look fine on mean length and vocabulary size while producing effectively three distinct examples.

Building the rare-class loop

Imbalance is the most common reason teams reach for synthesis, and the naive version of the fix teaches the wrong lesson. Oversampling the minority class by duplicating rows gives the classifier more gradient steps on the same examples, which overfits them rather than generalizing the boundary. Generation works when it adds variation the real data lacks — different phrasings, different contexts, different combinations of features — while preserving the class-defining signal.

python
def balanced_training_set(real_rows, synth_rows, target_ratio=0.4):
    """Merge real and synthetic minority examples without drowning reality."""
    majority = real_rows[real_rows["label"] == 0]
    minority_real = real_rows[real_rows["label"] == 1]
    n_minority = int(len(majority) * target_ratio)
    n_from_synth = max(n_minority - len(minority_real), 0)

    sampled_synth = synth_rows.sample(n=min(n_from_synth, len(synth_rows)), random_state=0)
    combined = pd.concat([majority, minority_real, sampled_synth], ignore_index=True)
    return combined.sample(frac=1.0, random_state=0)

Cap synthetic contribution rather than letting it dominate. Once synthetic rows outnumber real ones for a class, the classifier is fitting the generator's habits more than the world's — and the tell is a validation score computed on real data that falls while training accuracy climbs.

Will it transfer to the real task?

The only test that matters is downstream. Train a classifier on synthetic data, evaluate it on a held-out slice of real data, and compare against a baseline trained on whatever real data you had. If the gap is large, more synthetic volume will not close it; better grounding will.

Run that comparison more than once with different seeds. A single split can easily move an F1 score by a point or two, which is enough to reverse the conclusion of a marginal experiment. Report the mean and spread across three or five runs, and treat any improvement inside the spread as noise rather than a result worth shipping.

python
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import f1_score

def transfer_score(real_train, real_test, synthetic_train, feature_fn):
    """Compare a real-trained baseline against a synthetically augmented model."""
    base = LogisticRegression(max_iter=1000)
    base.fit(feature_fn(real_train["text"]), real_train["label"])
    baseline = f1_score(real_test["label"], base.predict(feature_fn(real_test["text"])), average="macro")

    augmented = LogisticRegression(max_iter=1000)
    combined = pd.concat([real_train, synthetic_train], ignore_index=True)
    augmented.fit(feature_fn(combined["text"]), combined["label"])
    with_synthetic = f1_score(real_test["label"], augmented.predict(feature_fn(real_test["text"])), average="macro")

    return {"baseline_f1": baseline, "augmented_f1": with_synthetic, "delta": with_synthetic - baseline}

A positive delta on real held-out data is the only result worth reporting. If synthetic data helps offline but not online, the features it teaches are artifacts of the generator — a signal to change the generation method rather than to ship anyway.

Common Mistakes

Reporting synthetic data volume as a success metric

Fix: Report downstream performance on held-out real data — volume without transfer is storage cost.

Generating with no seed contexts and hoping variety appears

Fix: Ground generation in real seed facts and vary tone and phrasing around them.

Skipping membership inference checks because the data looks realistic

Fix: Run an attack classifier against the generator output before making any privacy claim.

Evaluating diversity globally instead of per class

Fix: Check collapse metrics per label — minority classes collapse first and most often.

Best Practices

  • Start with the simplest synthesizer you can audit and escalate only when drift reports demand it
  • Keep a held-out real test set that synthetic data never touches
  • Attach provenance to every row so downstream users know what is real
  • Re-run transfer evaluation whenever the generator or the prompt changes
  • Document the privacy method precisely enough for a compliance reviewer to challenge it

Key Takeaways

  • Synthetic data solves scarcity, imbalance and privacy — each needs a different method and check
  • Fidelity and privacy trade directly; measure both, never assume either
  • Mode collapse hides behind improving accuracy metrics, so check diversity per class
  • Only downstream transfer on held-out real data justifies shipping synthetic training rows
  • Provenance and membership inference testing keep privacy claims honest
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Generative AI Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement