Skip to content

ASynthetic data · synth.mixture

Synthetic data — Gaussian mixture

Can I generate numeric rows from a mixture of a few overlapping groups that resembles this data?

Fits a Gaussian mixture model to the standardized numeric columns — optionally choosing the number of components by BIC — and samples new rows from it: each row picks a component by its weight and draws from that component's multivariate normal. Values can be clipped to the observed range, and whole-number columns stay whole. Good for numeric tables with clusters or skewed, multi-modal shapes. A share of rows is held out of training for privacy and utility checks; the fit and the draws use the shared random stream, so Python and R produce the same rows.

Verified in Python and R Python and R agree to 6 decimals

A real result

Example “Iris full”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

Synthetic data — Gaussian mixtureRecorded · Python and R agreeRecorded 2026-11-17 · 30 values compared
R

120 synthetic rows over 4 columns from 120 training rows with a 3-component Gaussian mixture (full covariances). Numeric columns differ from the data by a mean Kolmogorov–Smirnov distance of 0.119.

Synthetic rows
120
Mean KS distance
0.1187
Mean TV distance
—
Rows copied from the data
0

Plots

sepal_length: real vs syntheticDoes the synthetic data reproduce the shape of a numeric column?
View data
DensitySourcesepal_length
0.2206real4.357
0.0735real4.470
0.2206real4.583
0.1471real4.697
0.2941real4.810
0.3676real4.923
0.5147real5.037
0.7353real5.150
0.0735real5.263
0.2941real5.377
0.4412real5.490
0.2941real5.603
0.5147real5.717
0.5147real5.830
0.2206real5.943
0.6618real6.057
0.2941real6.170
0.5882real6.283
0.5147real6.397
0.2941real6.510
0.0735real6.623
0.5147real6.737
0.3676real6.850
0real6.963
0.0735real7.077
0.0735real7.190
0.0735real7.303
0.0735real7.417
0real7.530
0.2941real7.643
0.1471synthetic4.357
0.0735synthetic4.470
0.0735synthetic4.583
0.2941synthetic4.697
0.2206synthetic4.810
0.3676synthetic4.923
0.5882synthetic5.037
1.103synthetic5.150
0.3676synthetic5.263
0.3676synthetic5.377
0.5147synthetic5.490
0.5147synthetic5.603
0.5882synthetic5.717
0.1471synthetic5.830
0.4412synthetic5.943
0.4412synthetic6.057
0.2941synthetic6.170
0.2941synthetic6.283
0.4412synthetic6.397
0.5882synthetic6.510
0.0735synthetic6.623
0.0735synthetic6.737
0.1471synthetic6.850
0.1471synthetic6.963
0synthetic7.077
0.2941synthetic7.190
0.0735synthetic7.303
0.0735synthetic7.417
0synthetic7.530
0.0735synthetic7.643
sepal_width: real vs syntheticDoes the synthetic data reproduce the shape of a numeric column?
View data
DensitySourcesepal_width
0.1042real2.040
0real2.120
0.3125real2.200
0.2083real2.280
0.2083real2.360
0real2.440
0.8333real2.520
0.5208real2.600
0.6250real2.680
1.354real2.760
0real2.840
0.7292real2.920
1.979real3
1.042real3.080
0real3.160
1.146real3.240
0.4167real3.320
1.146real3.400
0.6250real3.480
0.2083real3.560
0real3.640
0.1042real3.720
0.5208real3.800
0.1042real3.880
0.1042real3.960
0real4.040
0real4.120
0.1042real4.200
0real4.280
0.1042real4.360
0synthetic2.040
0.2083synthetic2.120
0.2083synthetic2.200
0synthetic2.280
0.3125synthetic2.360
0.1042synthetic2.440
0.5208synthetic2.520
0.4167synthetic2.600
0.9375synthetic2.680
0.5208synthetic2.760
0.9375synthetic2.840
1.250synthetic2.920
0.9375synthetic3
0.8333synthetic3.080
0.6250synthetic3.160
0.5208synthetic3.240
0.3125synthetic3.320
1.250synthetic3.400
0.7292synthetic3.480
0.4167synthetic3.560
0.6250synthetic3.640
0.2083synthetic3.720
0synthetic3.800
0.2083synthetic3.880
0.2083synthetic3.960
0.1042synthetic4.040
0synthetic4.120
0synthetic4.200
0.1042synthetic4.280
0synthetic4.360
petal_length: real vs syntheticDoes the synthetic data reproduce the shape of a numeric column?
View data
DensitySourcepetal_length
0.1293real1.197
0.7759real1.390
0.6466real1.583
0.1293real1.777
0.0862real1.970
0real2.163
0real2.357
0real2.550
0real2.743
0.0431real2.937
0real3.130
0real3.323
0.1293real3.517
0.0862real3.710
0.2586real3.903
0.0862real4.097
0.2155real4.290
0.4310real4.483
0.2155real4.677
0.3448real4.870
0.4741real5.063
0.1724real5.257
0.1724real5.450
0.3448real5.643
0.0862real5.837
0.1724real6.030
0.0431real6.223
0real6.417
0.0862real6.610
0.0431real6.803
0.2155synthetic1.197
0.8190synthetic1.390
0.7328synthetic1.583
0.1724synthetic1.777
0synthetic1.970
0synthetic2.163
0synthetic2.357
0synthetic2.550
0.0431synthetic2.743
0synthetic2.937
0.1293synthetic3.130
0synthetic3.323
0.0431synthetic3.517
0.1293synthetic3.710
0.3017synthetic3.903
0.1293synthetic4.097
0.1724synthetic4.290
0.2586synthetic4.483
0.1724synthetic4.677
0.1724synthetic4.870
0.3448synthetic5.063
0.3448synthetic5.257
0.3879synthetic5.450
0.2586synthetic5.643
0.2155synthetic5.837
0.0431synthetic6.030
0.0431synthetic6.223
0.0431synthetic6.417
0synthetic6.610
0synthetic6.803
petal_width: real vs syntheticDoes the synthetic data reproduce the shape of a numeric column?
View data
DensitySourcepetal_width
0.4167real0.1400
2.396real0.2200
0.7292real0.3000
0.5208real0.3800
0real0.4600
0.1042real0.5400
0.1042real0.6200
0real0.7000
0real0.7800
0real0.8600
0real0.9400
0.5208real1.020
0.3125real1.100
0.5208real1.180
0real1.260
0.9375real1.340
0.6250real1.420
1.042real1.500
0.1042real1.580
0.2083real1.660
0real1.740
1.146real1.820
0.5208real1.900
0.5208real1.980
0real2.060
0.4167real2.140
0.2083real2.220
0.7292real2.300
0.2083real2.380
0.2083real2.460
1.042synthetic0.1400
1.250synthetic0.2200
1.979synthetic0.3000
0.3125synthetic0.3800
0.1042synthetic0.4600
0synthetic0.5400
0synthetic0.6200
0synthetic0.7000
0synthetic0.7800
0synthetic0.8600
0.3125synthetic0.9400
0.3125synthetic1.020
0.5208synthetic1.100
0.6250synthetic1.180
0.4167synthetic1.260
0.4167synthetic1.340
0.5208synthetic1.420
0.2083synthetic1.500
0.7292synthetic1.580
0synthetic1.660
0.1042synthetic1.740
0.5208synthetic1.820
0.4167synthetic1.900
0.5208synthetic1.980
0.5208synthetic2.060
0.1042synthetic2.140
0.1042synthetic2.220
0.7292synthetic2.300
0.3125synthetic2.380
0.4167synthetic2.460
Correlation difference (real − synthetic)What do the values of a square or rectangular result matrix look like at a glance?
View data
ColumnColumnDifference
sepal_lengthsepal_length0
sepal_widthsepal_length0.0329
petal_lengthsepal_length0.0274
petal_widthsepal_length0.0206
sepal_lengthsepal_width0.0329
sepal_widthsepal_width0
petal_lengthsepal_width0.0487
petal_widthsepal_width0.0209
sepal_lengthpetal_length0.0274
sepal_widthpetal_length0.0487
petal_lengthpetal_length0
petal_widthpetal_length−0.0002
sepal_lengthpetal_width0.0206
sepal_widthpetal_width0.0209
petal_lengthpetal_width−0.0002
petal_widthpetal_width0

