Skip to content

GANs: a generator, a discriminator and a game

A generator turns noise into rows and a discriminator learns to spot fakes. Read the game they play, why the generator uses a non-saturating loss, how DCGAN's upsampling makes checkerboards, and why the losses don't tell you sample quality.

Advanced ~14 min10 steps

What runs in CodeSplash

You will be able to

  • Write the GAN objective and the non-saturating generator loss
  • Explain mode collapse and why a GAN gives no likelihood
  • Describe DCGAN's design and where checkerboard artifacts come from
  • Judge a GAN by its samples, not its losses

Read first

01

Two networks with opposite goals

Read

A generative adversarial networkGenerative adversarial networkA generator learns to fool a discriminator that is trained to tell its output from real data. has a generator GG that turns noise zz into a row, and a discriminator DD that outputs the probability a row is real. They play a game:

min⁡Gmax⁡D  Ex[log⁡D(x)]+Ez[log⁡(1−D(G(z)))].\min_G \max_D \; \mathbb{E}_{x}\left[\log D(x)\right] + \mathbb{E}_{z}\left[\log\left(1 - D(G(z))\right)\right].

DD wants high scores on real rows and low ones on fakes. GG wants its fakes to score high. If DD were optimal at every step, GG would be minimizing a Jensen–Shannon divergence between real and generated rows.

02

The non-saturating loss

Read

Early in training the discriminator wins easily: D(G(z))D(G(z)) is near 0, where log⁡(1−D)\log(1 - D) is flat, so the generator gets almost no gradient. The usual fix is the non-saturating lossNon-saturating generator lossTrains the generator to maximize log D(fake) instead of minimizing log(1 − D(fake)), which keeps gradients alive early on.: the generator maximizes log⁡D(G(z))\log D(G(z)) instead, which is steep exactly where the fakes are bad.

In the reference's example a discriminator rates three real rows high and three fakes low. Its loss is 0.457; the generator's non-saturating loss is 1.705, large because its fakes are easy to spot.

03

The losses aren't a quality score

Predict

Predict first

Halfway through training, the generator's loss stops falling and starts to wander. What does that tell you about sample quality?

Its samples improvedNothing reliable about sample qualityThe discriminator broke
Reveal

Nothing reliable. Each loss is measured against the other player, who is also changing. A wandering loss can mean a balanced game or an oscillating one. Look at samples and score them against held-out rows.

04

Mode collapse

Read

The generator only has to fool the current discriminator. Often the cheapest way is to produce a few kinds of convincing rows and ignore the rest. That is mode collapseMode collapseA generator that covers only some of the data's kinds of rows, often switching between them, while its loss looks fine.: samples look good one at a time, but some categories or regions of the data never appear.

A GAN also gives no likelihood. You can't score how probable a held-out row is under it, so overfitting has to be checked through samples: coverage of every category, distances to the nearest training row, and a scorecard against held-out data.

A generator trained like a GAN against the best discriminator, beside one trained by likelihood.

DExplorable · GAN dynamics: two players, collapse, gradient penalty

Why is GAN training unstable, and why does a GAN drop modes?

Where does training end up?

How sure?

View

Loss (two players)

Discriminator penalty

Updates

0.20
0.50

γ for R1, λ for WGAN-GP.

200

Generator trained by

Mode collapse view: a GAN with the best discriminator minimizes JS; reverse KL is the most mode-seeking; maximum likelihood minimizes KL(data‖model).

2.5

Modes at ±this value (mode collapse view).

1.5
  • Data (two modes)
  • Generator N(2.50, 0.50²)

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

05

A GAN in the Synthetic studio

Explore
Synthetic data — tabular GAN (WGAN-GP)Recorded · Python and R agreeRecorded 2026-11-25 · 56 values compared
R

320 synthetic rows over 8 columns from 320 training rows with a Wasserstein GAN (gradient penalty). Numeric columns differ from the data by a mean Kolmogorov–Smirnov distance of 0.179 and categories by a mean total variation of 0.231.

Synthetic rows
320
Mean KS distance
0.1790
Mean TV distance
0.2315
Rows copied from the data
0

Plots

age: real vs syntheticDoes the synthetic data reproduce the shape of a numeric column?
View data
DensitySourceage
0.0230real18.950
0.0016real20.850
0.0049real22.750
0.0148real24.650
0.0148real26.550
0.0181real28.450
0.0197real30.350
0.0296real32.250
0.0362real34.150
0.0115real36.050
0.0362real37.950
0.0313real39.850
0.0296real41.750
0.0280real43.650
0.0280real45.550
0.0181real47.450
0.0164real49.350
0.0197real51.250
0.0362real53.150
0.0148real55.050
0.0164real56.950
0.0181real58.850
0.0082real60.750
0.0164real62.650
0.0049real64.550
0.0115real66.450
0.0066real68.350
0.0049real70.250
0.0016real72.150
0.0049real74.050
0.0395synthetic18.950
0.0214synthetic20.850
0.0164synthetic22.750
0.0164synthetic24.650
0.0099synthetic26.550
0.0296synthetic28.450
0.0280synthetic30.350
0.0197synthetic32.250
0.0181synthetic34.150
0.0132synthetic36.050
0.0230synthetic37.950
0.0164synthetic39.850
0.0230synthetic41.750
0.0066synthetic43.650
0.0132synthetic45.550
0.0296synthetic47.450
0.0230synthetic49.350
0.0362synthetic51.250
0.0132synthetic53.150
0.0115synthetic55.050
0.0214synthetic56.950
0.0132synthetic58.850
0.0115synthetic60.750
0.0066synthetic62.650
0.0099synthetic64.550
0.0099synthetic66.450
0.0099synthetic68.350
0.0049synthetic70.250
0.0115synthetic72.150
0.0197synthetic74.050
annual income: real vs syntheticDoes the synthetic data reproduce the shape of a numeric column?
View data
DensitySourceannual income
3.010e-6real6851.93
1.605e-5real10141.74
2.107e-5real13431.55
2.408e-5real16721.36
3.511e-5real20011.17
4.113e-5real23300.98
2.809e-5real26590.79
2.408e-5real29880.60
2.508e-5real33170.41
1.605e-5real36460.22
1.605e-5real39750.03
1.505e-5real43039.84
1.003e-5real46329.65
5.016e-6real49619.46
6.019e-6real52909.27
4.013e-6real56199.07
4.013e-6real59488.88
4.013e-6real62778.69
1.003e-6real66068.50
1.003e-6real69358.31
1.003e-6real72648.12
0real75937.93
1.003e-6real79227.74
1.003e-6real82517.55
0real85807.36
0real89097.17
0real92386.98
0real95676.79
0real98966.60
1.003e-6real102256.41
3.912e-5synthetic6851.93
1.304e-5synthetic10141.74
2.307e-5synthetic13431.55
2.909e-5synthetic16721.36
3.612e-5synthetic20011.17
1.605e-5synthetic23300.98
3.010e-5synthetic26590.79
1.906e-5synthetic29880.60
1.505e-5synthetic33170.41
9.029e-6synthetic36460.22
1.304e-5synthetic39750.03
1.605e-5synthetic43039.84
8.026e-6synthetic46329.65
4.013e-6synthetic49619.46
4.013e-6synthetic52909.27
3.010e-6synthetic56199.07
3.010e-6synthetic59488.88
4.013e-6synthetic62778.69
4.013e-6synthetic66068.50
2.006e-6synthetic69358.31
1.003e-6synthetic72648.12
1.003e-6synthetic75937.93
3.010e-6synthetic79227.74
2.006e-6synthetic82517.55
1.003e-6synthetic85807.36
0synthetic89097.17
1.003e-6synthetic92386.98
0synthetic95676.79
0synthetic98966.60
4.013e-6synthetic102256.41
tenure_months: real vs syntheticDoes the synthetic data reproduce the shape of a numeric column?
View data
DensitySourcetenure_months
0.0938real0.7667
0.0224real2.300
0.0183real3.833
0.0306real5.367
0.0204real6.900
0.0265real8.433
0.0204real9.967
0.0530real11.500
0.0183real13.033
0.0510real14.567
0.0183real16.100
0.0367real17.633
0.0224real19.167
0.0448real20.700
0.0469real22.233
0.0082real23.767
0.0306real25.300
0.0061real26.833
0.0183real28.367
0.0041real29.900
0.0143real31.433
0.0061real32.967
0.0183real34.500
0.0020real36.033
0.0041real37.567
0real39.100
0.0061real40.633
0.0041real42.167
0.0020real43.700
0.0041real45.233
0.1651synthetic0.7667
0synthetic2.300
0.0041synthetic3.833
0.0143synthetic5.367
0.0020synthetic6.900
0.0306synthetic8.433
0.0122synthetic9.967
0.0469synthetic11.500
0.0245synthetic13.033
0.0061synthetic14.567
0.0041synthetic16.100
0.0265synthetic17.633
0.0061synthetic19.167
0.0306synthetic20.700
0.0367synthetic22.233
0.0122synthetic23.767
0.0326synthetic25.300
0.0143synthetic26.833
0.0306synthetic28.367
0.0082synthetic29.900
0.0306synthetic31.433
0.0163synthetic32.967
0.0082synthetic34.500
0.0061synthetic36.033
0.0082synthetic37.567
0.0020synthetic39.100
0.0041synthetic40.633
0.0102synthetic42.167
0.0061synthetic43.700
0.0530synthetic45.233
signup: real vs syntheticDoes the synthetic data reproduce the shape of a numeric column?
View data
DensitySourcesignup
0.0005real17582.23
0.0007real17654.70
0.0005real17727.17
0.0005real17799.63
0.0004real17872.10
0.0005real17944.57
0.0006real18017.03
0.0004real18089.50
0.0005real18161.97
0.0005real18234.43
0.0001real18306.90
0.0009real18379.37
0.0006real18451.83
0.0003real18524.30
0.0005real18596.77
0.0004real18669.23
0.0002real18741.70
0.0005real18814.17
0.0006real18886.63
0.0005real18959.10
0.0005real19031.57
0.0005real19104.03
0.0003real19176.50
0.0006real19248.97
0.0004real19321.43
0.0003real19393.90
0.0002real19466.37
0.0005real19538.83
0.0003real19611.30
0.0004real19683.77
0.0029synthetic17582.23
0.0014synthetic17654.70
0.0009synthetic17727.17
0.0009synthetic17799.63
0.0004synthetic17872.10
8.625e-5synthetic17944.57
0.0001synthetic18017.03
0.0002synthetic18089.50
0.0002synthetic18161.97
0.0003synthetic18234.43
0.0003synthetic18306.90
0.0001synthetic18379.37
0.0004synthetic18451.83
0.0003synthetic18524.30
0.0004synthetic18596.77
0.0003synthetic18669.23
0.0003synthetic18741.70
0.0002synthetic18814.17
4.312e-5synthetic18886.63
0.0003synthetic18959.10
0.0001synthetic19031.57
0.0002synthetic19104.03
8.625e-5synthetic19176.50
0.0002synthetic19248.97
0.0001synthetic19321.43
0.0003synthetic19393.90
0.0003synthetic19466.37
0.0004synthetic19538.83
0.0008synthetic19611.30
0.0011synthetic19683.77
plan: real vs syntheticDoes the synthetic data keep the category proportions of the real data?
View data
planShareSource
basic0.3563real
plus0.3969real
premium0.2469real
basic0.4406synthetic
plus0.2562synthetic
premium0.3031synthetic
region: real vs syntheticDoes the synthetic data keep the category proportions of the real data?
View data
regionShareSource
east0.2848real
north0.2718real
south0.3042real
west0.1392real
east0.6230synthetic
north0.2109synthetic
south0.0990synthetic
west0.0671synthetic
churned: real vs syntheticDoes the synthetic data keep the category proportions of the real data?
View data
churnedShareSource
false0.7688real
true0.2313real
false0.5531synthetic
true0.4469synthetic
Correlation difference (real − synthetic)What do the values of a square or rectangular result matrix look like at a glance?
View data
ColumnColumnDifference
ageage0
annual incomeage0.3704
tenure_monthsage0.7748
signupage−0.0899
visitsage0.1080
ageannual income0.3704
annual incomeannual income0
tenure_monthsannual income0.1488
signupannual income0.0683
visitsannual income0.2467
agetenure_months0.7748
annual incometenure_months0.1488
tenure_monthstenure_months0
signuptenure_months−0.1098
visitstenure_months0.1820
agesignup−0.0899
annual incomesignup0.0683
tenure_monthssignup−0.1098
signupsignup0
visitssignup0.0735
agevisits0.1080
annual incomevisits0.2467
tenure_monthsvisits0.1820
signupvisits0.0735
visitsvisits0
Critic and generator by epochIs the network still learning, and which part of its loss moves?

