AI Wiki中文/EN

Synthetic data: preserve relationships, test on untouched target data

合成数据生成

Separate distribution matching, conditional sampling and downstream usefulness.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

More rows can contain less of the relationship you need

Suppose a table’s label depends on the relationship between two binary inputs. A generator might reproduce every column’s histogram while destroying that relationship. Thousands of additional rows would then make the wrong training distribution more precisely represented.

Synthetic data generation constructs examples for a purpose: model training, testing, simulation or controlled analysis. CTGAN addresses mixed-type tables and category imbalance. Self-Instruct uses a language model, human seed tasks and filtering to construct instruction data. They demonstrate different workflows; neither makes all generated records correct or private. Begin with data splits and generative models.

Fixed synthetic samples separate classifier utility, distribution fidelity and misleading exact-row matches.
Fixed synthetic samples separate classifier utility, distribution fidelity and misleading exact-row matches.

Keep the joint distribution and the condition prior

For a finite table state z=(a,b,y), the unsmoothed count estimate is:

p^(z)=nzN,N=∑znz.\widehat p(z)=\frac{n_z}{N},\qquad N=\sum_z n_z.

This maximum-likelihood estimate models dependence through complete rows. It cannot assign positive probability to an unseen row. Estimating each column independently instead gives:

qind(a,b,y)=p^(a)p^(b)p^(y).q_{\mathrm{ind}}(a,b,y)=\widehat p(a)\widehat p(b)\widehat p(y).

The column marginals match exactly, but conditional label information can disappear. A conditional generator exposes another distinction: the condition distribution used during training need not be the distribution wanted at generation time. With a chosen target prior π:

qπ(a,b,y)=π(a)p^(b,y∣a).q_\pi(a,b,y)=\pi(a)\widehat p(b,y\mid a).

The selected CTGAN method trains conditional models while changing how discrete conditions are sampled. Its intended target mixture uses the target category frequencies. The fixed sampler computes a training condition distribution from log(count+1), which for one binary condition is:

πlog⁡(a)=log⁡(na+1)∑a′log⁡(na′+1).\pi_{\log}(a)=\frac{\log(n_a+1)}{\sum_{a'}\log(n_{a'}+1)}.

This increases minority exposure relative to raw frequency without generally making the categories uniform. Our program keeps this prior separate from the original prior. The inspected helper named sample_original_condvec reuses a stored probability table, so its name alone is not evidence that the full library restores raw frequencies; that complete call path was not audited.

Evaluate downstream utility on untouched target data. For a fixed classifier h, target accuracy is:

AP(h)=∑a,b,yP(a,b,y)1[h(a,b)=y].A_P(h)=\sum_{a,b,y}P(a,b,y)\mathbf1[h(a,b)=y].

Good utility for one h need not mean the generator matches the entire distribution. For any fixed bounded indicator like this accuracy, total variation gives:

∣AP(h)−AQ(h)∣≤TV⁡(P,Q)=12∑z∣P(z)−Q(z)∣.|A_P(h)-A_Q(h)|\leq\operatorname{TV}(P,Q)=\tfrac12\sum_z|P(z)-Q(z)|.

To see the bound, collect states on which h is correct; the probability difference of any event is at most TV. It is a bound for a fixed classifier, not a guarantee that training on Q discovers the best target classifier.

Fit synthetic rows, then test a classifier elsewhere

Save as synthetic_data_generation.py; use Python 3.12 and NumPy 1.26.4. All data are artificial. A constructed 100-row training table has counts [36,4,4,36,1,9,9,1] in lexicographic (a,b,y) order. Those normalized counts also define the stipulated population: a=0 has probability .8, b is balanced, and y is a XOR b with independent .1 label-flip probability.

The program fits four generators: joint counts, independent columns, balanced conditions and log-frequency conditions. Each supplies 4,096 sampled training rows to a four-cell majority classifier. A separate seed draws 10,000 untouched target test rows. No target labels are used to select the generator or classifier. We additionally compute exact population accuracy because this artificial population is known.

"""Original synthetic table: dependencies, sampling priors and held-out utility."""
import itertools
import json
import numpy as np

STATES = np.array(list(itertools.product([0, 1], repeat=3)))