Real vs synthetic, column by column

ColumnKindRealSyntheticDistanceMeasure
sepal_lengthnumeric5.828 ± 0.85.714 ± 0.7240.1250Kolmogorov–Smirnov D
sepal_widthnumeric3.042 ± 0.4313.076 ± 0.4330.1250Kolmogorov–Smirnov D
petal_lengthnumeric3.725 ± 1.763.567 ± 1.750.0917Kolmogorov–Smirnov D
petal_widthnumeric1.188 ± 0.7631.146 ± 0.7940.1333Kolmogorov–Smirnov D
  • 30 of 150 rows (20%) were held out of training so privacy and utility can be checked against rows the generator never saw.
Python

120 synthetic rows over 4 columns from 120 training rows with a 3-component Gaussian mixture (full covariances). Numeric columns differ from the data by a mean Kolmogorov–Smirnov distance of 0.119.

Synthetic rows
120
Mean KS distance
0.1187
Mean TV distance
—
Rows copied from the data
0

To keep this page light, the plots are shown once, under the R tab.

Real vs synthetic, column by column

ColumnKindRealSyntheticDistanceMeasure
sepal_lengthnumeric5.828 ± 0.85.714 ± 0.7240.1250Kolmogorov–Smirnov D
sepal_widthnumeric3.042 ± 0.4313.076 ± 0.4330.1250Kolmogorov–Smirnov D
petal_lengthnumeric3.725 ± 1.763.567 ± 1.750.0917Kolmogorov–Smirnov D
petal_widthnumeric1.188 ± 0.7631.146 ± 0.7940.1333Kolmogorov–Smirnov D
  • 30 of 150 rows (20%) were held out of training so privacy and utility can be checked against rows the generator never saw.

Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.