The Wasserstein estimate is mean critic score on real rows minus fake rows; it should fall and level off as the generator improves.

View data
SeriesValueEpoch
Wasserstein estimate−0.05871
Wasserstein estimate−0.04792
Wasserstein estimate−0.05193
Wasserstein estimate−0.04344
Wasserstein estimate−0.02335
Wasserstein estimate−0.00406
Wasserstein estimate−0.00167
Wasserstein estimate0.01538
Wasserstein estimate0.07529
Wasserstein estimate0.098910
Wasserstein estimate0.158711
Wasserstein estimate0.200712
Wasserstein estimate0.250513
Wasserstein estimate0.267014
Wasserstein estimate0.326515
Wasserstein estimate0.351516
Wasserstein estimate0.406417
Wasserstein estimate0.438018
Wasserstein estimate0.473219
Wasserstein estimate0.487320
Wasserstein estimate0.505821
Wasserstein estimate0.577822
Wasserstein estimate0.590723
Wasserstein estimate0.625524
Wasserstein estimate0.646625
Wasserstein estimate0.695626
Wasserstein estimate0.704727
Wasserstein estimate0.717328
Wasserstein estimate0.789329
Wasserstein estimate0.759930
Wasserstein estimate0.787131
Wasserstein estimate0.791332
Wasserstein estimate0.788433
Wasserstein estimate0.795934
Wasserstein estimate0.794935
Wasserstein estimate0.812436
Wasserstein estimate0.813737
Wasserstein estimate0.803938
Wasserstein estimate0.787639
Wasserstein estimate0.751340
critic loss2.1931
critic loss1.8322
critic loss1.5063
critic loss1.1734
critic loss0.90345
critic loss0.61056
critic loss0.44287
critic loss0.32048
critic loss0.22339
critic loss0.197610
critic loss0.103211
critic loss0.062512
critic loss−0.016013
critic loss−0.032114
critic loss−0.097715
critic loss−0.134316
critic loss−0.181417
critic loss−0.232218
critic loss−0.281919
critic loss−0.282920

First 60 of 120 rows.

Assumptions

  • Enough rows for a neural generator — 293 complete training rows — neural generators have many weights to learn and can memorize small tables; compare with the copula or sequential trees.
  • Training stayed finite and the critic settled — Over the last 10% of epochs the Wasserstein estimate averaged 0.789 and the gradient penalty 0.0122.
  • No synthetic row copies a training row — 0 synthetic rows are identical to a training row; the scorecard's distance to closest record checks near-copies.
  • Synthetic columns match the data — Distance from the training rows: numeric columns 0.179 (mean Kolmogorov–Smirnov distance); categories 0.231 (mean total variation) — above 0.10, so some columns' distributions differ visibly from the data; the scorecard shows which columns and pairs.

Real vs synthetic, column by column

ColumnKindRealSyntheticDistanceMeasure
agenumeric43.14 ± 13.142.61 ± 16.20.1219Kolmogorov–Smirnov D
annual incomenumeric2.929e+04 ± 1.43e+042.835e+04 ± 1.96e+040.1386Kolmogorov–Smirnov D
tenure_monthsnumeric15 ± 10.718.16 ± 14.80.1750Kolmogorov–Smirnov D
plancategoricalplus 39.7%plus 25.6%0.1406total variation
regioncategoricalsouth 30.4%south 9.9%0.3382total variation
churnedbooleanfalse 76.9%false 55.3%0.2156total variation
signuptemporal2020-11-05 ± 621 days2020-04-08 ± 792 days0.3000Kolmogorov–Smirnov D
visitsnumeric3.394 ± 2.094.362 ± 3.120.1594Kolmogorov–Smirnov D

Modes per numeric column (mode-specific normalization)

ColumnMixture modes
age5
annual income5
tenure_months5
signup5
visits5
  • 80 of 400 rows (20%) were held out of training so privacy and utility can be checked against rows the generator never saw.