def table(x):
    x = np.asarray(x)
    if x.ndim != 2 or x.shape[1] != 3 or not 1 <= len(x) <= 100000 or x.dtype.kind not in 'iu' or not np.isin(x, [0, 1]).all():
        raise ValueError('Expected nonempty binary integer rows (a,b,y)')
    return x


def prob(p):
    p = np.asarray(p, dtype=float)
    if p.shape != (8,) or not np.isfinite(p).all() or np.any(p < 0) or not np.isclose(p.sum(), 1, atol=1e-12, rtol=0):
        raise ValueError('Expected normalized eight-state distribution')
    return p


def fit(x):
    x = table(x); return np.bincount(x @ [4, 2, 1], minlength=8)/len(x)


def independent(p):
    p = prob(p); marginal = p @ STATES
    return np.prod(np.where(STATES, marginal, 1-marginal), axis=1)


def change_prior(p, prior):
    p = prob(p).reshape(2, 4); prior = np.asarray(prior, dtype=float)
    if prior.shape != (2,) or not np.isfinite(prior).all() or np.any(prior < 0) or not np.isclose(prior.sum(), 1) or np.any(p.sum(axis=1) == 0):
        raise ValueError('Both conditions must be represented; specify a valid prior')
    return (p/p.sum(axis=1, keepdims=True)*prior[:, None]).ravel()


def sample(p, count, seed):
    p = prob(p)
    if type(count) is not int or not 1 <= count <= 100000: raise ValueError('Invalid count')
    return STATES[np.random.default_rng(seed).choice(8, size=count, p=p)].copy()


def classifier(p):
    return prob(p).reshape(4, 2).argmax(axis=1)


def accuracy(pred, test):
    pred = np.asarray(pred); test = table(test)
    if pred.shape != (4,) or not np.isin(pred, [0, 1]).all(): raise ValueError('Invalid classifier')
    return float(np.mean(pred[test[:, :2] @ [2, 1]] == test[:, 2]))


def expected_accuracy(pred, truth):
    pred = np.asarray(pred); truth = prob(truth)
    if pred.shape != (4,) or not np.isin(pred, [0, 1]).all(): raise ValueError('Invalid classifier')
    return float(truth[pred[STATES[:, :2] @ [2, 1]] == STATES[:, 2]].sum())


def demo():
    counts = np.array([36, 4, 4, 36, 1, 9, 9, 1]); training = np.repeat(STATES, counts, axis=0)
    truth = counts/counts.sum(); learned = fit(training); test = sample(truth, 10000, 29)
    log_prior = np.log1p([80, 20]); log_prior /= log_prior.sum()
    models = dict(joint=learned, independent=independent(learned),
                  balanced=change_prior(learned, [.5, .5]), log_prior=change_prior(learned, log_prior))
    results = {}
    for i, (name, p) in enumerate(models.items()):
        synthetic = sample(p, 4096, 40+i); pred = classifier(fit(synthetic))
        results[name] = dict(distribution=p.tolist(), marginal=(p @ STATES).tolist(),
                             total_variation=float(abs(p-truth).sum()/2), classifier=pred.tolist(),
                             population_accuracy=expected_accuracy(pred, truth), heldout_accuracy=accuracy(pred, test),
                             exact_training_row_fraction=float(np.mean([np.any(np.all(training == row, axis=1)) for row in synthetic])))
    return dict(training_counts=counts.tolist(), training_rows=len(training), synthetic_rows=4096, test_rows=len(test),
                models=results, independent_population_classifier=classifier(models['independent']).tolist(),
                independent_population_accuracy=expected_accuracy(classifier(models['independent']), truth),
                majority_accuracy=accuracy(np.zeros(4, dtype=int), test), log_condition_prior=log_prior.tolist(),
                scope='Count-fitted artificial binary table; no CTGAN or language-model training, real-person data or privacy guarantee.')


if __name__ == '__main__': print(json.dumps(demo(), indent=2))

Joint, balanced and log-prior samples recover the XOR classifier: population accuracy .9 and held-out accuracy .8993. The independent population has no label signal and its tie-to-zero classifier scores .5. However, the specific finite independent sample produces [0,1,0,1], scoring .74 on the target population and .7422 on the holdout. Keep that result: sampling noise happened to align with the majority a=0 subgroup; it did not restore the missing XOR relation. Repeating seeds would expose this instability.