Worked examples in the app

  • Iris fullml_iris · columns: sepal_length, sepal_width, petal_length, petal_width
  • Customers select kg1_customers · columns: age, annual income, tenure_months, signup
  • Penguins tied noclipml_penguins · columns: bill_len, bill_dep, flipper_len, body_mass
  • Degenerate all naml_iris · columns: sepal_length, sepal_width, petal_length, petal_width
  • Degenerate n2ml_iris · columns: sepal_length, sepal_width, petal_length, petal_width
  • Degenerate infml_iris · columns: sepal_length, sepal_width, petal_length, petal_width

In the guides

Where it sits in the decision guides

  • Generative models (GMM, VAEs) · DS & ML Decision Guide · Generate

What you need

Numeric columnsnumeric / temporal · 1–50 columns
Numbers and dates. Categories need the copula or the CART generator.

Choices you make

options

Synthetic rowsdefault —

How many synthetic rows to generate. Leave empty to match the number of real rows.

Missing valuesdefault keep_rate

Whether synthetic data keeps each column's share of missing values (placed at random).

  • Keep each column's missing share (at random)(default) — Blanks synthetic values at each column's real missing share, at random; keeps the data's gaps in overall rate.
  • No missing values — Produces complete synthetic data with no gaps; pick it when downstream tools can't handle missing values.

model

Components (k)default 3

Number of mixture components (clusters) fitted to the data, or the largest tried when choosing by BIC.

Choose k by BIC (1 … k)default off

Try 1 to k components and keep the one with the lowest BIC.

Covariancedefault full

Shape of each mixture component: full ellipses, axis-aligned, one shared shape, or circles.

  • Full (each component its own ellipse)(default) — Every component has its own size, shape and tilt; the most flexible, and it needs the most data.
  • Diagonal (axis-aligned ellipses) — Components are ellipses along the axes; pick it for wide data or roughly uncorrelated features within clusters.
  • Tied (one shared ellipse) — All components share one shape; pick it when clusters look like shifted copies of each other.
  • Spherical (circles) — Components are circles with their own sizes; the fewest parameters and the closest to k-means.