The exact R script · R R version 4.5.1 (2025-06-13)
# Synthetic data — tabular GAN (WGAN-GP)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method synth.gan 1.1.1 · spec b270e59f06622934
# Dataset: g1_customers (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("age", "annual income", "tenure_months", "plan", "region", "churned", "signup", "visits")
KINDS <- list(
  age = "numeric",
  `annual income` = "numeric",
  tenure_months = "numeric",
  plan = "categorical",
  region = "categorical",
  churned = "boolean",
  signup = "temporal",
  visits = "numeric"
)
LEVELS <- list(
  plan = c("basic", "plus", "premium"),
  region = c("east", "north", "south", "west")
)
SEED <- 42
loaded <- cs_synth_load("tests/parity/fixtures/g1_customers.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()
extra_charts <- list()
assumptions <- 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
n_complete <- length(cs_synth_complete(train))
assumptions[[1]] <- list(
  key = "enough_rows", label = "Enough rows for a neural generator",
  status = if (n_complete >= 1000) "pass" else "warn",
  detail = paste0(sprintf("%s complete training rows", format(n_complete, big.mark = ",")),
                  if (n_complete >= 1000) "." else " — neural generators have many weights to learn and can memorize small tables; compare with the copula or sequential trees.")
)

# %% Generate
# WGAN-GP on rows encoded by mode-specific normalization (numbers -> [alpha, mode one-hot], categories one-hot);
# the critic trains 5 steps per generator step with a gradient penalty of weight 10.
# Twin of codesplash.synth.neural.fit_gan (clean-room; no CTGAN/SDV code).
HIDDEN <- as.integer(unlist(c(32, 32)))
# Differential privacy (DP-SGD on the critic, the only part that sees real rows): with an epsilon or a noise
# multiplier set, each real row's critic loss is clipped and noise is added; the guarantee goes to dp.json.
DP <- cs_deep_dp_settings(list(
  dp_epsilon = NULL,
  dp_noise_multiplier = NULL,
  dp_max_grad_norm = 1,
  dp_delta = NULL,
  dp_sampling = "poisson"
))
if (!is.null(DP)) do.call(cs_deep_dp_make_private, c(DP, list(out_dir = cs_ml_out_dir("target/academy-parity/run-8142/synth.gan/customers_all/out-r"))))
fit <- cs_synth_gan(
  train, N_OUT, rng, HIDDEN,
  noise_dim = as.integer(16),
  epochs = as.integer(40),
  batch_size = 100,
  n_critic = as.integer(5),
  gp_weight = 10,
  lr = 0.0002,
  n_modes = as.integer(5),
  seed = SEED
)
synth <- fit$cols
hist <- fit$history
history <- data.frame(
  epoch = vapply(hist, function(h) as.numeric(h$epoch), numeric(1)),
  critic = vapply(hist, function(h) h$critic, numeric(1)),
  wasserstein = vapply(hist, function(h) h$wasserstein, numeric(1)),
  penalty = vapply(hist, function(h) h$penalty, numeric(1)),
  generator = vapply(hist, function(h) h$generator, numeric(1))
)
last <- max(1L, nrow(history) %/% 10L)  # the last 10% of epochs
tail_rows <- (nrow(history) - last + 1L):nrow(history)
fit_values$generator_steps <- fit$facts$generator_steps
fit_values$batch_size <- fit$facts$batch_size
fit_values$wasserstein <- mean(history$wasserstein[tail_rows])
fit_values$critic_loss <- mean(history$critic[tail_rows])
fit_values$penalty <- mean(history$penalty[tail_rows])
for (j in seq_along(COLUMNS)) {
  k <- fit$facts$modes[[j]]
  if (!is.null(k)) fit_values[[sprintf("modes[%s]", COLUMNS[j])]] <- as.integer(k)
}
model_note <- " with a Wasserstein GAN (gradient penalty)"
ne <- nrow(history)
extra_charts[[length(extra_charts) + 1L]] <- cs_chart("training", "training-components", "Critic and generator by epoch", list(
  x = cs_col("Epoch", rep(history$epoch, 3), "numeric"),
  value = cs_col("Value", c(history$wasserstein, history$critic, history$generator), "numeric"),
  component = cs_col("Series", rep(c("Wasserstein estimate", "critic loss", "generator loss"), each = ne), "categorical",
                     levels = c("Wasserstein estimate", "critic loss", "generator loss"))
), note = "The Wasserstein estimate is mean critic score on real rows minus fake rows; it should fall and level off as the generator improves.")
finite <- all(is.finite(c(history$critic, history$generator, history$wasserstein)))
assumptions[[length(assumptions) + 1L]] <- list(
  key = "training_stable", label = "Training stayed finite and the critic settled",
  status = if (!finite) "fail" else if (fit_values$penalty > 1) "warn" else "pass",
  detail = if (!finite) "A loss became infinite or undefined; lower the learning rate." else
    paste0(sprintf("Over the last 10%% of epochs the Wasserstein estimate averaged %s and the gradient penalty %s",
                   format(signif(fit_values$wasserstein, 3)), format(signif(fit_values$penalty, 3))),
           if (fit_values$penalty > 1) " — the critic's gradients are far from norm 1, so its estimate is unreliable." else ".")
)
mode_rows <- list()
for (j in seq_along(COLUMNS)) {
  k <- fit$facts$modes[[j]]
  if (!is.null(k)) mode_rows[[length(mode_rows) + 1L]] <- list(column = COLUMNS[j], modes = as.integer(k))
}
if (length(mode_rows)) {
  extra_tables[[length(extra_tables) + 1L]] <- list(
    key = "modes", title = "Modes per numeric column (mode-specific normalization)",
    columns = list(list(key = "column", label = "Column", type = "string"), list(key = "modes", label = "Mixture modes", type = "integer")),
    rows = mode_rows)
}
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-8142/synth.gan/customers_all/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)
nanoparquet::write_parquet(history, file.path(out, "history.parquet"))
sm <- cs_synth_summarize(train, synth, length(train_rows), n_input, length(holdout_rows), fit_values)
values <- sm$values
assumptions[[length(assumptions) + 1L]] <- list(
  key = "no_copies", label = "No synthetic row copies a training row",
  status = if (values$exact_matches == 0) "pass" else "warn",
  detail = sprintf("%s synthetic row%s identical to a training row; the scorecard's distance to closest record checks near-copies.",
                   format(values$exact_matches, big.mark = ","), if (values$exact_matches != 1) "s are" else " is")
)
# Fidelity (Stage 12.10): judged on the mean column distances, the scorecard's column fidelity (good at >= 0.9 = 1 - 0.1).
fid_d <- numeric(); fid_t <- character()
if (!is.nan(values$fidelity_ks_mean)) {
  fid_d <- c(fid_d, values$fidelity_ks_mean)
  fid_t <- c(fid_t, sprintf("numeric columns %.3f (mean Kolmogorov–Smirnov distance)", values$fidelity_ks_mean))
}
if (!is.nan(values$fidelity_tv_mean)) {
  fid_d <- c(fid_d, values$fidelity_tv_mean)
  fid_t <- c(fid_t, sprintf("categories %.3f (mean total variation)", values$fidelity_tv_mean))
}
assumptions[[length(assumptions) + 1L]] <- if (!length(fid_d)) {
  list(key = "fidelity", label = "Synthetic columns match the data", status = "info",
       detail = "No column could be compared with the data.")
} else {
  list(key = "fidelity", label = "Synthetic columns match the data",
       status = if (max(fid_d) <= 0.1) "pass" else "warn",
       detail = paste0("Distance from the training rows: ", paste(fid_t, collapse = "; "),
                       if (max(fid_d) <= 0.1) " — at most 0.10, which the Synthetic studio's scorecard rates as good column fidelity."
                       else " — above 0.10, so some columns' distributions differ visibly from the data; the scorecard shows which columns and pairs."))
}
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_publish(list(
  title = "Synthetic data — tabular GAN (WGAN-GP)",
  engine = cs_engine_info("torch", "nanoparquet", "codesplashr", "nanoparquet"),
  n = values$n_real, summary = summary,
  statistics = list(
    list(key = "n_rows", label = "Synthetic rows", value = values$n_rows, format = "integer"),
    list(key = "fidelity_ks_mean", label = "Mean KS distance", value = values$fidelity_ks_mean),
    list(key = "fidelity_tv_mean", label = "Mean TV distance", value = values$fidelity_tv_mean),
    list(key = "exact_matches", label = "Rows copied from the data", value = values$exact_matches, format = "integer")),
  tables = c(list(sm$table), extra_tables),
  values = values, charts = c(sm$charts, extra_charts), assumptions = assumptions, warnings = warnings,
  artifacts = list(list(key = "synthetic", path = path, format = "parquet", title = "Synthetic rows"),
                   list(key = "split", path = split, format = "parquet", title = "Training and holdout rows"),
                   list(key = "history", path = file.path(out, "history.parquet"), format = "parquet", title = "Training history")),
  model = list(kind = "generator", columns = I(COLUMNS), params = list(
    n_rows = NULL,
    hidden_layers = c(32, 32),
    noise_dim = 16,
    epochs = 40,
    batch_size = 100,
    n_critic = 5,
    gp_weight = 10,
    learning_rate = 0.0002,
    n_modes = 5,
    missing = "keep_rate",
    holdout = 0.2,
    dp_epsilon = NULL,
    dp_noise_multiplier = NULL,
    dp_max_grad_norm = 1,
    dp_delta = NULL,
    dp_sampling = "poisson"
  ))
))
Python

320 synthetic rows over 8 columns from 320 training rows with a Wasserstein GAN (gradient penalty). Numeric columns differ from the data by a mean Kolmogorov–Smirnov distance of 0.179 and categories by a mean total variation of 0.231.

Synthetic rows
320
Mean KS distance
0.1790
Mean TV distance
0.2315
Rows copied from the data
0

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

Assumptions

  • Enough rows for a neural generator — 293 complete training rows — neural generators have many weights to learn and can memorize small tables; compare with the copula or sequential trees.
  • Training stayed finite and the critic settled — Over the last 10% of epochs the Wasserstein estimate averaged 0.789 and the gradient penalty 0.0122.
  • No synthetic row copies a training row — 0 synthetic rows are identical to a training row; the scorecard's distance to closest record checks near-copies.
  • Synthetic columns match the data — Distance from the training rows: numeric columns 0.179 (mean Kolmogorov–Smirnov distance); categories 0.231 (mean total variation) — above 0.10, so some columns' distributions differ visibly from the data; the scorecard shows which columns and pairs.

Real vs synthetic, column by column