Balancing changes TV by .3 even though the fitted classifier remains useful. Every generated row also matches some training row, including the correctly sampled joint model: the training table contains all eight possible states. Exact-match rate alone therefore cannot diagnose memorization on this finite support.

Counting costs O(N) for these fixed three columns; storage is eight probabilities. For k binary columns the full table grows as 2^k. Sampling needs the finite categorical table, and fitting the downstream classifier costs O(M) for M generated rows. This is not a scalable mixed-type CTGAN implementation.

Filtering is not a new source of ground truth

Self-Instruct generates instructions and instances, filters invalid or similar outputs and then finetunes. Human-written seeds remain part of the pipeline. Its paper’s quality inspection still finds errors. The fixed filtering code uses ROUGE-L similarity; a lexical overlap threshold cannot establish that an answer is true.

For a real application, start with a non-generative baseline, reserve real target groups or time periods, inspect subgroup errors and compare real-only versus augmented training under a fixed budget. Preserve provenance and keep evaluation examples out of generation prompts and model selection. Privacy requires a separate threat model and assessment; generating a row does not make it anonymous.

Audit what the extra rows preserve

  1. Calculate. What distribution results from independent columns in the example? Answer: [.2,.2,.2,.2,.05,.05,.05,.05]. It matches a’s .8/.2 prior and balanced b/y, but removes their XOR relationship.
  2. Diagnose. Why does balanced condition sampling change the joint distribution? Answer: It replaces the .8/.2 mixture weights with .5/.5, even if each conditional distribution is exact. Restoring .8/.2 restores the original mixture.
  3. Interpret. Why is the independent sample’s .74 population accuracy not proof of a faithful generator? Answer: Its finite-sample majority decisions happen to fit the common subgroup. Exact independent labels contain no feature information, and the minority subgroup relationship remains wrong.
  4. Transfer. Is a 100% training-row match rate sufficient evidence of memorization? Answer: No. Here all eight possible rows occur in training, so a correct population sampler necessarily matches them. Novelty and privacy need a task-appropriate audit.

State the purpose before selecting the generator

CTGAN focuses on tabular representation and conditional training; Self-Instruct focuses on instruction bootstrapping. Our finite table makes mixture and utility questions independently checkable without reproducing either model. Continue with generative memorization for an explicit audit on artificial candidates.

Make a prediction, then check

Must the training condition prior be used for final sampling?

Choose one answer

Learning objectives

  • Fit and sample a finite joint distribution.
  • Restore the target condition prior.
  • Evaluate utility on an untouched holdout.

Prerequisites & connections

Explore related knowledge →

References

  1. Modeling Tabular Data using Conditional GAN (v2)
    Lei Xu; Maria Skoularidou; Alfredo Cuesta-Infante; Kalyan Veeramachaneni · 2019
  2. Self-Instruct: Aligning Language Models with Self-Generated Instructions (ACL2023)
    Yizhong Wang; Yeganeh Kordi; Swaroop Mishra; Alisa Liu; Noah A. Smith; Daniel Khashabi; Hannaneh Hajishirzi · 2023
  3. sdv-dev/CTGAN: ctgan/data_sampler.py @21175b9
    sdv-dev/CTGAN contributors
  4. yizhongw/self-instruct: self_instruct/bootstrap_instructions.py @0b26cca
    yizhongw/self-instruct contributors

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-20 · Single AI author checked CTGAN v2 sections4.2-4.3, Self-Instruct selected sections2.1-2.3/opening3.3 and fixed sampler/filter code. Six paired equations and four explained exercises; original100-row binary joint model, conditional prior changes,4096-row generated training sets and independent10000-row target tests. Actual independent-sample accuracy0.74 retained versus0.5 population rule; no CTGAN/LLM training or privacy guarantee.

  • Single AI author checked CTGAN v2 sections4.2-4.3, Self-Instruct selected sections2.1-2.3/opening3.3 and fixed sampler/filter code. Six paired equations and four explained exercises; original100-row binary joint model, conditional prior changes,4096-row generated training sets and independent10000-row target tests. Actual independent-sample accuracy0.74 retained versus0.5 population rule; no CTGAN/LLM training or privacy guarantee.
  • Four computed SVG variants per topic. Fifteen numeric/geometry tests and36 responsive cases passed; twelve final Chinese-mobile/English-desktop screenshots actually inspected. Initial label polish and English mobile-title clipping correction preserved. Full article acceptance recorded separately.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.