Keep values inside the observed rangedefault on

Keep synthetic values inside each column's observed minimum and maximum.

Advanced

Startsdefault 3

Number of random starts; the best fit is kept.

Maximum iterationsdefault 500

Upper limit on EM iterations when fitting the mixture. Raise it if the fit warns that it did not converge.

Convergence tolerancedefault 1e-8

Fitting stops when the improvement falls below this tolerance.

validation

Holdout for privacy and utility checksdefault 0.2

Share of rows kept out of training. The scorecard compares synthetic rows with these unseen rows.

What it reports

n_rows
How many independent units the analysis used; it sets precision and power.
n_real
How many independent units the analysis used; it sets precision and power.
n_input
How many independent units the analysis used; it sets precision and power.
n_holdout
How many independent units the analysis used; it sets precision and power.
n_columns
How many independent units the analysis used; it sets precision and power.
exact_matches
How far a row sits from its nearest training row; synthetic rows should sit no closer than real rows the generator never saw.
fidelity_ks_mean
How closely synthetic rows match the real ones, column by column, in pairs, and as whole rows.
k
How many groups, studies or clusters the analysis used. Many methods are less reliable when k is small.
bic
Like AIC but with a stronger penalty for parameters as n grows; favors simpler models.

Per group, level or term: mean[<column>], sd[<column>], wmean[<column>], missing[<column>], ks[<column>], weight[<component>], corr_mad, fidelity_tv_mean

Python and R

Python and R agree to 6 decimals (relative tolerance 1e-6). Python uses scikit-learn, pyarrow; R uses stats, nanoparquet.

Default traps between the two languages

  • Python fits with scikit-learn's GaussianMixture and R with codesplashr::cs_ml_gmm_em (the Phase 6 twin of the same EM updates), both from the same host-drawn starts, so the parameters agree to about 1e-9; the synthetic rows are then drawn from the shared stream through each language's Cholesky factor and inherit that agreement.
  • mclust::Mclust and scikit-learn's own sampler (GaussianMixture.sample, numpy's generator) are the classic equivalents; their random draws differ.
Python

The exact script CodeSplash ran for example “Iris full” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0

# Synthetic data — Gaussian mixture
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method synth.mixture 1.0.1 · spec e39203d9d91acae3
# Dataset: ml_iris (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os

import numpy as np

import codesplash as cs
from codesplash.errors import check_finite
from codesplash.ml.run import out_dir
from codesplash.stats.rng import Rng
from codesplash.synth import common as sy
from codesplash.synth import mixture

# %% Data
COLUMNS = ["sepal_length", "sepal_width", "petal_length", "petal_width"]
KINDS = {
    "sepal_length": "numeric",
    "sepal_width": "numeric",
    "petal_length": "numeric",
    "petal_width": "numeric",
}
LEVELS = {
}
SEED = 42
cols, n_input = sy.load("tests/parity/fixtures/ml_iris.parquet", COLUMNS, KINDS, LEVELS)
for c in cols:
    if c.kind == "numeric":
        check_finite(c.values, c.name)  # infinite values stop the run (registry/errors.yaml)
rng = Rng(SEED)  # shared stream: the same holdout and the same synthetic rows in Python and R
train_rows, holdout_rows = sy.split_holdout(n_input, 0.2, rng)
train = [c.take(train_rows) for c in cols]
N_OUT = None or len(train_rows)
warnings = []
fit_values = {}
extra_tables = []
model_note = ""
if len(holdout_rows):
    warnings.append(f"{len(holdout_rows):,} of {n_input:,} rows ({len(holdout_rows) / n_input:.0%}) were held out of training so privacy and utility can be checked against rows the generator never saw.")
for c in train:
    share = float(np.mean(c.missing()))
    if share == 1.0:
        cs.cs_error("CS_E_ALL_MISSING", column=c.name)  # no values in the training rows