ColumnKindRealSyntheticDistanceMeasure
agenumeric43.14 ± 13.142.61 ± 16.20.1219Kolmogorov–Smirnov D
annual incomenumeric2.929e+04 ± 1.43e+042.835e+04 ± 1.96e+040.1386Kolmogorov–Smirnov D
tenure_monthsnumeric15 ± 10.718.16 ± 14.80.1750Kolmogorov–Smirnov D
plancategoricalplus 39.7%plus 25.6%0.1406total variation
regioncategoricalsouth 30.4%south 9.9%0.3382total variation
churnedbooleanfalse 76.9%false 55.3%0.2156total variation
signuptemporal2020-11-05 ± 621 days2020-04-08 ± 792 days0.3000Kolmogorov–Smirnov D
visitsnumeric3.394 ± 2.094.362 ± 3.120.1594Kolmogorov–Smirnov D

Modes per numeric column (mode-specific normalization)

ColumnMixture modes
age5
annual income5
tenure_months5
signup5
visits5
  • 80 of 400 rows (20%) were held out of training so privacy and utility can be checked against rows the generator never saw.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Synthetic data — tabular GAN (WGAN-GP)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method synth.gan 1.1.1 · spec b270e59f06622934
# Dataset: g1_customers (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 pandas as pd

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 neural  # twin of codesplashr::cs_synth_gan (clean-room WGAN-GP; no CTGAN/SDV code)
from codesplash.deep import dp as deep_dp  # differentially private training, DP-SGD (twin: cs_deep_dp_*)

