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.
What runs in CodeSplash
- DNN043Generative adversarial network (GAN) Runs in CodeSplash (Experimental)
- DNN044Deep convolutional GAN (DCGAN) Explained here
- Synthetic data — tabular GAN (WGAN-GP) Experimental
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
Two networks with opposite goals
ReadA generative adversarial networkGenerative adversarial networkA generator learns to fool a discriminator that is trained to tell its output from real data. has a generator that turns noise into a row, and a discriminator that outputs the probability a row is real. They play a game:
wants high scores on real rows and low ones on fakes. wants its fakes to score high. If were optimal at every step, would be minimizing a Jensen–Shannon divergence between real and generated rows.
The non-saturating loss
ReadEarly in training the discriminator wins easily: is near 0, where 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 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.
The losses aren't a quality score
PredictPredict first
Halfway through training, the generator's loss stops falling and starts to wander. What does that tell you about sample quality?
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.
Mode collapse
ReadThe 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?
View
Loss (two players)
Discriminator penalty
Updates
γ for R1, λ for WGAN-GP.
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).
Modes at ±this value (mode collapse view).
- Data (two modes)
- Generator N(2.50, 0.50²)
Commit your prediction above to see the result
Make your prediction to see the result.
A GAN in the Synthetic studio
Explore320 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
View data
| Density | Source | age |
|---|---|---|
| 0.0230 | real | 18.950 |
| 0.0016 | real | 20.850 |
| 0.0049 | real | 22.750 |
| 0.0148 | real | 24.650 |
| 0.0148 | real | 26.550 |
| 0.0181 | real | 28.450 |
| 0.0197 | real | 30.350 |
| 0.0296 | real | 32.250 |
| 0.0362 | real | 34.150 |
| 0.0115 | real | 36.050 |
| 0.0362 | real | 37.950 |
| 0.0313 | real | 39.850 |
| 0.0296 | real | 41.750 |
| 0.0280 | real | 43.650 |
| 0.0280 | real | 45.550 |
| 0.0181 | real | 47.450 |
| 0.0164 | real | 49.350 |
| 0.0197 | real | 51.250 |
| 0.0362 | real | 53.150 |
| 0.0148 | real | 55.050 |
| 0.0164 | real | 56.950 |
| 0.0181 | real | 58.850 |
| 0.0082 | real | 60.750 |
| 0.0164 | real | 62.650 |
| 0.0049 | real | 64.550 |
| 0.0115 | real | 66.450 |
| 0.0066 | real | 68.350 |
| 0.0049 | real | 70.250 |
| 0.0016 | real | 72.150 |
| 0.0049 | real | 74.050 |
| 0.0395 | synthetic | 18.950 |
| 0.0214 | synthetic | 20.850 |
| 0.0164 | synthetic | 22.750 |
| 0.0164 | synthetic | 24.650 |
| 0.0099 | synthetic | 26.550 |
| 0.0296 | synthetic | 28.450 |
| 0.0280 | synthetic | 30.350 |
| 0.0197 | synthetic | 32.250 |
| 0.0181 | synthetic | 34.150 |
| 0.0132 | synthetic | 36.050 |
| 0.0230 | synthetic | 37.950 |
| 0.0164 | synthetic | 39.850 |
| 0.0230 | synthetic | 41.750 |
| 0.0066 | synthetic | 43.650 |
| 0.0132 | synthetic | 45.550 |
| 0.0296 | synthetic | 47.450 |
| 0.0230 | synthetic | 49.350 |
| 0.0362 | synthetic | 51.250 |
| 0.0132 | synthetic | 53.150 |
| 0.0115 | synthetic | 55.050 |
| 0.0214 | synthetic | 56.950 |
| 0.0132 | synthetic | 58.850 |
| 0.0115 | synthetic | 60.750 |
| 0.0066 | synthetic | 62.650 |
| 0.0099 | synthetic | 64.550 |
| 0.0099 | synthetic | 66.450 |
| 0.0099 | synthetic | 68.350 |
| 0.0049 | synthetic | 70.250 |
| 0.0115 | synthetic | 72.150 |
| 0.0197 | synthetic | 74.050 |
View data
| Density | Source | annual income |
|---|---|---|
| 3.010e-6 | real | 6851.93 |
| 1.605e-5 | real | 10141.74 |
| 2.107e-5 | real | 13431.55 |
| 2.408e-5 | real | 16721.36 |
| 3.511e-5 | real | 20011.17 |
| 4.113e-5 | real | 23300.98 |
| 2.809e-5 | real | 26590.79 |
| 2.408e-5 | real | 29880.60 |
| 2.508e-5 | real | 33170.41 |
| 1.605e-5 | real | 36460.22 |
| 1.605e-5 | real | 39750.03 |
| 1.505e-5 | real | 43039.84 |
| 1.003e-5 | real | 46329.65 |
| 5.016e-6 | real | 49619.46 |
| 6.019e-6 | real | 52909.27 |
| 4.013e-6 | real | 56199.07 |
| 4.013e-6 | real | 59488.88 |
| 4.013e-6 | real | 62778.69 |
| 1.003e-6 | real | 66068.50 |
| 1.003e-6 | real | 69358.31 |
| 1.003e-6 | real | 72648.12 |
| 0 | real | 75937.93 |
| 1.003e-6 | real | 79227.74 |
| 1.003e-6 | real | 82517.55 |
| 0 | real | 85807.36 |
| 0 | real | 89097.17 |
| 0 | real | 92386.98 |
| 0 | real | 95676.79 |
| 0 | real | 98966.60 |
| 1.003e-6 | real | 102256.41 |
| 3.912e-5 | synthetic | 6851.93 |
| 1.304e-5 | synthetic | 10141.74 |
| 2.307e-5 | synthetic | 13431.55 |
| 2.909e-5 | synthetic | 16721.36 |
| 3.612e-5 | synthetic | 20011.17 |
| 1.605e-5 | synthetic | 23300.98 |
| 3.010e-5 | synthetic | 26590.79 |
| 1.906e-5 | synthetic | 29880.60 |
| 1.505e-5 | synthetic | 33170.41 |
| 9.029e-6 | synthetic | 36460.22 |
| 1.304e-5 | synthetic | 39750.03 |
| 1.605e-5 | synthetic | 43039.84 |
| 8.026e-6 | synthetic | 46329.65 |
| 4.013e-6 | synthetic | 49619.46 |
| 4.013e-6 | synthetic | 52909.27 |
| 3.010e-6 | synthetic | 56199.07 |
| 3.010e-6 | synthetic | 59488.88 |
| 4.013e-6 | synthetic | 62778.69 |
| 4.013e-6 | synthetic | 66068.50 |
| 2.006e-6 | synthetic | 69358.31 |
| 1.003e-6 | synthetic | 72648.12 |
| 1.003e-6 | synthetic | 75937.93 |
| 3.010e-6 | synthetic | 79227.74 |
| 2.006e-6 | synthetic | 82517.55 |
| 1.003e-6 | synthetic | 85807.36 |
| 0 | synthetic | 89097.17 |
| 1.003e-6 | synthetic | 92386.98 |
| 0 | synthetic | 95676.79 |
| 0 | synthetic | 98966.60 |
| 4.013e-6 | synthetic | 102256.41 |
View data
| Density | Source | tenure_months |
|---|---|---|
| 0.0938 | real | 0.7667 |
| 0.0224 | real | 2.300 |
| 0.0183 | real | 3.833 |
| 0.0306 | real | 5.367 |
| 0.0204 | real | 6.900 |
| 0.0265 | real | 8.433 |
| 0.0204 | real | 9.967 |
| 0.0530 | real | 11.500 |
| 0.0183 | real | 13.033 |
| 0.0510 | real | 14.567 |
| 0.0183 | real | 16.100 |
| 0.0367 | real | 17.633 |
| 0.0224 | real | 19.167 |
| 0.0448 | real | 20.700 |
| 0.0469 | real | 22.233 |
| 0.0082 | real | 23.767 |
| 0.0306 | real | 25.300 |
| 0.0061 | real | 26.833 |
| 0.0183 | real | 28.367 |
| 0.0041 | real | 29.900 |
| 0.0143 | real | 31.433 |
| 0.0061 | real | 32.967 |
| 0.0183 | real | 34.500 |
| 0.0020 | real | 36.033 |
| 0.0041 | real | 37.567 |
| 0 | real | 39.100 |
| 0.0061 | real | 40.633 |
| 0.0041 | real | 42.167 |
| 0.0020 | real | 43.700 |
| 0.0041 | real | 45.233 |
| 0.1651 | synthetic | 0.7667 |
| 0 | synthetic | 2.300 |
| 0.0041 | synthetic | 3.833 |
| 0.0143 | synthetic | 5.367 |
| 0.0020 | synthetic | 6.900 |
| 0.0306 | synthetic | 8.433 |
| 0.0122 | synthetic | 9.967 |
| 0.0469 | synthetic | 11.500 |
| 0.0245 | synthetic | 13.033 |
| 0.0061 | synthetic | 14.567 |
| 0.0041 | synthetic | 16.100 |
| 0.0265 | synthetic | 17.633 |
| 0.0061 | synthetic | 19.167 |
| 0.0306 | synthetic | 20.700 |
| 0.0367 | synthetic | 22.233 |
| 0.0122 | synthetic | 23.767 |
| 0.0326 | synthetic | 25.300 |
| 0.0143 | synthetic | 26.833 |
| 0.0306 | synthetic | 28.367 |
| 0.0082 | synthetic | 29.900 |
| 0.0306 | synthetic | 31.433 |
| 0.0163 | synthetic | 32.967 |
| 0.0082 | synthetic | 34.500 |
| 0.0061 | synthetic | 36.033 |
| 0.0082 | synthetic | 37.567 |
| 0.0020 | synthetic | 39.100 |
| 0.0041 | synthetic | 40.633 |
| 0.0102 | synthetic | 42.167 |
| 0.0061 | synthetic | 43.700 |
| 0.0530 | synthetic | 45.233 |
View data
| Density | Source | signup |
|---|---|---|
| 0.0005 | real | 17582.23 |
| 0.0007 | real | 17654.70 |
| 0.0005 | real | 17727.17 |
| 0.0005 | real | 17799.63 |
| 0.0004 | real | 17872.10 |
| 0.0005 | real | 17944.57 |
| 0.0006 | real | 18017.03 |
| 0.0004 | real | 18089.50 |
| 0.0005 | real | 18161.97 |
| 0.0005 | real | 18234.43 |
| 0.0001 | real | 18306.90 |
| 0.0009 | real | 18379.37 |
| 0.0006 | real | 18451.83 |
| 0.0003 | real | 18524.30 |
| 0.0005 | real | 18596.77 |
| 0.0004 | real | 18669.23 |
| 0.0002 | real | 18741.70 |
| 0.0005 | real | 18814.17 |
| 0.0006 | real | 18886.63 |
| 0.0005 | real | 18959.10 |
| 0.0005 | real | 19031.57 |
| 0.0005 | real | 19104.03 |
| 0.0003 | real | 19176.50 |
| 0.0006 | real | 19248.97 |
| 0.0004 | real | 19321.43 |
| 0.0003 | real | 19393.90 |
| 0.0002 | real | 19466.37 |
| 0.0005 | real | 19538.83 |
| 0.0003 | real | 19611.30 |
| 0.0004 | real | 19683.77 |
| 0.0029 | synthetic | 17582.23 |
| 0.0014 | synthetic | 17654.70 |
| 0.0009 | synthetic | 17727.17 |
| 0.0009 | synthetic | 17799.63 |
| 0.0004 | synthetic | 17872.10 |
| 8.625e-5 | synthetic | 17944.57 |
| 0.0001 | synthetic | 18017.03 |
| 0.0002 | synthetic | 18089.50 |
| 0.0002 | synthetic | 18161.97 |
| 0.0003 | synthetic | 18234.43 |
| 0.0003 | synthetic | 18306.90 |
| 0.0001 | synthetic | 18379.37 |
| 0.0004 | synthetic | 18451.83 |
| 0.0003 | synthetic | 18524.30 |
| 0.0004 | synthetic | 18596.77 |
| 0.0003 | synthetic | 18669.23 |
| 0.0003 | synthetic | 18741.70 |
| 0.0002 | synthetic | 18814.17 |
| 4.312e-5 | synthetic | 18886.63 |
| 0.0003 | synthetic | 18959.10 |
| 0.0001 | synthetic | 19031.57 |
| 0.0002 | synthetic | 19104.03 |
| 8.625e-5 | synthetic | 19176.50 |
| 0.0002 | synthetic | 19248.97 |
| 0.0001 | synthetic | 19321.43 |
| 0.0003 | synthetic | 19393.90 |
| 0.0003 | synthetic | 19466.37 |
| 0.0004 | synthetic | 19538.83 |
| 0.0008 | synthetic | 19611.30 |
| 0.0011 | synthetic | 19683.77 |
View data
| plan | Share | Source |
|---|---|---|
| basic | 0.3563 | real |
| plus | 0.3969 | real |
| premium | 0.2469 | real |
| basic | 0.4406 | synthetic |
| plus | 0.2562 | synthetic |
| premium | 0.3031 | synthetic |
View data
| region | Share | Source |
|---|---|---|
| east | 0.2848 | real |
| north | 0.2718 | real |
| south | 0.3042 | real |
| west | 0.1392 | real |
| east | 0.6230 | synthetic |
| north | 0.2109 | synthetic |
| south | 0.0990 | synthetic |
| west | 0.0671 | synthetic |
View data
| churned | Share | Source |
|---|---|---|
| false | 0.7688 | real |
| true | 0.2313 | real |
| false | 0.5531 | synthetic |
| true | 0.4469 | synthetic |
View data
| Column | Column | Difference |
|---|---|---|
| age | age | 0 |
| annual income | age | 0.3704 |
| tenure_months | age | 0.7748 |
| signup | age | −0.0899 |
| visits | age | 0.1080 |
| age | annual income | 0.3704 |
| annual income | annual income | 0 |
| tenure_months | annual income | 0.1488 |
| signup | annual income | 0.0683 |
| visits | annual income | 0.2467 |
| age | tenure_months | 0.7748 |
| annual income | tenure_months | 0.1488 |
| tenure_months | tenure_months | 0 |
| signup | tenure_months | −0.1098 |
| visits | tenure_months | 0.1820 |
| age | signup | −0.0899 |
| annual income | signup | 0.0683 |
| tenure_months | signup | −0.1098 |
| signup | signup | 0 |
| visits | signup | 0.0735 |
| age | visits | 0.1080 |
| annual income | visits | 0.2467 |
| tenure_months | visits | 0.1820 |
| signup | visits | 0.0735 |
| visits | visits | 0 |
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
| Series | Value | Epoch |
|---|---|---|
| Wasserstein estimate | −0.0587 | 1 |
| Wasserstein estimate | −0.0479 | 2 |
| Wasserstein estimate | −0.0519 | 3 |
| Wasserstein estimate | −0.0434 | 4 |
| Wasserstein estimate | −0.0233 | 5 |
| Wasserstein estimate | −0.0040 | 6 |
| Wasserstein estimate | −0.0016 | 7 |
| Wasserstein estimate | 0.0153 | 8 |
| Wasserstein estimate | 0.0752 | 9 |
| Wasserstein estimate | 0.0989 | 10 |
| Wasserstein estimate | 0.1587 | 11 |
| Wasserstein estimate | 0.2007 | 12 |
| Wasserstein estimate | 0.2505 | 13 |
| Wasserstein estimate | 0.2670 | 14 |
| Wasserstein estimate | 0.3265 | 15 |
| Wasserstein estimate | 0.3515 | 16 |
| Wasserstein estimate | 0.4064 | 17 |
| Wasserstein estimate | 0.4380 | 18 |
| Wasserstein estimate | 0.4732 | 19 |
| Wasserstein estimate | 0.4873 | 20 |
| Wasserstein estimate | 0.5058 | 21 |
| Wasserstein estimate | 0.5778 | 22 |
| Wasserstein estimate | 0.5907 | 23 |
| Wasserstein estimate | 0.6255 | 24 |
| Wasserstein estimate | 0.6466 | 25 |
| Wasserstein estimate | 0.6956 | 26 |
| Wasserstein estimate | 0.7047 | 27 |
| Wasserstein estimate | 0.7173 | 28 |
| Wasserstein estimate | 0.7893 | 29 |
| Wasserstein estimate | 0.7599 | 30 |
| Wasserstein estimate | 0.7871 | 31 |
| Wasserstein estimate | 0.7913 | 32 |
| Wasserstein estimate | 0.7884 | 33 |
| Wasserstein estimate | 0.7959 | 34 |
| Wasserstein estimate | 0.7949 | 35 |
| Wasserstein estimate | 0.8124 | 36 |
| Wasserstein estimate | 0.8137 | 37 |
| Wasserstein estimate | 0.8039 | 38 |
| Wasserstein estimate | 0.7876 | 39 |
| Wasserstein estimate | 0.7513 | 40 |
| critic loss | 2.193 | 1 |
| critic loss | 1.832 | 2 |
| critic loss | 1.506 | 3 |
| critic loss | 1.173 | 4 |
| critic loss | 0.9034 | 5 |
| critic loss | 0.6105 | 6 |
| critic loss | 0.4428 | 7 |
| critic loss | 0.3204 | 8 |
| critic loss | 0.2233 | 9 |
| critic loss | 0.1976 | 10 |
| critic loss | 0.1032 | 11 |
| critic loss | 0.0625 | 12 |
| critic loss | −0.0160 | 13 |
| critic loss | −0.0321 | 14 |
| critic loss | −0.0977 | 15 |
| critic loss | −0.1343 | 16 |
| critic loss | −0.1814 | 17 |
| critic loss | −0.2322 | 18 |
| critic loss | −0.2819 | 19 |
| critic loss | −0.2829 | 20 |
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
| Column | Kind | Real | Synthetic | Distance | Measure |
|---|---|---|---|---|---|
| age | numeric | 43.14 ± 13.1 | 42.61 ± 16.2 | 0.1219 | Kolmogorov–Smirnov D |
| annual income | numeric | 2.929e+04 ± 1.43e+04 | 2.835e+04 ± 1.96e+04 | 0.1386 | Kolmogorov–Smirnov D |
| tenure_months | numeric | 15 ± 10.7 | 18.16 ± 14.8 | 0.1750 | Kolmogorov–Smirnov D |
| plan | categorical | plus 39.7% | plus 25.6% | 0.1406 | total variation |
| region | categorical | south 30.4% | south 9.9% | 0.3382 | total variation |
| churned | boolean | false 76.9% | false 55.3% | 0.2156 | total variation |
| signup | temporal | 2020-11-05 ± 621 days | 2020-04-08 ± 792 days | 0.3000 | Kolmogorov–Smirnov D |
| visits | numeric | 3.394 ± 2.09 | 4.362 ± 3.12 | 0.1594 | Kolmogorov–Smirnov D |
Modes per numeric column (mode-specific normalization)
| Column | Mixture modes |
|---|---|
| age | 5 |
| annual income | 5 |
| tenure_months | 5 |
| signup | 5 |
| visits | 5 |
- 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"
))
))
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
| Column | Kind | Real | Synthetic | Distance | Measure |
|---|---|---|---|---|---|
| age | numeric | 43.14 ± 13.1 | 42.61 ± 16.2 | 0.1219 | Kolmogorov–Smirnov D |
| annual income | numeric | 2.929e+04 ± 1.43e+04 | 2.835e+04 ± 1.96e+04 | 0.1386 | Kolmogorov–Smirnov D |
| tenure_months | numeric | 15 ± 10.7 | 18.16 ± 14.8 | 0.1750 | Kolmogorov–Smirnov D |
| plan | categorical | plus 39.7% | plus 25.6% | 0.1406 | total variation |
| region | categorical | south 30.4% | south 9.9% | 0.3382 | total variation |
| churned | boolean | false 76.9% | false 55.3% | 0.2156 | total variation |
| signup | temporal | 2020-11-05 ± 621 days | 2020-04-08 ± 792 days | 0.3000 | Kolmogorov–Smirnov D |
| visits | numeric | 3.394 ± 2.09 | 4.362 ± 3.12 | 0.1594 | Kolmogorov–Smirnov D |
Modes per numeric column (mode-specific normalization)
| Column | Mixture modes |
|---|---|
| age | 5 |
| annual income | 5 |
| tenure_months | 5 |
| signup | 5 |
| visits | 5 |
- 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.
Check every category
Explore400 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
View data
| Density | Source | bill_len |
|---|---|---|
| 0.0043 | real | 32.558 |
| 0.0043 | real | 33.475 |
| 0.0213 | real | 34.392 |
| 0.0341 | real | 35.308 |
| 0.0469 | real | 36.225 |
| 0.0469 | real | 37.142 |
| 0.0639 | real | 38.058 |
| 0.0639 | real | 38.975 |
| 0.0511 | real | 39.892 |
| 0.0767 | real | 40.808 |
| 0.0426 | real | 41.725 |
| 0.0384 | real | 42.642 |
| 0.0298 | real | 43.558 |
| 0.0256 | real | 44.475 |
| 0.0980 | real | 45.392 |
| 0.0767 | real | 46.308 |
| 0.0554 | real | 47.225 |
| 0.0384 | real | 48.142 |
| 0.0597 | real | 49.058 |
| 0.0639 | real | 49.975 |
| 0.0682 | real | 50.892 |
| 0.0384 | real | 51.808 |
| 0.0128 | real | 52.725 |
| 0.0085 | real | 53.642 |
| 0.0085 | real | 54.558 |
| 0.0085 | real | 55.475 |
| 0 | real | 56.392 |
| 0 | real | 57.308 |
| 0 | real | 58.225 |
| 0.0043 | real | 59.142 |
| 0.3327 | synthetic | 32.558 |
| 0.0355 | synthetic | 33.475 |
| 0.0518 | synthetic | 34.392 |
| 0.0436 | synthetic | 35.308 |
| 0.1145 | synthetic | 36.225 |
| 0.0736 | synthetic | 37.142 |
| 0.0545 | synthetic | 38.058 |
| 0.0409 | synthetic | 38.975 |
| 0.0464 | synthetic | 39.892 |
| 0.0491 | synthetic | 40.808 |
| 0.0382 | synthetic | 41.725 |
| 0.0300 | synthetic | 42.642 |
| 0.0191 | synthetic | 43.558 |
| 0.0109 | synthetic | 44.475 |
| 0.0273 | synthetic | 45.392 |
| 0.0082 | synthetic | 46.308 |
| 0.0136 | synthetic | 47.225 |
| 0.0136 | synthetic | 48.142 |
| 0.0109 | synthetic | 49.058 |
| 0.0245 | synthetic | 49.975 |
| 0.0055 | synthetic | 50.892 |
| 0.0082 | synthetic | 51.808 |
| 0.0082 | synthetic | 52.725 |
| 0.0109 | synthetic | 53.642 |
| 0.0055 | synthetic | 54.558 |
| 0.0055 | synthetic | 55.475 |
| 0.0027 | synthetic | 56.392 |
| 0 | synthetic | 57.308 |
| 0.0055 | synthetic | 58.225 |
| 0 | synthetic | 59.142 |
View data
| Density | Source | bill_dep |
|---|---|---|
| 0.0424 | real | 13.338 |
| 0.0847 | real | 13.615 |
| 0.1271 | real | 13.892 |
| 0.1412 | real | 14.168 |
| 0.1271 | real | 14.445 |
| 0.1271 | real | 14.722 |
| 0.1412 | real | 14.998 |
| 0.0988 | real | 15.275 |
| 0.0565 | real | 15.552 |
| 0.1553 | real | 15.828 |
| 0.0988 | real | 16.105 |
| 0.1271 | real | 16.382 |
| 0.0847 | real | 16.658 |
| 0.2118 | real | 16.935 |
| 0.2400 | real | 17.212 |
| 0.1412 | real | 17.488 |
| 0.2118 | real | 17.765 |
| 0.1412 | real | 18.042 |
| 0.1271 | real | 18.318 |
| 0.2683 | real | 18.595 |
| 0.2824 | real | 18.872 |
| 0.0847 | real | 19.148 |
| 0.1130 | real | 19.425 |
| 0.0988 | real | 19.702 |
| 0.1130 | real | 19.978 |
| 0.0565 | real | 20.255 |
| 0.0141 | real | 20.532 |
| 0.0282 | real | 20.808 |
| 0.0565 | real | 21.085 |
| 0.0141 | real | 21.362 |
| 0.2440 | synthetic | 13.338 |
| 0.1355 | synthetic | 13.615 |
| 0.0723 | synthetic | 13.892 |
| 0.0994 | synthetic | 14.168 |
| 0.1355 | synthetic | 14.445 |
| 0.1265 | synthetic | 14.722 |
| 0.1988 | synthetic | 14.998 |
| 0.1536 | synthetic | 15.275 |
| 0.2349 | synthetic | 15.552 |
| 0.1988 | synthetic | 15.828 |
| 0.1988 | synthetic | 16.105 |
| 0.2078 | synthetic | 16.382 |
| 0.0723 | synthetic | 16.658 |
| 0.0181 | synthetic | 16.935 |
| 0.0452 | synthetic | 17.212 |
| 0.0452 | synthetic | 17.488 |
| 0.0181 | synthetic | 17.765 |
| 0.0542 | synthetic | 18.042 |
| 0.0452 | synthetic | 18.318 |
| 0.0452 | synthetic | 18.595 |
| 0.0633 | synthetic | 18.872 |
| 0.0633 | synthetic | 19.148 |
| 0.0542 | synthetic | 19.425 |
| 0.1265 | synthetic | 19.702 |
| 0.0723 | synthetic | 19.978 |
| 0.0361 | synthetic | 20.255 |
| 0.0633 | synthetic | 20.532 |
| 0.0723 | synthetic | 20.808 |
| 0.0452 | synthetic | 21.085 |
| 0.6687 | synthetic | 21.362 |
View data
| Density | Source | flipper_len |
|---|---|---|
| 0.0020 | real | 172.98 |
| 0.0020 | real | 174.95 |
| 0.0020 | real | 176.92 |
| 0.0060 | real | 178.88 |
| 0.0159 | real | 180.85 |
| 0.0099 | real | 182.82 |
| 0.0238 | real | 184.78 |
| 0.0258 | real | 186.75 |
| 0.0179 | real | 188.72 |
| 0.0616 | real | 190.68 |
| 0.0218 | real | 192.65 |
| 0.0358 | real | 194.62 |
| 0.0278 | real | 196.58 |
| 0.0258 | real | 198.55 |
| 0.0139 | real | 200.52 |
| 0.0119 | real | 202.48 |
| 0.0060 | real | 204.45 |
| 0.0060 | real | 206.42 |
| 0.0179 | real | 208.38 |
| 0.0218 | real | 210.35 |
| 0.0218 | real | 212.32 |
| 0.0278 | real | 214.28 |
| 0.0199 | real | 216.25 |
| 0.0179 | real | 218.22 |
| 0.0199 | real | 220.18 |
| 0.0079 | real | 222.15 |
| 0.0119 | real | 224.12 |
| 0.0020 | real | 226.08 |
| 0.0119 | real | 228.05 |
| 0.0119 | real | 230.02 |
| 0.1081 | synthetic | 172.98 |
| 0.0229 | synthetic | 174.95 |
| 0.0153 | synthetic | 176.92 |
| 0.0102 | synthetic | 178.88 |
| 0.0165 | synthetic | 180.85 |
| 0.0140 | synthetic | 182.82 |
| 0.0153 | synthetic | 184.78 |
| 0.0432 | synthetic | 186.75 |
| 0.0381 | synthetic | 188.72 |
| 0.0216 | synthetic | 190.68 |
| 0.0178 | synthetic | 192.65 |
| 0.0165 | synthetic | 194.62 |
| 0.0229 | synthetic | 196.58 |
| 0.0127 | synthetic | 198.55 |
| 0.0203 | synthetic | 200.52 |
| 0.0140 | synthetic | 202.48 |
| 0.0153 | synthetic | 204.45 |
| 0.0076 | synthetic | 206.42 |
| 0.0089 | synthetic | 208.38 |
| 0.0089 | synthetic | 210.35 |
| 0.0064 | synthetic | 212.32 |
| 0.0038 | synthetic | 214.28 |
| 0.0038 | synthetic | 216.25 |
| 0.0076 | synthetic | 218.22 |
| 0.0038 | synthetic | 220.18 |
| 0.0038 | synthetic | 222.15 |
| 0.0013 | synthetic | 224.12 |
| 0.0102 | synthetic | 226.08 |
| 0.0013 | synthetic | 228.05 |
| 0.0165 | synthetic | 230.02 |
View data
| Density | Source | body_mass |
|---|---|---|
| 3.498e-5 | real | 2755.83 |
| 0.0001 | real | 2867.50 |
| 6.996e-5 | real | 2979.17 |
| 0.0002 | real | 3090.83 |
| 0.0005 | real | 3202.50 |
| 0.0003 | real | 3314.17 |
| 0.0006 | real | 3425.83 |
| 0.0005 | real | 3537.50 |
| 0.0007 | real | 3649.17 |
| 0.0005 | real | 3760.83 |
| 0.0004 | real | 3872.50 |
| 0.0005 | real | 3984.17 |
| 0.0005 | real | 4095.83 |
| 0.0003 | real | 4207.50 |
| 0.0003 | real | 4319.17 |
| 0.0004 | real | 4430.83 |
| 0.0001 | real | 4542.50 |
| 0.0006 | real | 4654.17 |
| 0.0003 | real | 4765.83 |
| 0.0003 | real | 4877.50 |
| 0.0002 | real | 4989.17 |
| 0.0003 | real | 5100.83 |
| 0.0001 | real | 5212.50 |
| 0.0002 | real | 5324.17 |
| 0.0001 | real | 5435.83 |
| 0.0005 | real | 5547.50 |
| 0.0002 | real | 5659.17 |
| 6.996e-5 | real | 5770.83 |
| 3.498e-5 | real | 5882.50 |
| 0.0001 | real | 5994.17 |
| 0.0010 | synthetic | 2755.83 |
| 0.0002 | synthetic | 2867.50 |
| 0.0003 | synthetic | 2979.17 |
| 0.0003 | synthetic | 3090.83 |
| 8.955e-5 | synthetic | 3202.50 |
| 0.0003 | synthetic | 3314.17 |
| 8.955e-5 | synthetic | 3425.83 |
| 0.0002 | synthetic | 3537.50 |
| 0.0002 | synthetic | 3649.17 |
| 0.0002 | synthetic | 3760.83 |
| 8.955e-5 | synthetic | 3872.50 |
| 8.955e-5 | synthetic | 3984.17 |
| 0.0001 | synthetic | 4095.83 |
| 0.0003 | synthetic | 4207.50 |
| 0.0001 | synthetic | 4319.17 |
| 0.0002 | synthetic | 4430.83 |
| 0.0001 | synthetic | 4542.50 |
| 0.0006 | synthetic | 4654.17 |
| 0.0005 | synthetic | 4765.83 |
| 0.0006 | synthetic | 4877.50 |
| 0.0004 | synthetic | 4989.17 |
| 0.0002 | synthetic | 5100.83 |
| 0.0002 | synthetic | 5212.50 |
| 0.0003 | synthetic | 5324.17 |
| 0.0002 | synthetic | 5435.83 |
| 0.0003 | synthetic | 5547.50 |
| 0.0003 | synthetic | 5659.17 |
| 0.0002 | synthetic | 5770.83 |
| 0.0002 | synthetic | 5882.50 |
| 0.0010 | synthetic | 5994.17 |
View data
| species | Share | Source |
|---|---|---|
| Adelie | 0.4419 | real |
| Chinstrap | 0.1899 | real |
| Gentoo | 0.3682 | real |
| Adelie | 0.4975 | synthetic |
| Chinstrap | 0.1450 | synthetic |
| Gentoo | 0.3575 | synthetic |
View data
| island | Share | Source |
|---|---|---|
| Biscoe | 0.4806 | real |
| Dream | 0.3643 | real |
| Torgersen | 0.1550 | real |
| Biscoe | 0.3800 | synthetic |
| Dream | 0.3775 | synthetic |
| Torgersen | 0.2425 | synthetic |
View data
| sex | Share | Source |
|---|---|---|
| female | 0.4940 | real |
| male | 0.5060 | real |
| female | 0.4300 | synthetic |
| male | 0.5700 | synthetic |
View data
| Column | Column | Difference |
|---|---|---|
| bill_len | bill_len | 0 |
| bill_dep | bill_len | −0.3273 |
| flipper_len | bill_len | 0.5662 |
| body_mass | bill_len | 0.8578 |
| bill_len | bill_dep | −0.3273 |
| bill_dep | bill_dep | 0 |
| flipper_len | bill_dep | −0.7312 |
| body_mass | bill_dep | −0.2861 |
| bill_len | flipper_len | 0.5662 |
| bill_dep | flipper_len | −0.7312 |
| flipper_len | flipper_len | 0 |
| body_mass | flipper_len | 0.9032 |
| bill_len | body_mass | 0.8578 |
| bill_dep | body_mass | −0.2861 |
| flipper_len | body_mass | 0.9032 |
| body_mass | body_mass | 0 |
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
| Series | Value | Epoch |
|---|---|---|
| Wasserstein estimate | 0.1847 | 1 |
| Wasserstein estimate | 0.2213 | 2 |
| Wasserstein estimate | 0.2621 | 3 |
| Wasserstein estimate | 0.2694 | 4 |
| Wasserstein estimate | 0.2892 | 5 |
| Wasserstein estimate | 0.3209 | 6 |
| Wasserstein estimate | 0.3621 | 7 |
| Wasserstein estimate | 0.3784 | 8 |
| Wasserstein estimate | 0.4599 | 9 |
| Wasserstein estimate | 0.4253 | 10 |
| Wasserstein estimate | 0.4554 | 11 |
| Wasserstein estimate | 0.5060 | 12 |
| Wasserstein estimate | 0.4987 | 13 |
| Wasserstein estimate | 0.5511 | 14 |
| Wasserstein estimate | 0.4933 | 15 |
| Wasserstein estimate | 0.5982 | 16 |
| Wasserstein estimate | 0.6130 | 17 |
| Wasserstein estimate | 0.6179 | 18 |
| Wasserstein estimate | 0.6637 | 19 |
| Wasserstein estimate | 0.6705 | 20 |
| Wasserstein estimate | 0.6746 | 21 |
| Wasserstein estimate | 0.7196 | 22 |
| Wasserstein estimate | 0.7000 | 23 |
| Wasserstein estimate | 0.7549 | 24 |
| Wasserstein estimate | 0.7691 | 25 |
| Wasserstein estimate | 0.7437 | 26 |
| Wasserstein estimate | 0.7713 | 27 |
| Wasserstein estimate | 0.7679 | 28 |
| Wasserstein estimate | 0.8293 | 29 |
| Wasserstein estimate | 0.8374 | 30 |
| critic loss | −0.0726 | 1 |
| critic loss | −0.1106 | 2 |
| critic loss | −0.1599 | 3 |
| critic loss | −0.1865 | 4 |
| critic loss | −0.2050 | 5 |
| critic loss | −0.2294 | 6 |
| critic loss | −0.2784 | 7 |
| critic loss | −0.2864 | 8 |
| critic loss | −0.3780 | 9 |
| critic loss | −0.3401 | 10 |
| critic loss | −0.3680 | 11 |
| critic loss | −0.4219 | 12 |
| critic loss | −0.4137 | 13 |
| critic loss | −0.4648 | 14 |
| critic loss | −0.4063 | 15 |
| critic loss | −0.5192 | 16 |
| critic loss | −0.5287 | 17 |
| critic loss | −0.5382 | 18 |
| critic loss | −0.5870 | 19 |
| critic loss | −0.5876 | 20 |
| critic loss | −0.6011 | 21 |
| critic loss | −0.6418 | 22 |
| critic loss | −0.6215 | 23 |
| critic loss | −0.6736 | 24 |
| critic loss | −0.6896 | 25 |
| critic loss | −0.6638 | 26 |
| critic loss | −0.6933 | 27 |
| critic loss | −0.6958 | 28 |
| critic loss | −0.7540 | 29 |
| critic loss | −0.7594 | 30 |
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
| Column | Kind | Real | Synthetic | Distance | Measure |
|---|---|---|---|---|---|
| species | categorical | Adelie 44.2% | Adelie 49.8% | 0.0556 | total variation |
| island | categorical | Biscoe 48.1% | Biscoe 38.0% | 0.1006 | total variation |
| bill_len | numeric | 43.96 ± 5.5 | 37.82 ± 5.99 | 0.4606 | Kolmogorov–Smirnov D |
| bill_dep | numeric | 17.14 ± 1.98 | 17.25 ± 2.85 | 0.2062 | Kolmogorov–Smirnov D |
| flipper_len | numeric | 201.3 ± 14.2 | 190.5 ± 16.2 | 0.3505 | Kolmogorov–Smirnov D |
| body_mass | numeric | 4219 ± 791 | 4503 ± 1.1e+03 | 0.2533 | Kolmogorov–Smirnov D |
| sex | categorical | male 50.6% | male 57.0% | 0.0640 | total variation |
Modes per numeric column (mode-specific normalization)
| Column | Mixture modes |
|---|---|
| bill_len | 3 |
| bill_dep | 3 |
| flipper_len | 3 |
| body_mass | 3 |
- 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"
))
))
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
| Column | Kind | Real | Synthetic | Distance | Measure |
|---|---|---|---|---|---|
| species | categorical | Adelie 44.2% | Adelie 49.8% | 0.0556 | total variation |
| island | categorical | Biscoe 48.1% | Biscoe 38.0% | 0.1006 | total variation |
| bill_len | numeric | 43.96 ± 5.5 | 37.82 ± 5.99 | 0.4606 | Kolmogorov–Smirnov D |
| bill_dep | numeric | 17.14 ± 1.98 | 17.25 ± 2.85 | 0.2063 | Kolmogorov–Smirnov D |
| flipper_len | numeric | 201.3 ± 14.2 | 190.5 ± 16.2 | 0.3505 | Kolmogorov–Smirnov D |
| body_mass | numeric | 4219 ± 791 | 4503 ± 1.1e+03 | 0.2533 | Kolmogorov–Smirnov D |
| sex | categorical | male 50.6% | male 57.0% | 0.0640 | total variation |
Modes per numeric column (mode-specific normalization)
| Column | Mixture modes |
|---|---|
| bill_len | 3 |
| bill_dep | 3 |
| flipper_len | 3 |
| body_mass | 3 |
- 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.
DCGAN and checkerboards
ReadDCGAN 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.What runs here
ReadCheck: GANs
CheckpointCheck 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.
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