# %% Generate
# Gaussian mixture: scikit-learn's GaussianMixture from host-drawn starts (R: the cs_ml_gmm_em twin),
# then shared-stream sampling from the fitted components.
synth, facts = mixture.synthesize(
    train, N_OUT, rng, k=3, covariance="full", n_init=3, tol=1e-8,
    max_iter=500, select_k=False, clip=True, seed=SEED,
)
fit_values["k"] = facts["k"]
fit_values["bic"] = facts["bic"]
for j, w in enumerate(facts["weights"]):
    fit_values[f"weight[{j + 1}]"] = w
model_note = f" with a {facts['k']}-component Gaussian mixture (full covariances)"
sy.add_missing(synth, train, rng, "keep_rate")  # each column's missing share, at random

# %% Write and compare
out = out_dir("target/academy-parity/run-953/synth.mixture/iris_full/out-python")
path = sy.write(os.path.join(out, "synthetic.parquet"), synth)
split = sy.write_split(os.path.join(out, "split.parquet"), n_input, train_rows, holdout_rows)
values, table, charts = sy.summarize(train, synth, len(train_rows), n_input, len(holdout_rows), fit_values)
summary = (
    f"{values['n_rows']:,} synthetic rows over {len(COLUMNS)} column{'s' if len(COLUMNS) != 1 else ''} from "
    f"{len(train_rows):,} training rows{model_note}."
)
if not np.isnan(values["fidelity_ks_mean"]):
    summary += f" Numeric columns differ from the data by a mean Kolmogorov–Smirnov distance of {values['fidelity_ks_mean']:.3f}"
    summary += f" and categories by a mean total variation of {values['fidelity_tv_mean']:.3f}." if not np.isnan(values["fidelity_tv_mean"]) else "."
elif not np.isnan(values["fidelity_tv_mean"]):
    summary += f" Categories differ from the data by a mean total variation of {values['fidelity_tv_mean']:.3f}."
if values["exact_matches"]:
    summary += f" {values['exact_matches']:,} synthetic row{'s are' if values['exact_matches'] != 1 else ' is'} identical to a training row."
sy.publish(
    "Synthetic data — Gaussian mixture",
    cs.engine_info("scikit-learn", "pyarrow", "numpy", "pyarrow"),
    summary, values, table, charts, warnings,
    [{"key": "synthetic", "path": path, "format": "parquet", "title": "Synthetic rows"},
     {"key": "split", "path": split, "format": "parquet", "title": "Training and holdout rows"}],
    {"kind": "generator", "columns": COLUMNS, "params": {
        "n_rows": None,
        "k": 3,
        "select_k": False,
        "covariance": "full",
        "n_init": 3,
        "max_iter": 500,
        "tol": 1e-8,
        "clip": True,
        "missing": "keep_rate",
        "holdout": 0.2,
    }},
    extra_tables,
)
R

The exact script CodeSplash ran for example “Iris full” · R version 4.5.1 (2025-06-13)

# Synthetic data — Gaussian mixture
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method synth.mixture 1.0.1 · spec e39203d9d91acae3
# Dataset: ml_iris (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Data
COLUMNS <- c("sepal_length", "sepal_width", "petal_length", "petal_width")
KINDS <- list(
  sepal_length = "numeric",
  sepal_width = "numeric",
  petal_length = "numeric",
  petal_width = "numeric"
)
LEVELS <- list(
)
SEED <- 42
loaded <- cs_synth_load("tests/parity/fixtures/ml_iris.parquet", COLUMNS, KINDS, LEVELS)
cols <- loaded$cols; n_input <- loaded$n
for (c in cols) if (c$kind == "numeric") cs_check_finite(c$values, c$name)  # infinite values stop the run (registry/errors.yaml)
rng <- cs_rng(SEED)  # shared stream: the same holdout and the same synthetic rows in Python and R
sp <- cs_synth_split(n_input, 0.2, rng)
train_rows <- sp$train; holdout_rows <- sp$holdout
train <- lapply(cols, cs_synth_take, rows = train_rows)
N_OUT <- length(train_rows)
warnings <- list()
fit_values <- list()
extra_tables <- list()
model_note <- ""
if (length(holdout_rows)) {
  warnings <- c(warnings, sprintf("%s of %s rows (%.0f%%) were held out of training so privacy and utility can be checked against rows the generator never saw.",
                                  format(length(holdout_rows), big.mark = ","), format(n_input, big.mark = ","), 100 * length(holdout_rows) / n_input))
}
for (c in train) if (mean(cs_synth_missing(c)) == 1) cs_error("CS_E_ALL_MISSING", column = c$name)  # no values in the training rows