# %% Data
COLUMNS = ["age", "annual income", "tenure_months", "plan", "region", "churned", "signup", "visits"]
KINDS = {
    "age": "numeric",
    "annual income": "numeric",
    "tenure_months": "numeric",
    "plan": "categorical",
    "region": "categorical",
    "churned": "boolean",
    "signup": "temporal",
    "visits": "numeric",
}
LEVELS = {
    "plan": ["basic", "plus", "premium"],
    "region": ["east", "north", "south", "west"],
}
SEED = 42
cols, n_input = sy.load("tests/parity/fixtures/g1_customers.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 = []
extra_charts = []
assumptions = []
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
n_complete = len(sy.complete_rows(train))
assumptions.append({
    "key": "enough_rows",
    "label": "Enough rows for a neural generator",
    "status": "pass" if n_complete >= 1000 else "warn",
    "detail": f"{n_complete:,} complete training rows"
              + ("." if n_complete >= 1000 else " — neural generators have many weights to learn and can memorize small tables; compare with the copula or sequential trees."),
})

# %% Generate
# WGAN-GP on rows encoded by mode-specific normalization (numbers → [α, mode one-hot], categories one-hot);
# the critic trains 5 steps per generator step with a gradient penalty of weight 10.
HIDDEN = [int(u) for u in [32, 32]]
# Differential privacy (DP-SGD on the critic, the only part that sees real rows): with an ε or a noise
# multiplier set, each real row's critic loss is clipped and noise is added; the guarantee goes to dp.json.
DP = deep_dp.settings({
    "dp_epsilon": None,
    "dp_noise_multiplier": None,
    "dp_max_grad_norm": 1,
    "dp_delta": None,
    "dp_sampling": "poisson",
})
if DP is not None:
    deep_dp.make_private(**DP, out_dir=out_dir("target/academy-parity/run-8142/synth.gan/customers_all/out-python"))
synth, facts, hist = neural.fit_gan(
    train, N_OUT, rng, HIDDEN,
    noise_dim=16,
    epochs=40,
    batch_size=100,
    n_critic=5,
    gp_weight=10,
    lr=0.0002,
    n_modes=5,
    seed=SEED,
)
history = pd.DataFrame(hist)
last = max(1, len(hist) // 10)  # the last 10% of epochs
fit_values["generator_steps"] = facts["generator_steps"]
fit_values["batch_size"] = facts["batch_size"]
fit_values["wasserstein"] = float(np.mean([h["wasserstein"] for h in hist[-last:]]))
fit_values["critic_loss"] = float(np.mean([h["critic"] for h in hist[-last:]]))
fit_values["penalty"] = float(np.mean([h["penalty"] for h in hist[-last:]]))
for c, k in zip(COLUMNS, facts["modes"]):
    if k is not None:
        fit_values[f"modes[{c}]"] = int(k)
model_note = " with a Wasserstein GAN (gradient penalty)"
ep = history["epoch"].tolist()
extra_charts.append(cs.chart("training", "training-components", "Critic and generator by epoch", {
    "x": cs.col("Epoch", ep * 3, "numeric"),
    "value": cs.col("Value", history["wasserstein"].tolist() + history["critic"].tolist() + history["generator"].tolist(), "numeric"),
    "component": cs.col("Series", ["Wasserstein estimate"] * len(ep) + ["critic loss"] * len(ep) + ["generator loss"] * len(ep), "categorical",
                        levels=["Wasserstein estimate", "critic loss", "generator loss"]),
}, note="The Wasserstein estimate is mean critic score on real rows minus fake rows; it should fall and level off as the generator improves."))
finite = bool(np.all(np.isfinite(history[["critic", "generator", "wasserstein"]].to_numpy())))
assumptions.append({
    "key": "training_stable",
    "label": "Training stayed finite and the critic settled",
    "status": "fail" if not finite else ("warn" if fit_values["penalty"] > 1.0 else "pass"),
    "detail": "A loss became infinite or undefined; lower the learning rate." if not finite else
              f"Over the last 10% of epochs the Wasserstein estimate averaged {fit_values['wasserstein']:.3g} and the gradient penalty {fit_values['penalty']:.3g}"
              + (" — the critic's gradients are far from norm 1, so its estimate is unreliable." if fit_values["penalty"] > 1.0 else "."),
})
mode_rows = [{"column": c, "modes": int(k)} for c, k in zip(COLUMNS, facts["modes"]) if k is not None]
if mode_rows:
    extra_tables.append({
        "key": "modes",
        "title": "Modes per numeric column (mode-specific normalization)",
        "columns": [{"key": "column", "label": "Column", "type": "string"}, {"key": "modes", "label": "Mixture modes", "type": "integer"}],
        "rows": mode_rows,
    })
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-8142/synth.gan/customers_all/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)
history.to_parquet(os.path.join(out, "history.parquet"), index=False)
values, table, charts = sy.summarize(train, synth, len(train_rows), n_input, len(holdout_rows), fit_values)
assumptions.append({
    "key": "no_copies",
    "label": "No synthetic row copies a training row",
    "status": "pass" if values["exact_matches"] == 0 else "warn",
    "detail": f"{values['exact_matches']:,} synthetic row{'s are' if values['exact_matches'] != 1 else ' is'} identical to a training row; the scorecard's distance to closest record checks near-copies.",
})
# Fidelity (Stage 12.10): judged on the mean column distances, the scorecard's column fidelity (good at ≥ 0.9 = 1 − 0.1).
fid_parts = []
if not np.isnan(values["fidelity_ks_mean"]):
    fid_parts.append((values["fidelity_ks_mean"], f"numeric columns {values['fidelity_ks_mean']:.3f} (mean Kolmogorov–Smirnov distance)"))
if not np.isnan(values["fidelity_tv_mean"]):
    fid_parts.append((values["fidelity_tv_mean"], f"categories {values['fidelity_tv_mean']:.3f} (mean total variation)"))
fid_worst = max((d for d, _ in fid_parts), default=None)
assumptions.append({
    "key": "fidelity",
    "label": "Synthetic columns match the data",
    "status": "info" if fid_worst is None else ("pass" if fid_worst <= 0.1 else "warn"),
    "detail": "No column could be compared with the data." if fid_worst is None else
              "Distance from the training rows: " + "; ".join(t for _, t in fid_parts)
              + (" — at most 0.10, which the Synthetic studio's scorecard rates as good column fidelity." if fid_worst <= 0.1 else
                 " — above 0.10, so some columns' distributions differ visibly from the data; the scorecard shows which columns and pairs."),
})
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."
cs.publish({
    "title": "Synthetic data — tabular GAN (WGAN-GP)",
    "engine": cs.engine_info("torch", "pyarrow", "codesplash", "numpy", "pyarrow"),
    "n": values["n_real"],
    "summary": summary,
    "statistics": [
        {"key": "n_rows", "label": "Synthetic rows", "value": values["n_rows"], "format": "integer"},
        {"key": "fidelity_ks_mean", "label": "Mean KS distance", "value": values.get("fidelity_ks_mean")},
        {"key": "fidelity_tv_mean", "label": "Mean TV distance", "value": values.get("fidelity_tv_mean")},
        {"key": "exact_matches", "label": "Rows copied from the data", "value": values["exact_matches"], "format": "integer"},
    ],
    "tables": [table, *extra_tables],
    "values": values,
    "charts": charts + extra_charts,
    "assumptions": assumptions,
    "warnings": warnings,
    "artifacts": [
        {"key": "synthetic", "path": path, "format": "parquet", "title": "Synthetic rows"},
        {"key": "split", "path": split, "format": "parquet", "title": "Training and holdout rows"},
        {"key": "history", "path": os.path.join(out, "history.parquet"), "format": "parquet", "title": "Training history"},
    ],
    "model": {"kind": "generator", "columns": COLUMNS, "params": {
        "n_rows": None,
        "hidden_layers": [32, 32],
        "noise_dim": 16,
        "epochs": 40,
        "batch_size": 100,
        "n_critic": 5,
        "gp_weight": 10,
        "learning_rate": 0.0002,
        "n_modes": 5,
        "missing": "keep_rate",
        "holdout": 0.2,
        "dp_epsilon": None,
        "dp_noise_multiplier": None,
        "dp_max_grad_norm": 1,
        "dp_delta": None,
        "dp_sampling": "poisson",
    }},
})

CodeSplash's GAN is a Wasserstein GAN with a gradient penalty (next lesson), which is more stable than the original game. On the customer table its mean Kolmogorov–Smirnov distance per column is 0.179, and the mean total-variation distance on categories 0.231. 0 generated rows copy a real row exactly.

06

Check every category

Explore
Synthetic data — tabular GAN (WGAN-GP)Recorded · Python and R agreeRecorded 2026-11-25 · 48 values compared
R

400 synthetic rows over 7 columns from 258 training rows with a Wasserstein GAN (gradient penalty). Numeric columns differ from the data by a mean Kolmogorov–Smirnov distance of 0.318 and categories by a mean total variation of 0.073.

Synthetic rows
400
Mean KS distance
0.3177
Mean TV distance
0.0734
Rows copied from the data
0

Plots

bill_len: real vs syntheticDoes the synthetic data reproduce the shape of a numeric column?
View data
DensitySourcebill_len
0.0043real32.558
0.0043real33.475
0.0213real34.392
0.0341real35.308
0.0469real36.225
0.0469real37.142
0.0639real38.058
0.0639real38.975
0.0511real39.892
0.0767real40.808
0.0426real41.725
0.0384real42.642
0.0298real43.558
0.0256real44.475
0.0980real45.392
0.0767real46.308
0.0554real47.225
0.0384real48.142
0.0597real49.058
0.0639real49.975
0.0682real50.892
0.0384real51.808
0.0128real52.725
0.0085real53.642
0.0085real54.558
0.0085real55.475
0real56.392
0real57.308
0real58.225
0.0043real59.142
0.3327synthetic32.558
0.0355synthetic33.475
0.0518synthetic34.392
0.0436synthetic35.308
0.1145synthetic36.225
0.0736synthetic37.142
0.0545synthetic38.058
0.0409synthetic38.975
0.0464synthetic39.892
0.0491synthetic40.808
0.0382synthetic41.725
0.0300synthetic42.642
0.0191synthetic43.558
0.0109synthetic44.475
0.0273synthetic45.392
0.0082synthetic46.308
0.0136synthetic47.225
0.0136synthetic48.142
0.0109synthetic49.058
0.0245synthetic49.975
0.0055synthetic50.892
0.0082synthetic51.808
0.0082synthetic52.725
0.0109synthetic53.642
0.0055synthetic54.558
0.0055synthetic55.475
0.0027synthetic56.392
0synthetic57.308
0.0055synthetic58.225
0synthetic59.142
bill_dep: real vs syntheticDoes the synthetic data reproduce the shape of a numeric column?
View data
DensitySourcebill_dep
0.0424real13.338
0.0847real13.615
0.1271real13.892
0.1412real14.168
0.1271real14.445
0.1271real14.722
0.1412real14.998
0.0988real15.275
0.0565real15.552
0.1553real15.828
0.0988real16.105
0.1271real16.382
0.0847real16.658
0.2118real16.935
0.2400real17.212
0.1412real17.488
0.2118real17.765
0.1412real18.042
0.1271real18.318
0.2683real18.595
0.2824real18.872
0.0847real19.148
0.1130real19.425
0.0988real19.702
0.1130real19.978
0.0565real20.255
0.0141real20.532
0.0282real20.808
0.0565real21.085
0.0141real21.362
0.2440synthetic13.338
0.1355synthetic13.615
0.0723synthetic13.892
0.0994synthetic14.168
0.1355synthetic14.445
0.1265synthetic14.722
0.1988synthetic14.998
0.1536synthetic15.275
0.2349synthetic15.552
0.1988synthetic15.828
0.1988synthetic16.105
0.2078synthetic16.382
0.0723synthetic16.658
0.0181synthetic16.935
0.0452synthetic17.212
0.0452synthetic17.488
0.0181synthetic17.765
0.0542synthetic18.042
0.0452synthetic18.318
0.0452synthetic18.595
0.0633synthetic18.872
0.0633synthetic19.148
0.0542synthetic19.425
0.1265synthetic19.702
0.0723synthetic19.978
0.0361synthetic20.255
0.0633synthetic20.532
0.0723synthetic20.808
0.0452synthetic21.085
0.6687synthetic21.362
flipper_len: real vs syntheticDoes the synthetic data reproduce the shape of a numeric column?
View data
DensitySourceflipper_len
0.0020real172.98
0.0020real174.95
0.0020real176.92
0.0060real178.88
0.0159real180.85
0.0099real182.82
0.0238real184.78
0.0258real186.75
0.0179real188.72
0.0616real190.68
0.0218real192.65
0.0358real194.62
0.0278real196.58
0.0258real198.55
0.0139real200.52
0.0119real202.48
0.0060real204.45
0.0060real206.42
0.0179real208.38
0.0218real210.35
0.0218real212.32
0.0278real214.28
0.0199real216.25
0.0179real218.22
0.0199real220.18
0.0079real222.15
0.0119real224.12
0.0020real226.08
0.0119real228.05
0.0119real230.02
0.1081synthetic172.98
0.0229synthetic174.95
0.0153synthetic176.92
0.0102synthetic178.88
0.0165synthetic180.85
0.0140synthetic182.82
0.0153synthetic184.78
0.0432synthetic186.75
0.0381synthetic188.72
0.0216synthetic190.68
0.0178synthetic192.65
0.0165synthetic194.62
0.0229synthetic196.58
0.0127synthetic198.55
0.0203synthetic200.52
0.0140synthetic202.48
0.0153synthetic204.45
0.0076synthetic206.42
0.0089synthetic208.38
0.0089synthetic210.35
0.0064synthetic212.32
0.0038synthetic214.28
0.0038synthetic216.25
0.0076synthetic218.22
0.0038synthetic220.18
0.0038synthetic222.15
0.0013synthetic224.12
0.0102synthetic226.08
0.0013synthetic228.05
0.0165synthetic230.02
body_mass: real vs syntheticDoes the synthetic data reproduce the shape of a numeric column?
View data
DensitySourcebody_mass
3.498e-5real2755.83
0.0001real2867.50
6.996e-5real2979.17
0.0002real3090.83
0.0005real3202.50
0.0003real3314.17
0.0006real3425.83
0.0005real3537.50
0.0007real3649.17
0.0005real3760.83
0.0004real3872.50
0.0005real3984.17
0.0005real4095.83
0.0003real4207.50
0.0003real4319.17
0.0004real4430.83
0.0001real4542.50
0.0006real4654.17
0.0003real4765.83
0.0003real4877.50
0.0002real4989.17
0.0003real5100.83
0.0001real5212.50
0.0002real5324.17
0.0001real5435.83
0.0005real5547.50
0.0002real5659.17
6.996e-5real5770.83
3.498e-5real5882.50
0.0001real5994.17
0.0010synthetic2755.83
0.0002synthetic2867.50
0.0003synthetic2979.17
0.0003synthetic3090.83
8.955e-5synthetic3202.50
0.0003synthetic3314.17
8.955e-5synthetic3425.83
0.0002synthetic3537.50
0.0002synthetic3649.17
0.0002synthetic3760.83
8.955e-5synthetic3872.50
8.955e-5synthetic3984.17
0.0001synthetic4095.83
0.0003synthetic4207.50
0.0001synthetic4319.17
0.0002synthetic4430.83
0.0001synthetic4542.50
0.0006synthetic4654.17
0.0005synthetic4765.83
0.0006synthetic4877.50
0.0004synthetic4989.17
0.0002synthetic5100.83
0.0002synthetic5212.50
0.0003synthetic5324.17
0.0002synthetic5435.83
0.0003synthetic5547.50
0.0003synthetic5659.17
0.0002synthetic5770.83
0.0002synthetic5882.50
0.0010synthetic5994.17
species: real vs syntheticDoes the synthetic data keep the category proportions of the real data?
View data
speciesShareSource
Adelie0.4419real
Chinstrap0.1899real
Gentoo0.3682real
Adelie0.4975synthetic
Chinstrap0.1450synthetic
Gentoo0.3575synthetic
island: real vs syntheticDoes the synthetic data keep the category proportions of the real data?
View data
islandShareSource
Biscoe0.4806real
Dream0.3643real
Torgersen0.1550real
Biscoe0.3800synthetic
Dream0.3775synthetic
Torgersen0.2425synthetic
sex: real vs syntheticDoes the synthetic data keep the category proportions of the real data?
View data
sexShareSource
female0.4940real
male0.5060real
female0.4300synthetic
male0.5700synthetic
Correlation difference (real − synthetic)What do the values of a square or rectangular result matrix look like at a glance?
View data
ColumnColumnDifference
bill_lenbill_len0
bill_depbill_len−0.3273
flipper_lenbill_len0.5662
body_massbill_len0.8578
bill_lenbill_dep−0.3273
bill_depbill_dep0
flipper_lenbill_dep−0.7312
body_massbill_dep−0.2861
bill_lenflipper_len0.5662
bill_depflipper_len−0.7312
flipper_lenflipper_len0
body_massflipper_len0.9032
bill_lenbody_mass0.8578
bill_depbody_mass−0.2861
flipper_lenbody_mass0.9032
body_massbody_mass0
Critic and generator by epochIs the network still learning, and which part of its loss moves?

The Wasserstein estimate is mean critic score on real rows minus fake rows; it should fall and level off as the generator improves.

View data
SeriesValueEpoch
Wasserstein estimate0.18471
Wasserstein estimate0.22132
Wasserstein estimate0.26213
Wasserstein estimate0.26944
Wasserstein estimate0.28925
Wasserstein estimate0.32096
Wasserstein estimate0.36217
Wasserstein estimate0.37848
Wasserstein estimate0.45999
Wasserstein estimate0.425310
Wasserstein estimate0.455411
Wasserstein estimate0.506012
Wasserstein estimate0.498713
Wasserstein estimate0.551114
Wasserstein estimate0.493315
Wasserstein estimate0.598216
Wasserstein estimate0.613017
Wasserstein estimate0.617918
Wasserstein estimate0.663719
Wasserstein estimate0.670520
Wasserstein estimate0.674621
Wasserstein estimate0.719622
Wasserstein estimate0.700023
Wasserstein estimate0.754924
Wasserstein estimate0.769125
Wasserstein estimate0.743726
Wasserstein estimate0.771327
Wasserstein estimate0.767928
Wasserstein estimate0.829329
Wasserstein estimate0.837430
critic loss−0.07261
critic loss−0.11062
critic loss−0.15993
critic loss−0.18654
critic loss−0.20505
critic loss−0.22946
critic loss−0.27847
critic loss−0.28648
critic loss−0.37809
critic loss−0.340110
critic loss−0.368011
critic loss−0.421912
critic loss−0.413713
critic loss−0.464814
critic loss−0.406315
critic loss−0.519216
critic loss−0.528717
critic loss−0.538218
critic loss−0.587019
critic loss−0.587620
critic loss−0.601121
critic loss−0.641822
critic loss−0.621523
critic loss−0.673624
critic loss−0.689625
critic loss−0.663826
critic loss−0.693327
critic loss−0.695828
critic loss−0.754029
critic loss−0.759430

First 60 of 90 rows.

Assumptions

  • Enough rows for a neural generator — 251 complete training rows — neural generators have many weights to learn and can memorize small tables; compare with the copula or sequential trees.
  • Training stayed finite and the critic settled — Over the last 10% of epochs the Wasserstein estimate averaged 0.812 and the gradient penalty 0.00751.
  • No synthetic row copies a training row — 0 synthetic rows are identical to a training row; the scorecard's distance to closest record checks near-copies.
  • Synthetic columns match the data — Distance from the training rows: numeric columns 0.318 (mean Kolmogorov–Smirnov distance); categories 0.073 (mean total variation) — above 0.10, so some columns' distributions differ visibly from the data; the scorecard shows which columns and pairs.

Real vs synthetic, column by column

ColumnKindRealSyntheticDistanceMeasure
speciescategoricalAdelie 44.2%Adelie 49.8%0.0556total variation
islandcategoricalBiscoe 48.1%Biscoe 38.0%0.1006total variation
bill_lennumeric43.96 ± 5.537.82 ± 5.990.4606Kolmogorov–Smirnov D
bill_depnumeric17.14 ± 1.9817.25 ± 2.850.2062Kolmogorov–Smirnov D
flipper_lennumeric201.3 ± 14.2190.5 ± 16.20.3505Kolmogorov–Smirnov D
body_massnumeric4219 ± 7914503 ± 1.1e+030.2533Kolmogorov–Smirnov D
sexcategoricalmale 50.6%male 57.0%0.0640total variation

Modes per numeric column (mode-specific normalization)

ColumnMixture modes
bill_len3
bill_dep3
flipper_len3
body_mass3
  • 86 of 344 rows (25%) were held out of training so privacy and utility can be checked against rows the generator never saw.
The exact R script · R R version 4.5.1 (2025-06-13)
# Synthetic data — tabular GAN (WGAN-GP)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method synth.gan 1.1.1 · spec 2a528df1925e5397
# Dataset: ml_penguins (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("species", "island", "bill_len", "bill_dep", "flipper_len", "body_mass", "sex")
KINDS <- list(
  species = "categorical",
  island = "categorical",
  bill_len = "numeric",
  bill_dep = "numeric",
  flipper_len = "numeric",
  body_mass = "numeric",
  sex = "categorical"
)
LEVELS <- list(
  species = c("Adelie", "Chinstrap", "Gentoo"),
  island = c("Biscoe", "Dream", "Torgersen"),
  sex = c("female", "male")
)
SEED <- 42
loaded <- cs_synth_load("tests/parity/fixtures/ml_penguins.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.25, rng)
train_rows <- sp$train; holdout_rows <- sp$holdout
train <- lapply(cols, cs_synth_take, rows = train_rows)
N_OUT <- 400L
warnings <- list()
fit_values <- list()
extra_tables <- list()
extra_charts <- list()
assumptions <- 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
n_complete <- length(cs_synth_complete(train))
assumptions[[1]] <- list(
  key = "enough_rows", label = "Enough rows for a neural generator",
  status = if (n_complete >= 1000) "pass" else "warn",
  detail = paste0(sprintf("%s complete training rows", format(n_complete, big.mark = ",")),
                  if (n_complete >= 1000) "." else " — neural generators have many weights to learn and can memorize small tables; compare with the copula or sequential trees.")
)

# %% Generate
# WGAN-GP on rows encoded by mode-specific normalization (numbers -> [alpha, mode one-hot], categories one-hot);
# the critic trains 3 steps per generator step with a gradient penalty of weight 10.
# Twin of codesplash.synth.neural.fit_gan (clean-room; no CTGAN/SDV code).
HIDDEN <- as.integer(unlist(c(32)))
# Differential privacy (DP-SGD on the critic, the only part that sees real rows): with an epsilon or a noise
# multiplier set, each real row's critic loss is clipped and noise is added; the guarantee goes to dp.json.
DP <- cs_deep_dp_settings(list(
  dp_epsilon = NULL,
  dp_noise_multiplier = NULL,
  dp_max_grad_norm = 1,
  dp_delta = NULL,
  dp_sampling = "poisson"
))
if (!is.null(DP)) do.call(cs_deep_dp_make_private, c(DP, list(out_dir = cs_ml_out_dir("target/academy-parity/run-8142/synth.gan/penguins_no_missing/out-r"))))
fit <- cs_synth_gan(
  train, N_OUT, rng, HIDDEN,
  noise_dim = as.integer(32),
  epochs = as.integer(30),
  batch_size = 64,
  n_critic = as.integer(3),
  gp_weight = 10,
  lr = 0.0002,
  n_modes = as.integer(3),
  seed = SEED
)
synth <- fit$cols
hist <- fit$history
history <- data.frame(
  epoch = vapply(hist, function(h) as.numeric(h$epoch), numeric(1)),
  critic = vapply(hist, function(h) h$critic, numeric(1)),
  wasserstein = vapply(hist, function(h) h$wasserstein, numeric(1)),
  penalty = vapply(hist, function(h) h$penalty, numeric(1)),
  generator = vapply(hist, function(h) h$generator, numeric(1))
)
last <- max(1L, nrow(history) %/% 10L)  # the last 10% of epochs
tail_rows <- (nrow(history) - last + 1L):nrow(history)
fit_values$generator_steps <- fit$facts$generator_steps
fit_values$batch_size <- fit$facts$batch_size
fit_values$wasserstein <- mean(history$wasserstein[tail_rows])
fit_values$critic_loss <- mean(history$critic[tail_rows])
fit_values$penalty <- mean(history$penalty[tail_rows])
for (j in seq_along(COLUMNS)) {
  k <- fit$facts$modes[[j]]
  if (!is.null(k)) fit_values[[sprintf("modes[%s]", COLUMNS[j])]] <- as.integer(k)
}
model_note <- " with a Wasserstein GAN (gradient penalty)"
ne <- nrow(history)
extra_charts[[length(extra_charts) + 1L]] <- cs_chart("training", "training-components", "Critic and generator by epoch", list(
  x = cs_col("Epoch", rep(history$epoch, 3), "numeric"),
  value = cs_col("Value", c(history$wasserstein, history$critic, history$generator), "numeric"),
  component = cs_col("Series", rep(c("Wasserstein estimate", "critic loss", "generator loss"), each = ne), "categorical",
                     levels = c("Wasserstein estimate", "critic loss", "generator loss"))
), note = "The Wasserstein estimate is mean critic score on real rows minus fake rows; it should fall and level off as the generator improves.")
finite <- all(is.finite(c(history$critic, history$generator, history$wasserstein)))
assumptions[[length(assumptions) + 1L]] <- list(
  key = "training_stable", label = "Training stayed finite and the critic settled",
  status = if (!finite) "fail" else if (fit_values$penalty > 1) "warn" else "pass",
  detail = if (!finite) "A loss became infinite or undefined; lower the learning rate." else
    paste0(sprintf("Over the last 10%% of epochs the Wasserstein estimate averaged %s and the gradient penalty %s",
                   format(signif(fit_values$wasserstein, 3)), format(signif(fit_values$penalty, 3))),
           if (fit_values$penalty > 1) " — the critic's gradients are far from norm 1, so its estimate is unreliable." else ".")
)
mode_rows <- list()
for (j in seq_along(COLUMNS)) {
  k <- fit$facts$modes[[j]]
  if (!is.null(k)) mode_rows[[length(mode_rows) + 1L]] <- list(column = COLUMNS[j], modes = as.integer(k))
}
if (length(mode_rows)) {
  extra_tables[[length(extra_tables) + 1L]] <- list(
    key = "modes", title = "Modes per numeric column (mode-specific normalization)",
    columns = list(list(key = "column", label = "Column", type = "string"), list(key = "modes", label = "Mixture modes", type = "integer")),
    rows = mode_rows)
}
synth <- cs_synth_add_missing(synth, train, rng, "none")  # each column's missing share, at random

# %% Write and compare
out <- cs_ml_out_dir("target/academy-parity/run-8142/synth.gan/penguins_no_missing/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)
nanoparquet::write_parquet(history, file.path(out, "history.parquet"))
sm <- cs_synth_summarize(train, synth, length(train_rows), n_input, length(holdout_rows), fit_values)
values <- sm$values
assumptions[[length(assumptions) + 1L]] <- list(
  key = "no_copies", label = "No synthetic row copies a training row",
  status = if (values$exact_matches == 0) "pass" else "warn",
  detail = sprintf("%s synthetic row%s identical to a training row; the scorecard's distance to closest record checks near-copies.",
                   format(values$exact_matches, big.mark = ","), if (values$exact_matches != 1) "s are" else " is")
)
# Fidelity (Stage 12.10): judged on the mean column distances, the scorecard's column fidelity (good at >= 0.9 = 1 - 0.1).
fid_d <- numeric(); fid_t <- character()
if (!is.nan(values$fidelity_ks_mean)) {
  fid_d <- c(fid_d, values$fidelity_ks_mean)
  fid_t <- c(fid_t, sprintf("numeric columns %.3f (mean Kolmogorov–Smirnov distance)", values$fidelity_ks_mean))
}
if (!is.nan(values$fidelity_tv_mean)) {
  fid_d <- c(fid_d, values$fidelity_tv_mean)
  fid_t <- c(fid_t, sprintf("categories %.3f (mean total variation)", values$fidelity_tv_mean))
}
assumptions[[length(assumptions) + 1L]] <- if (!length(fid_d)) {
  list(key = "fidelity", label = "Synthetic columns match the data", status = "info",
       detail = "No column could be compared with the data.")
} else {
  list(key = "fidelity", label = "Synthetic columns match the data",
       status = if (max(fid_d) <= 0.1) "pass" else "warn",
       detail = paste0("Distance from the training rows: ", paste(fid_t, collapse = "; "),
                       if (max(fid_d) <= 0.1) " — at most 0.10, which the Synthetic studio's scorecard rates as good column fidelity."
                       else " — above 0.10, so some columns' distributions differ visibly from the data; the scorecard shows which columns and pairs."))
}
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_publish(list(
  title = "Synthetic data — tabular GAN (WGAN-GP)",
  engine = cs_engine_info("torch", "nanoparquet", "codesplashr", "nanoparquet"),
  n = values$n_real, summary = summary,
  statistics = list(
    list(key = "n_rows", label = "Synthetic rows", value = values$n_rows, format = "integer"),
    list(key = "fidelity_ks_mean", label = "Mean KS distance", value = values$fidelity_ks_mean),
    list(key = "fidelity_tv_mean", label = "Mean TV distance", value = values$fidelity_tv_mean),
    list(key = "exact_matches", label = "Rows copied from the data", value = values$exact_matches, format = "integer")),
  tables = c(list(sm$table), extra_tables),
  values = values, charts = c(sm$charts, extra_charts), assumptions = assumptions, warnings = warnings,
  artifacts = list(list(key = "synthetic", path = path, format = "parquet", title = "Synthetic rows"),
                   list(key = "split", path = split, format = "parquet", title = "Training and holdout rows"),
                   list(key = "history", path = file.path(out, "history.parquet"), format = "parquet", title = "Training history")),
  model = list(kind = "generator", columns = I(COLUMNS), params = list(
    n_rows = 400,
    hidden_layers = c(32),
    noise_dim = 32,
    epochs = 30,
    batch_size = 64,
    n_critic = 3,
    gp_weight = 10,
    learning_rate = 0.0002,
    n_modes = 3,
    missing = "none",
    holdout = 0.25,
    dp_epsilon = NULL,
    dp_noise_multiplier = NULL,
    dp_max_grad_norm = 1,
    dp_delta = NULL,
    dp_sampling = "poisson"
  ))
))
Python

400 synthetic rows over 7 columns from 258 training rows with a Wasserstein GAN (gradient penalty). Numeric columns differ from the data by a mean Kolmogorov–Smirnov distance of 0.318 and categories by a mean total variation of 0.073.

Synthetic rows
400
Mean KS distance
0.3177
Mean TV distance
0.0734
Rows copied from the data
0

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

Assumptions

  • Enough rows for a neural generator — 251 complete training rows — neural generators have many weights to learn and can memorize small tables; compare with the copula or sequential trees.
  • Training stayed finite and the critic settled — Over the last 10% of epochs the Wasserstein estimate averaged 0.812 and the gradient penalty 0.00751.
  • No synthetic row copies a training row — 0 synthetic rows are identical to a training row; the scorecard's distance to closest record checks near-copies.
  • Synthetic columns match the data — Distance from the training rows: numeric columns 0.318 (mean Kolmogorov–Smirnov distance); categories 0.073 (mean total variation) — above 0.10, so some columns' distributions differ visibly from the data; the scorecard shows which columns and pairs.

Real vs synthetic, column by column

ColumnKindRealSyntheticDistanceMeasure
speciescategoricalAdelie 44.2%Adelie 49.8%0.0556total variation
islandcategoricalBiscoe 48.1%Biscoe 38.0%0.1006total variation
bill_lennumeric43.96 ± 5.537.82 ± 5.990.4606Kolmogorov–Smirnov D
bill_depnumeric17.14 ± 1.9817.25 ± 2.850.2063Kolmogorov–Smirnov D
flipper_lennumeric201.3 ± 14.2190.5 ± 16.20.3505Kolmogorov–Smirnov D
body_massnumeric4219 ± 7914503 ± 1.1e+030.2533Kolmogorov–Smirnov D
sexcategoricalmale 50.6%male 57.0%0.0640total variation

Modes per numeric column (mode-specific normalization)

ColumnMixture modes
bill_len3
bill_dep3
flipper_len3
body_mass3
  • 86 of 344 rows (25%) were held out of training so privacy and utility can be checked against rows the generator never saw.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Synthetic data — tabular GAN (WGAN-GP)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method synth.gan 1.1.1 · spec 2a528df1925e5397
# Dataset: ml_penguins (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 pandas as pd

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 neural  # twin of codesplashr::cs_synth_gan (clean-room WGAN-GP; no CTGAN/SDV code)
from codesplash.deep import dp as deep_dp  # differentially private training, DP-SGD (twin: cs_deep_dp_*)

# %% Data
COLUMNS = ["species", "island", "bill_len", "bill_dep", "flipper_len", "body_mass", "sex"]
KINDS = {
    "species": "categorical",
    "island": "categorical",
    "bill_len": "numeric",
    "bill_dep": "numeric",
    "flipper_len": "numeric",
    "body_mass": "numeric",
    "sex": "categorical",
}
LEVELS = {
    "species": ["Adelie", "Chinstrap", "Gentoo"],
    "island": ["Biscoe", "Dream", "Torgersen"],
    "sex": ["female", "male"],
}
SEED = 42
cols, n_input = sy.load("tests/parity/fixtures/ml_penguins.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.25, rng)
train = [c.take(train_rows) for c in cols]
N_OUT = 400 or len(train_rows)
warnings = []
fit_values = {}
extra_tables = []
extra_charts = []
assumptions = []
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
n_complete = len(sy.complete_rows(train))
assumptions.append({
    "key": "enough_rows",
    "label": "Enough rows for a neural generator",
    "status": "pass" if n_complete >= 1000 else "warn",
    "detail": f"{n_complete:,} complete training rows"
              + ("." if n_complete >= 1000 else " — neural generators have many weights to learn and can memorize small tables; compare with the copula or sequential trees."),
})

# %% Generate
# WGAN-GP on rows encoded by mode-specific normalization (numbers → [α, mode one-hot], categories one-hot);
# the critic trains 3 steps per generator step with a gradient penalty of weight 10.
HIDDEN = [int(u) for u in [32]]
# Differential privacy (DP-SGD on the critic, the only part that sees real rows): with an ε or a noise
# multiplier set, each real row's critic loss is clipped and noise is added; the guarantee goes to dp.json.
DP = deep_dp.settings({
    "dp_epsilon": None,
    "dp_noise_multiplier": None,
    "dp_max_grad_norm": 1,
    "dp_delta": None,
    "dp_sampling": "poisson",
})
if DP is not None:
    deep_dp.make_private(**DP, out_dir=out_dir("target/academy-parity/run-8142/synth.gan/penguins_no_missing/out-python"))
synth, facts, hist = neural.fit_gan(
    train, N_OUT, rng, HIDDEN,
    noise_dim=32,
    epochs=30,
    batch_size=64,
    n_critic=3,
    gp_weight=10,
    lr=0.0002,
    n_modes=3,
    seed=SEED,
)
history = pd.DataFrame(hist)
last = max(1, len(hist) // 10)  # the last 10% of epochs
fit_values["generator_steps"] = facts["generator_steps"]
fit_values["batch_size"] = facts["batch_size"]
fit_values["wasserstein"] = float(np.mean([h["wasserstein"] for h in hist[-last:]]))
fit_values["critic_loss"] = float(np.mean([h["critic"] for h in hist[-last:]]))
fit_values["penalty"] = float(np.mean([h["penalty"] for h in hist[-last:]]))
for c, k in zip(COLUMNS, facts["modes"]):
    if k is not None:
        fit_values[f"modes[{c}]"] = int(k)
model_note = " with a Wasserstein GAN (gradient penalty)"
ep = history["epoch"].tolist()
extra_charts.append(cs.chart("training", "training-components", "Critic and generator by epoch", {
    "x": cs.col("Epoch", ep * 3, "numeric"),
    "value": cs.col("Value", history["wasserstein"].tolist() + history["critic"].tolist() + history["generator"].tolist(), "numeric"),
    "component": cs.col("Series", ["Wasserstein estimate"] * len(ep) + ["critic loss"] * len(ep) + ["generator loss"] * len(ep), "categorical",
                        levels=["Wasserstein estimate", "critic loss", "generator loss"]),
}, note="The Wasserstein estimate is mean critic score on real rows minus fake rows; it should fall and level off as the generator improves."))
finite = bool(np.all(np.isfinite(history[["critic", "generator", "wasserstein"]].to_numpy())))
assumptions.append({
    "key": "training_stable",
    "label": "Training stayed finite and the critic settled",
    "status": "fail" if not finite else ("warn" if fit_values["penalty"] > 1.0 else "pass"),
    "detail": "A loss became infinite or undefined; lower the learning rate." if not finite else
              f"Over the last 10% of epochs the Wasserstein estimate averaged {fit_values['wasserstein']:.3g} and the gradient penalty {fit_values['penalty']:.3g}"
              + (" — the critic's gradients are far from norm 1, so its estimate is unreliable." if fit_values["penalty"] > 1.0 else "."),
})
mode_rows = [{"column": c, "modes": int(k)} for c, k in zip(COLUMNS, facts["modes"]) if k is not None]
if mode_rows:
    extra_tables.append({
        "key": "modes",
        "title": "Modes per numeric column (mode-specific normalization)",
        "columns": [{"key": "column", "label": "Column", "type": "string"}, {"key": "modes", "label": "Mixture modes", "type": "integer"}],
        "rows": mode_rows,
    })
sy.add_missing(synth, train, rng, "none")  # each column's missing share, at random

# %% Write and compare
out = out_dir("target/academy-parity/run-8142/synth.gan/penguins_no_missing/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)
history.to_parquet(os.path.join(out, "history.parquet"), index=False)
values, table, charts = sy.summarize(train, synth, len(train_rows), n_input, len(holdout_rows), fit_values)
assumptions.append({
    "key": "no_copies",
    "label": "No synthetic row copies a training row",
    "status": "pass" if values["exact_matches"] == 0 else "warn",
    "detail": f"{values['exact_matches']:,} synthetic row{'s are' if values['exact_matches'] != 1 else ' is'} identical to a training row; the scorecard's distance to closest record checks near-copies.",
})
# Fidelity (Stage 12.10): judged on the mean column distances, the scorecard's column fidelity (good at ≥ 0.9 = 1 − 0.1).
fid_parts = []
if not np.isnan(values["fidelity_ks_mean"]):
    fid_parts.append((values["fidelity_ks_mean"], f"numeric columns {values['fidelity_ks_mean']:.3f} (mean Kolmogorov–Smirnov distance)"))
if not np.isnan(values["fidelity_tv_mean"]):
    fid_parts.append((values["fidelity_tv_mean"], f"categories {values['fidelity_tv_mean']:.3f} (mean total variation)"))
fid_worst = max((d for d, _ in fid_parts), default=None)
assumptions.append({
    "key": "fidelity",
    "label": "Synthetic columns match the data",
    "status": "info" if fid_worst is None else ("pass" if fid_worst <= 0.1 else "warn"),
    "detail": "No column could be compared with the data." if fid_worst is None else
              "Distance from the training rows: " + "; ".join(t for _, t in fid_parts)
              + (" — at most 0.10, which the Synthetic studio's scorecard rates as good column fidelity." if fid_worst <= 0.1 else
                 " — above 0.10, so some columns' distributions differ visibly from the data; the scorecard shows which columns and pairs."),
})
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."
cs.publish({
    "title": "Synthetic data — tabular GAN (WGAN-GP)",
    "engine": cs.engine_info("torch", "pyarrow", "codesplash", "numpy", "pyarrow"),
    "n": values["n_real"],
    "summary": summary,
    "statistics": [
        {"key": "n_rows", "label": "Synthetic rows", "value": values["n_rows"], "format": "integer"},
        {"key": "fidelity_ks_mean", "label": "Mean KS distance", "value": values.get("fidelity_ks_mean")},
        {"key": "fidelity_tv_mean", "label": "Mean TV distance", "value": values.get("fidelity_tv_mean")},
        {"key": "exact_matches", "label": "Rows copied from the data", "value": values["exact_matches"], "format": "integer"},
    ],
    "tables": [table, *extra_tables],
    "values": values,
    "charts": charts + extra_charts,
    "assumptions": assumptions,
    "warnings": warnings,
    "artifacts": [
        {"key": "synthetic", "path": path, "format": "parquet", "title": "Synthetic rows"},
        {"key": "split", "path": split, "format": "parquet", "title": "Training and holdout rows"},
        {"key": "history", "path": os.path.join(out, "history.parquet"), "format": "parquet", "title": "Training history"},
    ],
    "model": {"kind": "generator", "columns": COLUMNS, "params": {
        "n_rows": 400,
        "hidden_layers": [32],
        "noise_dim": 32,
        "epochs": 30,
        "batch_size": 64,
        "n_critic": 3,
        "gp_weight": 10,
        "learning_rate": 0.0002,
        "n_modes": 3,
        "missing": "none",
        "holdout": 0.25,
        "dp_epsilon": None,
        "dp_noise_multiplier": None,
        "dp_max_grad_norm": 1,
        "dp_delta": None,
        "dp_sampling": "poisson",
    }},
})

On penguins, compare each category's share in the generated rows with the real shares. A category that shrinks or vanishes is the tabular face of mode collapse. Here the mean total-variation distance across the categorical columns is 0.073; open the per-column table to see which category drifts most.

07

DCGAN and checkerboards

Read

DCGAN set the recipe for image GANs: strided convolutions instead of pooling, batch normalization, ReLU in the generator and leaky ReLU in the discriminator. Its generator upsamples with transposed convolutionsTransposed convolutionAn upsampling layer that spreads each input value through a kernel; with stride not dividing kernel size, overlaps make checkerboards., which spread each input value through a kernel.

When the stride doesn't divide the kernel size, some outputs get one kernel copy and others get two. In the reference's 1-D example, a 3-wide kernel at stride 2 gives 0.6 where two copies overlap, beside 0.5 where only one lands. In 2-D that uneven overlap shows as a checkerboard.

Reference · DNN044 · Explained hereDeep convolutional GAN (DCGAN)DCGAN adapts convolutional and transposed-convolutional architectures to adversarial image generation, with design constraints that helped stabilize early GAN training.
08

What runs here

Read
09

Check: GANs

Checkpoint

Check yourself

Why do GANs usually train the generator to maximize log D(G(z)) instead of minimizing log(1 − D(G(z)))?

Show the answer

Answer: a

With D(G(z)) near 0, log(1 − D) is flat. log D is steep there, so the generator learns fastest when it is worst.

Check yourself

How can you check whether a GAN memorized its training rows?

Show the answer

Answer: b

A GAN defines no likelihood, so there is nothing to compute on held-out rows. Memorizing shows up in the samples.

Check yourself

A GAN's generated penguins look realistic one by one, but one species almost never appears. What is this?

Show the answer

Answer: a

The generator found it could fool the discriminator without producing every kind of row. Compare category shares and coverage, not individual samples.

Check yourself

Where do DCGAN's checkerboard artifacts come from?

Show the answer

Answer: b

Uneven overlap makes some pixels sums of two kernel copies and others of one. Resize-then-convolve upsampling avoids it.

Check yourself

Which belongs to the DCGAN recipe?

Show the answer

Answer: a

DCGAN's guidelines were architectural: all-convolutional networks with strides, batch normalization, ReLU in the generator and leaky ReLU in the discriminator.

10

Recap

Recap
  • A GAN pits a generator against a discriminator; the non-saturating loss keeps the generator's gradient alive.
  • Losses track the game, not sample quality, and a GAN gives no likelihood.
  • Check samples for coverage and copying; mode collapse hides behind realistic individual rows.
  • DCGAN's transposed convolutions can leave checkerboards. CodeSplash runs a tabular WGAN-GP.

Concepts in this lesson