# %% Generate
# Gaussian mixture: the cs_ml_gmm_em twin of scikit-learn's EM from host-drawn starts, then
# shared-stream sampling from the fitted components.
fit <- cs_synth_mixture(train, N_OUT, rng, k = 3L, covariance = "full", n_init = 3L,
                        tol = 1e-8, max_iter = 500L, select_k = FALSE,
                        clip = TRUE)
synth <- fit$cols
fit_values$k <- fit$facts$k
fit_values$bic <- fit$facts$bic
for (j in seq_along(fit$facts$weights)) fit_values[[sprintf("weight[%d]", j)]] <- fit$facts$weights[j]
model_note <- sprintf(" with a %d-component Gaussian mixture (%s covariances)", fit$facts$k, "full")
synth <- cs_synth_add_missing(synth, train, rng, "keep_rate")  # each column's missing share, at random

# %% Write and compare
out <- cs_ml_out_dir("target/academy-parity/run-953/synth.mixture/iris_full/out-r")
path <- cs_synth_write(file.path(out, "synthetic.parquet"), synth)
split <- cs_synth_write_split(file.path(out, "split.parquet"), n_input, train_rows, holdout_rows)
sm <- cs_synth_summarize(train, synth, length(train_rows), n_input, length(holdout_rows), fit_values)
values <- sm$values
summary <- sprintf("%s synthetic rows over %d column%s from %s training rows%s.",
                   format(values$n_rows, big.mark = ","), length(COLUMNS), if (length(COLUMNS) != 1) "s" else "",
                   format(length(train_rows), big.mark = ","), model_note)
if (!is.nan(values$fidelity_ks_mean)) {
  summary <- paste0(summary, sprintf(" Numeric columns differ from the data by a mean Kolmogorov–Smirnov distance of %.3f", values$fidelity_ks_mean),
                    if (!is.nan(values$fidelity_tv_mean)) sprintf(" and categories by a mean total variation of %.3f.", values$fidelity_tv_mean) else ".")
} else if (!is.nan(values$fidelity_tv_mean)) {
  summary <- paste0(summary, sprintf(" Categories differ from the data by a mean total variation of %.3f.", values$fidelity_tv_mean))
}
if (values$exact_matches > 0) {
  summary <- paste0(summary, sprintf(" %s synthetic row%s identical to a training row.", format(values$exact_matches, big.mark = ","),
                                     if (values$exact_matches != 1) "s are" else " is"))
}
cs_synth_publish(
  "Synthetic data — Gaussian mixture",
  cs_engine_info("stats", "nanoparquet", "nanoparquet"),
  summary, values, sm$table, sm$charts, warnings,
  list(list(key = "synthetic", path = path, format = "parquet", title = "Synthetic rows"),
       list(key = "split", path = split, format = "parquet", title = "Training and holdout rows")),
  list(kind = "generator", columns = I(COLUMNS), params = list(
    n_rows = NULL,
    k = 3,
    select_k = FALSE,
    covariance = "full",
    n_init = 3,
    max_iter = 500,
    tol = 1e-8,
    clip = TRUE,
    missing = "keep_rate",
    holdout = 0.2
  )),
  extra_tables
)

Sources

  • Dempster AP, Laird NM, Rubin DB (1977). Maximum likelihood from incomplete data via the EM algorithm. JRSS B 39:1–38.
  • Schwarz G (1978). Estimating the dimension of a model. Annals of Statistics 6:461–464 (BIC).

From the CodeSplash method registry · synth.mixture v1.0.1.