Skip to content

Learned representations: a VAE and a contrastive encoder

Two Experimental methods learn a compact summary of each row with a neural network. A variational autoencoder gives a map you can sample; a SCARF contrastive encoder learns by telling rows apart. What each optimizes and how to check it.

Applied ~12 min9 steps

What runs in CodeSplash

You will be able to

  • Explain the two parts of a VAE's loss and what posterior collapse looks like
  • Explain how SCARF builds a second view of a row and what InfoNCE rewards
  • Check a learned representation with trustworthiness and a label probe

Read first

01

A description the network learns

Read

PCA describes each row by a few weighted sums of its columns. A neural network can learn a bent description instead. Discover has two Experimental methods for this, under Map the data.

A variational autoencoderVariational autoencoderAn autoencoder trained so its latent space is smooth and close to a normal distribution, which lets you sample from it. squeezes each row into a small normal distribution and rebuilds the row from a draw.

A contrastive encoderContrastive learningLearning representations without labels by pulling two views of the same row together and pushing other rows' views away. learns by matching each row with a scrambled copy of itself, and never rebuilds anything.

02

Two forces in one loss

Predict

Predict first

A VAE's loss adds the rebuilding error to β times a KL term that pulls every row's code towards N(0, I). What happens when you raise β?

Rows get rebuilt more sharplyThe latent space gets smoother, and some dimensions may switch offNothing changes
Reveal

The pull towards the prior wins more often. The space gets smoother, rebuilt rows get blurrier, and dimensions the model can spare collapse onto the prior. On Pima with β = 4, only 1 of 2 dimensions stay active.

03

Read a VAE's latent map

Explore

Run the VAE on iris and open Latent means against the N(0, I) prior.

Variational autoencoder (latent map, anomalies and generated rows)Recorded · Python and R agreeRecorded 2026-11-25 · 43 values compared
R

A variational autoencoder mapped 150 rows into 2 latent coordinates (2 in use); the mean squared reconstruction error is 0.133 per standardized column and the mean KL is 1.11 nats; 8 rows with a loss of at least 3.53 are flagged as anomalies. 150 rows generated from the prior differ from the data by a mean KS distance of 0.160.

Mean reconstruction error
0.1330
Mean KL (nats per row)
1.110
Active latent dimensions
2
Trustworthiness (k = 10)
0.9773
Anomalies
8

Plots

Latent means against the N(0, I) priorDoes a variational autoencoder's latent space fill its N(0, I) prior, or leave holes and collapse?
View data
speciesLatent 1 (μ)Latent 2 (μ)
setosa1.1760.3987
setosa1.151−0.3919
setosa1.291−0.1713
setosa1.287−0.3178
setosa1.2160.4858
setosa0.99571.062
setosa1.3260.0476
setosa1.1960.2171
setosa1.299−0.6013
setosa1.195−0.2248
setosa1.0620.8139
setosa1.2610.1357
setosa1.212−0.3913
setosa1.401−0.4933
setosa0.95431.329
setosa0.87561.628
setosa1.0381.057
setosa1.1570.3926
setosa0.91391.076
setosa1.1470.7914
setosa1.0120.3939
setosa1.1320.6660
setosa1.3760.2936
setosa1.0530.0777
setosa1.2320.1401
setosa1.090−0.3562
setosa1.1450.2015
setosa1.1290.4465
setosa1.1260.2994
setosa1.267−0.1591
setosa1.205−0.2643
setosa0.98700.3600
setosa1.1131.155
setosa1.0051.393
setosa1.175−0.2433
setosa1.187−0.0832
setosa1.0250.5760
setosa1.2680.4352
setosa1.340−0.4887
setosa1.1570.2596
setosa1.2030.3455
setosa0.9491−1.270
setosa1.387−0.2521
setosa1.1090.3276
setosa1.0840.7959
setosa1.170−0.4365
setosa1.1550.7866
setosa1.318−0.1957
setosa1.0990.7653
setosa1.1910.0722
versicolor−0.78220.5444
versicolor−0.54930.3661
versicolor−0.84500.3862
versicolor−0.0362−1.121
versicolor−0.6487−0.1629
versicolor−0.1764−0.4722
versicolor−0.57480.4935
versicolor0.4366−1.172
versicolor−0.59920.0041
versicolor0.1325−0.8017

First 60 of 150 rows.

Per-row loss (reconstruction + β·KL) distributionHow unusual are the most anomalous rows compared with the rest, and where is the cut?
View data
AnomalyPer-row loss
false1.315
false1.521
false1.439
false1.607
false1.447
false2.103
false1.513
false1.256
false2.173
false1.447
false1.670
false1.346
false1.629
false2.195
false3.030
true4.902
false2.189
false1.291
false2.056
false1.816
false1.316
false1.577
false1.776
false1.197
false1.390
false1.463
false1.235
false1.315
false1.268
false1.437
false1.440
false1.268
false3.056
true3.605
false1.389
false1.322
false1.514
false1.527
false1.994
false1.245
false1.321
true4.088
false1.772
false1.399
false1.808
false1.546
false1.840
false1.524
false1.625
false1.251
false1.800
false1.094
false1.385
false1.944
false0.9980
false0.8023
false1.252
false2.226
false1.176
false1.287

First 60 of 150 rows.

Training loss and its parts by epochIs the network still learning, and which part of its loss moves?
View data
PartLoss per rowEpoch
total5.2891
total4.9312
total4.9073
total4.5974
total4.3595
total4.2546
total4.0137
total4.1768
total3.9259
total3.80310
total3.69511
total3.66612
total3.49813
total3.50814
total3.28815
total3.40516
total3.28917
total3.09918
total3.07719
total2.74120
total2.69521
total2.85722
total2.83123
total2.77724
total2.93625
total3.03126
total2.90427
total2.75628
total2.76229
total2.67830
total2.71831
total2.73032
total2.48533
total2.56434
total2.60735
total2.52736
total2.67437
total2.59738
total2.68039
total2.47440
total2.68541
total2.62342
total2.75043
total2.71244
total2.49745
total2.56446
total2.44647
total2.57748
total2.51649
total2.45250
total2.50751
total2.41052
total2.43353
total2.33254
total2.36955
total2.49656
total2.52057
total2.47458
total2.65659
total2.40560

First 60 of 600 rows.

sepal_length: data vs rows generated from the priorDoes the synthetic data reproduce the shape of a numeric column?
View data
DensitySourcesepal_length
0.2222real4.360
0.0556real4.480
0.2222real4.600
0.1111real4.720
0.2778real4.840
0.8889real4.960
0.5000real5.080
0.2222real5.200
0.0556real5.320
0.3333real5.440
0.7222real5.560
0.4444real5.680
0.3889real5.800
0.1667real5.920
0.6667real6.040
0.2222real6.160
0.5000real6.280
0.3889real6.400
0.2778real6.520
0.1111real6.640
0.6111real6.760
0.2222real6.880
0.0556real7
0.0556real7.120
0.2222real7.240
0.0556real7.360
0real7.480
0.0556real7.600
0.2222real7.720
0.0556real7.840
0synthetic4.360
0.0556synthetic4.480
0.1111synthetic4.600
0.2778synthetic4.720
0.4444synthetic4.840
0.3333synthetic4.960
0.3889synthetic5.080
0.3333synthetic5.200
0.6111synthetic5.320
0.2778synthetic5.440
0.5000synthetic5.560
0.5000synthetic5.680
0.6111synthetic5.800
0.3889synthetic5.920
0.3333synthetic6.040
0.4444synthetic6.160
0.6111synthetic6.280
0.5000synthetic6.400
0.4444synthetic6.520
0.4444synthetic6.640
0.4444synthetic6.760
0.1667synthetic6.880
0.1111synthetic7
0synthetic7.120
0synthetic7.240
0synthetic7.360
0synthetic7.480
0synthetic7.600
0synthetic7.720
0synthetic7.840

Assumptions

  • Latent dimensions in use — 2 of 2 latent dimensions vary across rows (variance of μ > 0.01).

Rows the model finds least typical

RankRowPer-row losssepal_lengthsepal_widthpetal_lengthpetal_width
11325.8707.9003.8006.4002
21185.5507.7003.8006.7002.200
3164.9025.7004.4001.5000.4000
41194.3427.7002.6006.9002.300
5424.0884.5002.3001.3000.3000
6613.918523.5001
7343.6055.5004.2001.4000.2000
81103.5307.2003.6006.1002.500
91233.2797.7002.8006.7002
10333.0565.2004.1001.5000.1000
11153.0305.80041.2000.2000
121362.7547.70036.1002.300
13632.68862.20041
141062.6617.60036.6002.100
15692.6166.2002.2004.5001.500
161202.55562.20051.500
171072.4914.9002.5004.5001.700
18942.42652.3003.3001
191372.3336.3003.4005.6002.400
201012.3246.3003.30062.500

Latent dimensions

DimensionMean KL (nats)Variance of μActive
10.86340.8815yes
20.24680.3660yes
The exact R script · R R version 4.5.1 (2025-06-13)
# Variational autoencoder (latent map, anomalies and generated rows)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.vae 1.2.0 · spec dddd5c04a52df612
# Dataset: ml_iris (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)  # cs_deep_fit_vae: torch VAE with shared initial weights (twin of codesplash.deep.generative)

# %% Data — standardized numbers (median-imputed), one-hot categories
IMPUTE <- "median"
SCALE <- "standard"
cs_check_finite_columns(as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_iris.parquet", col_select = c("sepal_length", "sepal_width", "petal_length", "petal_width"))), c("sepal_length", "sepal_width", "petal_length", "petal_width"))
# Training options, live progress and checkpoints (twin: codesplash.deep.trainer.configure).
cs_deep_trainer_configure(list(
  optimizer = "default",
  lr_schedule = "none",
  warmup_epochs = 0,
  grad_clip = 0,
  ema_decay = 0,
  swa_start = 0,
  history_every_step = FALSE,
  profile = "parity",
  checkpoint_every = NULL
), out_dir = "target/academy-parity/run-8142/discover.vae/iris_map/out-r")
FEATURES <- c("sepal_length", "sepal_width", "petal_length", "petal_width")
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_iris.parquet", col_select = FEATURES))
warnings <- list()
design <- cs_ml_design(
  df, FEATURES,
  kinds = list(
    sepal_length = "numeric",
    sepal_width = "numeric",
    petal_length = "numeric",
    petal_width = "numeric"
  ),
  levels = list(
  ),
  impute = IMPUTE,
  scale = SCALE
)
fitted <- cs_ml_design_fit(design, df)
X <- unname(cs_ml_design_apply(fitted, df))  # numbers imputed / scaled; categories one-hot (missing -> all zero)
rows <- seq_len(nrow(df)) - 1L
LABEL <- "species"
if (!is.null(LABEL)) df[[LABEL]] <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_iris.parquet", col_select = LABEL))[[LABEL]]

# %% Variational autoencoder (torch for R, float64, one thread): encoder -> (mu, log sigma^2) -> z = mu + sigma * eps -> decoder
HIDDEN <- as.integer(unlist(c(8)))
LATENT <- as.integer(2)
BETA <- 1
N_SAMPLES <- as.integer(150)
PRIOR <- "normal"  # N(0, I), or a learned Gaussian mixture (VaDE)
IWAE <- as.integer(0)
if (PRIOR == "mixture" && length(rows) <= 3) {
  cs_error("CS_E_TOO_FEW_ROWS", what = "A 3-component mixture prior", min = 3 + 1, n = length(rows))
}
fit <- if (PRIOR == "mixture") {
  cs_deep_fit_vade(
    X, HIDDEN, LATENT, as.integer(3),
    activation = "tanh",
    beta = BETA,
    epochs = as.integer(200),
    lr = 0.01,
    batch_size = NULL,
    weight_decay = 0,
    n_samples = N_SAMPLES,
    pretrain_epochs = as.integer(100),
    seed = 42
  )
} else {
  cs_deep_fit_vae(
    X, HIDDEN, LATENT,
    activation = "tanh",
    beta = BETA,
    epochs = as.integer(200),
    lr = 0.01,
    batch_size = NULL,
    weight_decay = 0,
    n_samples = N_SAMPLES,
    seed = 42
  )
}
if (any(!is.finite(fit$score))) cs_error("CS_E_NO_CONVERGENCE", what = "Variational autoencoder training")
Z <- fit$embedding  # posterior means mu (n x LATENT)
scores <- fit$score  # squared reconstruction error at z = mu plus beta x KL, per row
errors <- fit$error  # mean squared reconstruction error per standardized column

# %% Anomalies by the per-row loss
RULE <- "share"
flagged <- cs_ml_flag(scores, RULE, 0.05, 10)
flags <- flagged$flag
threshold <- flagged$threshold
ord <- order(-scores, rows)  # largest loss first, ties by row

# %% Neighborhood preservation of the map (same rows in both engines)
sample <- cs_ml_sample_rows(length(rows))
k_eval <- min(10L, length(sample) - 2L)
trust <- if (k_eval >= 1L) cs_ml_trustworthiness(X[sample, , drop = FALSE], Z[sample, , drop = FALSE], k_eval) else NaN  # undefined with fewer than 3 rows

# %% Mixture prior: each row's component at z = mu (canonical ids 1..k by size)
clusters <- NULL
if (PRIOR == "mixture") {
  clusters <- cs_ml_canonical(fit$cluster)
  comp_of <- integer(0)
  for (j in seq_along(fit$pi)) {
    members <- which(fit$cluster == j - 1L)
    if (length(members)) comp_of[as.character(j)] <- clusters[members[1]]
  }
}

# %% Importance-weighted bound on log p(x) (and the ELBO from the same draws)
bound <- if (IWAE > 0L) cs_deep_iwae_bound(X, fit, LATENT, "tanh", IWAE, 42) else NULL

# %% Generated rows: decode prior draws back to the columns' units
gen_cols <- if (N_SAMPLES > 0L) cs_deep_decode_design(fitted, fit$samples) else list()
NUMERIC <- Filter(function(f) identical(design$kinds[[f]], "numeric"), FEATURES)
sample_ks <- list()
if (N_SAMPLES > 0L) for (f in NUMERIC) sample_ks[[f]] <- cs_deep_ks(suppressWarnings(as.numeric(df[[f]])), gen_cols[[f]])

# %% Artifacts
out <- cs_ml_out_dir("target/academy-parity/run-8142/discover.vae/iris_map/out-r")
emb <- data.frame(row = as.integer(rows))
for (j in seq_len(LATENT)) emb[[paste0("dim_", j)]] <- Z[, j]
nanoparquet::write_parquet(emb, file.path(out, "embedding.parquet"))
labels_df <- data.frame(row = as.integer(rows), score = scores, anomaly = flags)
if (!is.null(clusters)) labels_df$cluster <- as.integer(clusters)
nanoparquet::write_parquet(labels_df, file.path(out, "labels.parquet"))
hist <- data.frame(
  epoch = vapply(fit$history, function(h) as.numeric(h$epoch), numeric(1)),
  loss = vapply(fit$history, function(h) h$loss, numeric(1)),
  reconstruction = vapply(fit$history, function(h) h$recon, numeric(1)),
  kl = vapply(fit$history, function(h) h$kl, numeric(1))
)
nanoparquet::write_parquet(hist, file.path(out, "history.parquet"))
artifacts <- list(
  list(key = "embedding", path = file.path(out, "embedding.parquet"), format = "parquet"),
  list(key = "labels", path = file.path(out, "labels.parquet"), format = "parquet"),
  list(key = "history", path = file.path(out, "history.parquet"), format = "parquet")
)
if (N_SAMPLES > 0L) {
  nanoparquet::write_parquet(as.data.frame(gen_cols[FEATURES], check.names = FALSE), file.path(out, "samples.parquet"))
  artifacts[[length(artifacts) + 1L]] <- list(key = "samples", path = file.path(out, "samples.parquet"), format = "parquet",
                                              title = "Rows generated from the prior")
}

# %% Result
active <- as.integer(fit$active)
values <- list(
  n = length(rows), n_features = ncol(X), latent_dim = LATENT, recon_mse = mean(errors), kl = mean(fit$kl_row),
  elbo_loss = mean(scores), active_dims = active, error_check = cs_ml_checksum(scores, rows), n_flagged = sum(flags),
  threshold = threshold, final_loss = hist$loss[nrow(hist)], epochs_run = fit$epochs_run, trustworthiness = trust,
  n_samples = N_SAMPLES, sample_ks_mean = if (length(sample_ks)) mean(unlist(sample_ks)) else NaN
)
for (j in seq_len(LATENT)) {
  values[[sprintf("emb_check[%d]", j)]] <- cs_ml_checksum(Z[, j], rows)
  values[[sprintf("kl_dim[%d]", j)]] <- fit$kl_dim[j]
}
for (f in names(sample_ks)) values[[sprintf("sample_ks[%s]", f)]] <- sample_ks[[f]]
if (!is.null(clusters)) {
  values$components <- length(fit$pi)
  values$n_clusters <- length(comp_of)
  for (j in names(comp_of)) {
    values[[sprintf("pi[%d]", comp_of[[j]])]] <- fit$pi[as.integer(j)]
    values[[sprintf("cluster_size[%d]", comp_of[[j]])]] <- sum(clusters == comp_of[[j]])
  }
}
if (!is.null(bound)) {
  values$iwae_samples <- IWAE
  values$iwae_bound <- mean(bound$iwae)
  values$elbo_estimate <- mean(bound$elbo)
  values$iwae_gap <- values$iwae_bound - values$elbo_estimate
}
for (rank in seq_len(min(10L, length(ord)))) {
  values[[sprintf("top_row[%d]", rank)]] <- rows[ord[rank]]
  values[[sprintf("top_score[%d]", rank)]] <- scores[ord[rank]]
}
top <- utils::head(ord, 20L)
table_rows <- lapply(seq_along(top), function(rank) {
  i <- top[rank]
  r <- list(rank = rank, row = rows[i] + 1L, score = scores[i])
  for (f in FEATURES) {
    v <- df[[f]][rows[i] + 1L]
    r[[f]] <- if (is.na(v)) NULL else if (is.numeric(v)) v else as.character(v)
  }
  r
})
dim_rows <- lapply(seq_len(LATENT), function(j) list(dim = j, kl = fit$kl_dim[j], var_mu = fit$mu_var[j], active = fit$mu_var[j] > 0.01))
pick <- cs_ml_sample_rows(length(rows), 5000)
groups <- if (is.null(LABEL)) rep("All rows", length(pick)) else {
  g <- df[[LABEL]][rows[pick] + 1L]
  ifelse(is.na(g), "(missing)", as.character(g))
}
charts <- list()
if (LATENT >= 2L && !is.null(clusters)) {
  cent_ <- as.integer(names(comp_of))[order(comp_of)]
  charts[[length(charts) + 1L]] <- cs_chart("latent", "cluster-scatter", "Latent means by mixture component (component means marked)", list(
    x = cs_col("Latent 1 (μ)", c(Z[pick, 1], fit$mu_c[cent_, 1]), "numeric"),
    y = cs_col("Latent 2 (μ)", c(Z[pick, 2], fit$mu_c[cent_, 2]), "numeric"),
    cluster = cs_col("Component", c(as.character(clusters[pick]), as.character(comp_of[as.character(cent_)])), "categorical",
                     levels = as.character(sort(as.integer(comp_of)))),
    centroid = cs_col("Component mean", c(rep(FALSE, length(pick)), rep(TRUE, length(cent_))), "boolean")
  ), note = if (length(pick) == length(rows)) NULL else sprintf("%s of %s rows shown.", format(length(pick), big.mark = ","), format(length(rows), big.mark = ",")))
} else if (LATENT >= 2L) {
  charts[[length(charts) + 1L]] <- cs_chart("latent", "latent-prior", "Latent means against the N(0, I) prior", list(
    x = cs_col("Latent 1 (μ)", Z[pick, 1], "numeric"),
    y = cs_col("Latent 2 (μ)", Z[pick, 2], "numeric"),
    group = cs_col(if (is.null(LABEL)) "Group" else LABEL, groups, "categorical")
  ), note = if (length(pick) == length(rows)) NULL else sprintf("%s of %s rows shown.", format(length(pick), big.mark = ","), format(length(rows), big.mark = ",")))
}
charts[[length(charts) + 1L]] <- cs_chart("errors", "anomaly-scores", "Per-row loss (reconstruction + β·KL) distribution", list(
  score = cs_col("Per-row loss", scores, "numeric"),
  anomaly = cs_col("Anomaly", flags, "boolean")
), controls = list(threshold = threshold))
ne <- nrow(hist)
charts[[length(charts) + 1L]] <- cs_chart("training", "training-components", "Training loss and its parts by epoch", list(
  x = cs_col("Epoch", rep(hist$epoch, 3), "numeric"),
  value = cs_col("Loss per row", c(hist$loss, hist$reconstruction, hist$kl), "numeric"),
  component = cs_col("Part", rep(c("total", "reconstruction", "KL"), each = ne), "categorical", levels = c("total", "reconstruction", "KL"))
))
if (length(sample_ks)) {
  f0 <- NUMERIC[1]
  d <- cs_synth_density_rows(suppressWarnings(as.numeric(df[[f0]])), as.numeric(gen_cols[[f0]]))
  if (!is.null(d)) {
    charts[[length(charts) + 1L]] <- cs_chart("samples", "density-compare", sprintf("%s: data vs rows generated from the prior", f0), list(
      x = cs_col(f0, d$x, "numeric"), density = cs_col("Density", d$density, "numeric"),
      source = cs_col("Source", d$source, "categorical", levels = c("real", "synthetic"))))
  }
}
assumptions <- list(list(
  key = "active_units", label = "Latent dimensions in use",
  status = if (active == LATENT) "pass" else if (active == 0L) "fail" else "warn",
  detail = paste0(sprintf("%d of %d latent dimension%s vary across rows (variance of μ > 0.01)", active, LATENT, if (LATENT != 1L) "s" else ""),
                  if (active == LATENT) "." else "; the rest collapsed onto the prior and carry no information about the rows.")
))
if (active < LATENT) {
  warnings <- c(warnings, sprintf("Posterior collapse: %d latent dimension%s carry no information (KL ≈ 0). Lower β, shrink the bottleneck, or train longer.",
                                  LATENT - active, if (LATENT - active != 1L) "s" else ""))
}
summary <- sprintf("A variational autoencoder mapped %d rows into %d latent coordinate%s (%d in use); the mean squared reconstruction error is %s per standardized column and the mean KL is %s nats; %d rows with a loss of at least %s are flagged as anomalies.",
                   length(rows), LATENT, if (LATENT != 1L) "s" else "", active, format(signif(mean(errors), 3)), format(signif(mean(fit$kl_row), 3)),
                   sum(flags), format(signif(threshold, 3)))
if (length(sample_ks)) summary <- paste0(summary, sprintf(" %d rows generated from the prior differ from the data by a mean KS distance of %.3f.", N_SAMPLES, values$sample_ks_mean))
if (!is.null(clusters)) summary <- paste0(summary, sprintf(" The mixture prior's %d components hold %d cluster%s of rows.", length(fit$pi), length(comp_of), if (length(comp_of) != 1L) "s" else ""))
if (!is.null(bound)) summary <- paste0(summary, sprintf(" The importance-weighted bound with %d draws is %s nats per row (%s above the ELBO estimate).", IWAE,
                                                       format(signif(values$iwae_bound, 4)), format(signif(values$iwae_gap, 3))))
extra_stats <- list()
if (!is.null(bound)) extra_stats[[1]] <- list(key = "iwae_bound", label = sprintf("Log-likelihood bound (IWAE, %d draws)", IWAE), value = values$iwae_bound)
extra_tables <- list()
if (!is.null(clusters)) {
  ordj <- as.integer(names(comp_of))[order(comp_of)]
  extra_tables[[1]] <- list(
    key = "components", title = "Mixture prior components",
    columns = c(list(list(key = "cluster", label = "Component", type = "integer"), list(key = "size", label = "Rows", type = "integer"),
                     list(key = "weight", label = "Prior weight", type = "number")),
                lapply(seq_len(LATENT), function(d) list(key = sprintf("mu_%d", d), label = sprintf("Mean %d", d), type = "number"))),
    rows = lapply(ordj, function(j) {
      cc <- comp_of[[as.character(j)]]
      r <- list(cluster = cc, size = sum(clusters == cc), weight = fit$pi[j])
      for (d in seq_len(LATENT)) r[[sprintf("mu_%d", d)]] <- fit$mu_c[j, d]
      r
    })
  )
}
cs_publish(list(
  title = "Variational autoencoder (latent map, anomalies and generated rows)",
  engine = cs_engine_info("torch", "nanoparquet"),
  n = length(rows),
  summary = summary,
  statistics = c(list(
    list(key = "recon_mse", label = "Mean reconstruction error", value = mean(errors)),
    list(key = "kl", label = "Mean KL (nats per row)", value = mean(fit$kl_row)),
    list(key = "active_dims", label = "Active latent dimensions", value = active, format = "integer"),
    list(key = "trustworthiness", label = sprintf("Trustworthiness (k = %d)", k_eval), value = trust),
    list(key = "n_flagged", label = "Anomalies", value = sum(flags), format = "integer")
  ), extra_stats),
  tables = c(list(
    list(
      key = "top", title = "Rows the model finds least typical",
      columns = c(list(list(key = "rank", label = "Rank", type = "integer"), list(key = "row", label = "Row", type = "integer"),
                       list(key = "score", label = "Per-row loss", type = "number")),
                  lapply(FEATURES, function(f) list(key = f, label = f))),
      rows = table_rows
    ),
    list(
      key = "latent", title = "Latent dimensions",
      columns = list(list(key = "dim", label = "Dimension", type = "integer"), list(key = "kl", label = "Mean KL (nats)", type = "number"),
                     list(key = "var_mu", label = "Variance of μ", type = "number"), list(key = "active", label = "Active", type = "boolean")),
      rows = dim_rows
    )
  ), extra_tables),
  charts = charts,
  assumptions = assumptions,
  values = values,
  warnings = warnings,
  artifacts = artifacts
))
Python

A variational autoencoder mapped 150 rows into 2 latent coordinates (2 in use); the mean squared reconstruction error is 0.133 per standardized column and the mean KL is 1.11 nats; 8 rows with a loss of at least 3.53 are flagged as anomalies. 150 rows generated from the prior differ from the data by a mean KS distance of 0.160.

Mean reconstruction error
0.1330
Mean KL (nats per row)
1.110
Active latent dimensions
2
Trustworthiness (k = 10)
0.9773
Anomalies
8

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

Assumptions

  • Latent dimensions in use — 2 of 2 latent dimensions vary across rows (variance of μ > 0.01).

Rows the model finds least typical

RankRowPer-row losssepal_lengthsepal_widthpetal_lengthpetal_width
11325.8707.9003.8006.4002
21185.5507.7003.8006.7002.200
3164.9025.7004.4001.5000.4000
41194.3427.7002.6006.9002.300
5424.0884.5002.3001.3000.3000
6613.918523.5001
7343.6055.5004.2001.4000.2000
81103.5307.2003.6006.1002.500
91233.2797.7002.8006.7002
10333.0565.2004.1001.5000.1000
11153.0305.80041.2000.2000
121362.7547.70036.1002.300
13632.68862.20041
141062.6617.60036.6002.100
15692.6166.2002.2004.5001.500
161202.55562.20051.500
171072.4914.9002.5004.5001.700
18942.42652.3003.3001
191372.3336.3003.4005.6002.400
201012.3246.3003.30062.500

Latent dimensions

DimensionMean KL (nats)Variance of μActive
10.86340.8815yes
20.24680.3660yes
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Variational autoencoder (latent map, anomalies and generated rows)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.vae 1.2.0 · spec dddd5c04a52df612
# Dataset: ml_iris (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os

import numpy as np
import pandas as pd

import codesplash as cs
from codesplash import ml as csml
from codesplash.deep import generative as gen  # twin of codesplashr::cs_deep_fit_vae (shared initial weights, Adam written out)
from codesplash.deep import unsupervised as du  # VaDE prior and the importance-weighted bound (twin of codesplashr::cs_deep_fit_vade)
from codesplash.ml import anomaly as csanom
from codesplash.ml import embed as csembed
from codesplash.synth import common as sy

# %% Data — standardized numbers (median-imputed), one-hot categories
IMPUTE = "median"
SCALE = "standard"
cs.check_finite_columns(pd.read_parquet("tests/parity/fixtures/ml_iris.parquet", columns=["sepal_length", "sepal_width", "petal_length", "petal_width"]), ["sepal_length", "sepal_width", "petal_length", "petal_width"])
from codesplash.deep import trainer as deep_trainer  # training options, live progress, checkpoints (twin: cs_deep_trainer_*)

deep_trainer.configure(
    {
        "optimizer": "default",
        "lr_schedule": "none",
        "warmup_epochs": 0,
        "grad_clip": 0,
        "ema_decay": 0,
        "swa_start": 0,
        "history_every_step": False,
        "profile": "parity",
        "checkpoint_every": None,
    },
    out_dir="target/academy-parity/run-8142/discover.vae/iris_map/out-python",
)
FEATURES = ["sepal_length", "sepal_width", "petal_length", "petal_width"]
df = pd.read_parquet("tests/parity/fixtures/ml_iris.parquet", columns=FEATURES)
warnings = []
design = csml.Design.for_frame(
    df,
    FEATURES,
    kinds={
        "sepal_length": "numeric",
        "sepal_width": "numeric",
        "petal_length": "numeric",
        "petal_width": "numeric",
    },
    levels={
    },
    impute=IMPUTE,
    scale=SCALE,
)
fitted = design.fit(df)
X = fitted.transform(df)  # numbers imputed / scaled; categories one-hot (missing → all zero)
rows = np.arange(len(df))
LABEL = "species"
if LABEL:
    df[LABEL] = pd.read_parquet("tests/parity/fixtures/ml_iris.parquet", columns=[LABEL])[LABEL]

# %% Variational autoencoder (PyTorch, float64, one thread): encoder → (μ, log σ²) → z = μ + σ·ε → decoder
HIDDEN = [int(u) for u in [8]]
LATENT = 2
BETA = 1
N_SAMPLES = 150
PRIOR = "normal"  # N(0, I), or a learned Gaussian mixture (VaDE)
IWAE = 0
if PRIOR == "mixture" and len(rows) <= 3:
    cs.cs_error("CS_E_TOO_FEW_ROWS", what="A 3-component mixture prior", min=3 + 1, n=len(rows))
if PRIOR == "mixture":
    fit = du.fit_vade(
        X, HIDDEN, LATENT, 3,
        activation="tanh",
        beta=BETA,
        epochs=200,
        lr=0.01,
        batch_size=None,
        weight_decay=0,
        n_samples=N_SAMPLES,
        pretrain_epochs=100,
        seed=42,
    )
else:
    fit = gen.fit_vae(
        X, HIDDEN, LATENT,
        activation="tanh",
        beta=BETA,
        epochs=200,
        lr=0.01,
        batch_size=None,
        weight_decay=0,
        n_samples=N_SAMPLES,
        seed=42,
    )
if not np.all(np.isfinite(fit["score"])):
    cs.cs_error("CS_E_NO_CONVERGENCE", what="Variational autoencoder training")
Z = fit["embedding"]  # posterior means μ (n × LATENT)
scores = fit["score"]  # squared reconstruction error at z = μ plus β × KL, per row
errors = fit["error"]  # mean squared reconstruction error per standardized column

# %% Anomalies by the per-row loss
RULE = "share"
flags, threshold = csanom.flag(scores, RULE, 0.05, 10)
order = np.lexsort((rows, -scores))  # largest loss first, ties by row

# %% Neighborhood preservation of the map (same rows in both engines)
sample = csembed.sample_rows(len(rows))
k_eval = min(10, len(sample) - 2)
trust = csembed.trustworthiness(X[sample], Z[sample], k_eval) if k_eval >= 1 else float("nan")  # undefined with fewer than 3 rows

# %% Mixture prior: each row's component at z = μ (canonical ids 1…k by size)
clusters = None
if PRIOR == "mixture":
    from codesplash.ml import cluster as csc

    clusters = csc.canonical(fit["cluster"])
    comp_of = {}
    for j in range(len(fit["pi"])):
        members = np.flatnonzero(fit["cluster"] == j)
        if len(members):
            comp_of[j] = int(clusters[members[0]])

# %% Importance-weighted bound on log p(x) (and the ELBO from the same draws)
bound = du.iwae_bound(X, fit, LATENT, "tanh", IWAE, 42) if IWAE > 0 else None

# %% Generated rows: decode prior draws back to the columns' units
gen_cols = gen.decode_design(fitted, fit["samples"]) if N_SAMPLES > 0 else {}
NUMERIC = [f for f in FEATURES if design.kinds[f] == "numeric"]
sample_ks = {}
for f in NUMERIC if N_SAMPLES > 0 else []:
    real = pd.to_numeric(df[f], errors="coerce").to_numpy(dtype=np.float64)
    sample_ks[f] = gen.ks_distance(real, gen_cols[f])

# %% Artifacts
out = csml.out_dir("target/academy-parity/run-8142/discover.vae/iris_map/out-python")
emb = pd.DataFrame({"row": rows.astype(np.int64), **{f"dim_{j + 1}": Z[:, j] for j in range(LATENT)}})
emb.to_parquet(os.path.join(out, "embedding.parquet"), index=False)
pd.DataFrame({"row": rows.astype(np.int64), "score": scores, "anomaly": flags, **({"cluster": clusters} if clusters is not None else {})}).to_parquet(
    os.path.join(out, "labels.parquet"), index=False
)
history = pd.DataFrame({
    "epoch": [h["epoch"] for h in fit["history"]],
    "loss": [h["loss"] for h in fit["history"]],
    "reconstruction": [h["recon"] for h in fit["history"]],
    "kl": [h["kl"] for h in fit["history"]],
})
history.to_parquet(os.path.join(out, "history.parquet"), index=False)
artifacts = [
    {"key": "embedding", "path": os.path.join(out, "embedding.parquet"), "format": "parquet"},
    {"key": "labels", "path": os.path.join(out, "labels.parquet"), "format": "parquet"},
    {"key": "history", "path": os.path.join(out, "history.parquet"), "format": "parquet"},
]
if N_SAMPLES > 0:
    pd.DataFrame({f: gen_cols[f] for f in FEATURES}).to_parquet(os.path.join(out, "samples.parquet"), index=False)
    artifacts.append({"key": "samples", "path": os.path.join(out, "samples.parquet"), "format": "parquet", "title": "Rows generated from the prior"})

# %% Result
active = int(fit["active"])
values = {
    "n": len(rows),
    "n_features": int(X.shape[1]),
    "latent_dim": LATENT,
    "recon_mse": float(np.mean(errors)),
    "kl": float(np.mean(fit["kl_row"])),
    "elbo_loss": float(np.mean(scores)),
    "active_dims": active,
    "error_check": csembed.checksum(scores, rows),
    "n_flagged": int(flags.sum()),
    "threshold": float(threshold),
    "final_loss": float(fit["history"][-1]["loss"]),
    "epochs_run": int(fit["epochs_run"]),
    "trustworthiness": trust,
    "n_samples": N_SAMPLES,
    "sample_ks_mean": float(np.mean(list(sample_ks.values()))) if sample_ks else float("nan"),
}
for j in range(LATENT):
    values[f"emb_check[{j + 1}]"] = csembed.checksum(Z[:, j], rows)
    values[f"kl_dim[{j + 1}]"] = float(fit["kl_dim"][j])
for f, v in sample_ks.items():
    values[f"sample_ks[{f}]"] = v
if clusters is not None:
    values["components"] = int(len(fit["pi"]))
    values["n_clusters"] = len(comp_of)
    for j, c in comp_of.items():
        values[f"pi[{c}]"] = float(fit["pi"][j])
        values[f"cluster_size[{c}]"] = int(np.sum(clusters == c))
if bound is not None:
    values["iwae_samples"] = IWAE
    values["iwae_bound"] = float(np.mean(bound["iwae"]))
    values["elbo_estimate"] = float(np.mean(bound["elbo"]))
    values["iwae_gap"] = values["iwae_bound"] - values["elbo_estimate"]
for rank, i in enumerate(order[:10], start=1):
    values[f"top_row[{rank}]"] = int(rows[i])
    values[f"top_score[{rank}]"] = float(scores[i])
table_rows = []
for rank, i in enumerate(order[:20], start=1):
    r = {"rank": rank, "row": int(rows[i]) + 1, "score": float(scores[i])}
    for f in FEATURES:
        v = df[f].iloc[rows[i]]
        r[f] = None if pd.isna(v) else (v if isinstance(v, (int, float)) else str(v))  # None, NaN, pd.NA, NaT
    table_rows.append(r)
dim_rows = [{"dim": j + 1, "kl": float(fit["kl_dim"][j]), "var_mu": float(fit["mu_var"][j]), "active": bool(fit["mu_var"][j] > 0.01)} for j in range(LATENT)]
pick = csembed.sample_rows(len(rows), 5000)
groups = [("All rows" if LABEL is None else ("(missing)" if pd.isna(v) else str(v))) for v in (df[LABEL].iloc[rows[pick]] if LABEL else [None] * len(pick))]
charts = []
if LATENT >= 2 and clusters is not None:
    _cent = sorted(comp_of, key=lambda j: comp_of[j])
    charts.append(cs.chart("latent", "cluster-scatter", "Latent means by mixture component (component means marked)", {
        "x": cs.col("Latent 1 (μ)", list(Z[pick, 0]) + [float(fit["mu_c"][j, 0]) for j in _cent], "numeric"),
        "y": cs.col("Latent 2 (μ)", list(Z[pick, 1]) + [float(fit["mu_c"][j, 1]) for j in _cent], "numeric"),
        "cluster": cs.col("Component", [str(c) for c in clusters[pick]] + [str(comp_of[j]) for j in _cent], "categorical",
                          levels=[str(c) for c in sorted(comp_of.values())]),
        "centroid": cs.col("Component mean", [False] * len(pick) + [True] * len(_cent), "boolean"),
    }, note=None if len(pick) == len(rows) else f"{len(pick):,} of {len(rows):,} rows shown."))
elif LATENT >= 2:
    charts.append(cs.chart("latent", "latent-prior", "Latent means against the N(0, I) prior", {
        "x": cs.col("Latent 1 (μ)", Z[pick, 0], "numeric"),
        "y": cs.col("Latent 2 (μ)", Z[pick, 1], "numeric"),
        "group": cs.col(LABEL or "Group", groups, "categorical"),
    }, note=None if len(pick) == len(rows) else f"{len(pick):,} of {len(rows):,} rows shown."))
charts.append(cs.chart("errors", "anomaly-scores", "Per-row loss (reconstruction + β·KL) distribution", {
    "score": cs.col("Per-row loss", scores, "numeric"),
    "anomaly": cs.col("Anomaly", [bool(x) for x in flags], "boolean"),
}, controls={"threshold": float(threshold)}))
ep = [h["epoch"] for h in fit["history"]]
charts.append(cs.chart("training", "training-components", "Training loss and its parts by epoch", {
    "x": cs.col("Epoch", ep * 3, "numeric"),
    "value": cs.col("Loss per row", [h["loss"] for h in fit["history"]] + [h["recon"] for h in fit["history"]] + [h["kl"] for h in fit["history"]], "numeric"),
    "component": cs.col("Part", ["total"] * len(ep) + ["reconstruction"] * len(ep) + ["KL"] * len(ep), "categorical", levels=["total", "reconstruction", "KL"]),
}))
if sample_ks:
    f0 = NUMERIC[0]
    xs, dens, src = sy.density_rows(pd.to_numeric(df[f0], errors="coerce").to_numpy(dtype=np.float64), np.asarray(gen_cols[f0], dtype=np.float64))
    if xs:
        charts.append(cs.chart("samples", "density-compare", f"{f0}: data vs rows generated from the prior", {
            "x": cs.col(f0, xs, "numeric"),
            "density": cs.col("Density", dens, "numeric"),
            "source": cs.col("Source", src, "categorical", levels=["real", "synthetic"]),
        }))
assumptions = [{
    "key": "active_units",
    "label": "Latent dimensions in use",
    "status": "pass" if active == LATENT else ("fail" if active == 0 else "warn"),
    "detail": f"{active} of {LATENT} latent dimension{'s' if LATENT != 1 else ''} vary across rows (variance of μ > 0.01)"
              + ("." if active == LATENT else "; the rest collapsed onto the prior and carry no information about the rows."),
}]
if active < LATENT:
    warnings.append(f"Posterior collapse: {LATENT - active} latent dimension{'s' if LATENT - active != 1 else ''} carry no information (KL ≈ 0). Lower β, shrink the bottleneck, or train longer.")
summary = (
    f"A variational autoencoder mapped {len(rows)} rows into {LATENT} latent coordinate{'s' if LATENT != 1 else ''} "
    f"({active} in use); the mean squared reconstruction error is {np.mean(errors):.3g} per standardized column and the mean KL is "
    f"{np.mean(fit['kl_row']):.3g} nats; {int(flags.sum())} rows with a loss of at least {threshold:.3g} are flagged as anomalies."
)
if sample_ks:
    summary += f" {N_SAMPLES} rows generated from the prior differ from the data by a mean KS distance of {values['sample_ks_mean']:.3f}."
if clusters is not None:
    summary += f" The mixture prior's {len(fit['pi'])} components hold {len(comp_of)} cluster{'s' if len(comp_of) != 1 else ''} of rows."
if bound is not None:
    summary += f" The importance-weighted bound with {IWAE} draws is {values['iwae_bound']:.4g} nats per row ({values['iwae_gap']:.3g} above the ELBO estimate)."
extra_stats = []
if bound is not None:
    extra_stats.append({"key": "iwae_bound", "label": f"Log-likelihood bound (IWAE, {IWAE} draws)", "value": values["iwae_bound"]})
extra_tables = []
if clusters is not None:
    extra_tables.append({
        "key": "components",
        "title": "Mixture prior components",
        "columns": [{"key": "cluster", "label": "Component", "type": "integer"}, {"key": "size", "label": "Rows", "type": "integer"},
                    {"key": "weight", "label": "Prior weight", "type": "number"}]
                   + [{"key": f"mu_{d + 1}", "label": f"Mean {d + 1}", "type": "number"} for d in range(LATENT)],
        "rows": [{"cluster": comp_of[j], "size": int(np.sum(clusters == comp_of[j])), "weight": float(fit["pi"][j]),
                  **{f"mu_{d + 1}": float(fit["mu_c"][j, d]) for d in range(LATENT)}} for j in sorted(comp_of, key=lambda j: comp_of[j])],
    })
cs.publish({
    "title": "Variational autoencoder (latent map, anomalies and generated rows)",
    "engine": cs.engine_info("torch", "numpy", "pandas"),
    "n": len(rows),
    "summary": summary,
    "statistics": [
        {"key": "recon_mse", "label": "Mean reconstruction error", "value": float(np.mean(errors))},
        {"key": "kl", "label": "Mean KL (nats per row)", "value": float(np.mean(fit["kl_row"]))},
        {"key": "active_dims", "label": "Active latent dimensions", "value": active, "format": "integer"},
        {"key": "trustworthiness", "label": f"Trustworthiness (k = {k_eval})", "value": trust},
        {"key": "n_flagged", "label": "Anomalies", "value": int(flags.sum()), "format": "integer"},
    ] + extra_stats,
    "tables": [
        {
            "key": "top",
            "title": "Rows the model finds least typical",
            "columns": [{"key": "rank", "label": "Rank", "type": "integer"}, {"key": "row", "label": "Row", "type": "integer"},
                        {"key": "score", "label": "Per-row loss", "type": "number"}] + [{"key": f, "label": f} for f in FEATURES],
            "rows": table_rows,
        },
        {
            "key": "latent",
            "title": "Latent dimensions",
            "columns": [{"key": "dim", "label": "Dimension", "type": "integer"}, {"key": "kl", "label": "Mean KL (nats)", "type": "number"},
                        {"key": "var_mu", "label": "Variance of μ", "type": "number"}, {"key": "active", "label": "Active", "type": "boolean"}],
            "rows": dim_rows,
        },
    ] + extra_tables,
    "charts": charts,
    "assumptions": assumptions,
    "values": values,
    "warnings": warnings,
    "artifacts": artifacts,
})

Each point is a flower's posterior mean. Here 2 of 2 dimensions are active, and the mean KL is 1.11 nats per row. Do the species fill the rings, or leave holes? Holes are where generated rows will look least like real flowers.

04

Generate, then check

Read

Because its latent space is close to a standard normal, a VAE can generate rowsSampling from the priorGenerating new rows by drawing latent codes from N(0, I) and decoding them, which a smooth VAE latent space allows.: draw codes from N(0, I) and decode them. The result card compares the generated numbers with the real ones. On iris, the mean Kolmogorov–Smirnov distance is 0.16. For a table you mean to share, use the Synthetic studio, which keeps a holdout and scores privacy.

05

Learning by telling rows apart

Explore

SCARF makes a second view of each row by swapping featuresRandom feature corruptionReplacing a random share of a row's features with the same features from random other rows, to make a second view of it. with random other rows. The InfoNCE lossInfoNCE lossA loss that asks each row to pick out its own corrupted view among the views of every row in the batch. rewards picking each row's own view out of the batch. Run it on the penguins, with species used only for color.

Contrastive representation (SCARF)Recorded · Python and R agreeRecorded 2026-11-25 · 19 values compared
R

A SCARF contrastive encoder turned 344 rows (6 features) into 8-dimensional representations (final InfoNCE loss 3.901); neighborhoods are kept with trustworthiness 0.981. A 5-nearest-neighbor probe recovers species for 98.3% of rows (98.8% on the raw columns).

Final InfoNCE loss
3.901
Trustworthiness (k = 10)
0.9807
Alignment (lower = views closer)
1.049
Uniformity (lower = more spread)
−1.514
5-NN probe accuracy (species)
98.3%

Plots

Contrastive representation (principal components 1 and 2)Which rows group together, and how well separated are the groups?
View data
speciesComponent 1Component 2
Adelie2.774−1.047
Adelie1.9150.9130
Adelie1.7370.7030
Adelie1.223−0.5208
Adelie2.3980.7307
Adelie2.956−1.940
Adelie2.2080.9186
Adelie2.202−2.159
Adelie2.042−0.1045
Adelie2.501−1.059
Adelie1.7860.0384
Adelie2.0700.2609
Adelie2.0200.7916
Adelie3.030−2.232
Adelie2.725−2.541
Adelie2.2691.018
Adelie2.0990.6687
Adelie2.068−2.496
Adelie2.6510.9900
Adelie2.310−2.618
Adelie1.7401.707
Adelie2.039−0.2494
Adelie1.2501.983
Adelie1.506−0.2852
Adelie1.601−0.1191
Adelie1.2311.961
Adelie1.825−0.2493
Adelie1.1071.849
Adelie1.8941.726
Adelie1.734−0.3572
Adelie1.5681.551
Adelie2.251−0.3916
Adelie1.6241.375
Adelie1.983−0.6697
Adelie0.96981.364
Adelie1.553−2.436
Adelie2.011−1.594
Adelie1.7161.386
Adelie2.2671.418
Adelie1.615−1.332
Adelie2.0421.448
Adelie1.462−0.9915
Adelie2.0261.413
Adelie0.8182−1.880
Adelie1.5731.424
Adelie1.345−1.448
Adelie2.450−0.3963
Adelie2.2770.4321
Adelie1.4761.368
Adelie1.655−2.335
Adelie0.91921.819
Adelie1.112−0.8849
Adelie0.93901.951
Adelie0.5064−1.033
Adelie1.4081.915
Adelie1.230−0.4059
Adelie0.82331.800
Adelie1.120−0.5507
Adelie1.0851.582
Adelie1.310−0.5862

First 60 of 344 rows.

InfoNCE loss by epochIs the network still learning, and which part of its loss moves?
View data
PartLossEpoch
InfoNCE4.0241
InfoNCE4.0252
InfoNCE4.0363
InfoNCE3.9854
InfoNCE4.0155
InfoNCE3.9646
InfoNCE3.9797
InfoNCE3.9818
InfoNCE3.9529
InfoNCE3.95610
InfoNCE3.98311
InfoNCE3.92112
InfoNCE3.94613
InfoNCE3.94114
InfoNCE3.96215
InfoNCE3.96816
InfoNCE3.92117
InfoNCE3.93618
InfoNCE3.92319
InfoNCE3.93820
InfoNCE3.93021
InfoNCE3.92822
InfoNCE3.93623
InfoNCE3.90724
InfoNCE3.95425
InfoNCE3.87726
InfoNCE3.93527
InfoNCE3.92128
InfoNCE3.90129
InfoNCE3.91030
InfoNCE3.90831
InfoNCE3.91532
InfoNCE3.87433
InfoNCE3.88234
InfoNCE3.93035
InfoNCE3.90036
InfoNCE3.89637
InfoNCE3.90738
InfoNCE3.95239
InfoNCE3.91540
InfoNCE3.91841
InfoNCE3.88542
InfoNCE3.90243
InfoNCE3.89344
InfoNCE3.89245
InfoNCE3.90346
InfoNCE3.90447
InfoNCE3.90748
InfoNCE3.87749
InfoNCE3.90650
InfoNCE3.93751
InfoNCE3.88652
InfoNCE3.92753
InfoNCE3.86154
InfoNCE3.87555
InfoNCE3.89456
InfoNCE3.88757
InfoNCE3.89258
InfoNCE3.86159
InfoNCE3.90160

Assumptions

  • The representation uses several directions — The first principal direction holds 59% of the representation's variance.
  • Neighbors share the label at least as often as in the raw data — 5-nearest-neighbor accuracy for species: 98.3% on the representation vs 98.8% on the standardized columns.
The exact R script · R R version 4.5.1 (2025-06-13)
# Contrastive representation (SCARF)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.contrastive 1.3.0 · spec 93f6670c35f62417
# 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)  # cs_deep_fit_scarf: SCARF contrastive encoder (twin of codesplash.deep.generative)

# %% Data — standardized numbers (median-imputed), one-hot categories
IMPUTE <- "median"
SCALE <- "standard"
# Training options, live progress and checkpoints (twin: codesplash.deep.trainer.configure).
cs_deep_trainer_configure(list(
  optimizer = "default",
  lr_schedule = "none",
  warmup_epochs = 0,
  grad_clip = 0,
  ema_decay = 0,
  swa_start = 0,
  history_every_step = FALSE,
  profile = "parity",
  checkpoint_every = NULL
), out_dir = "target/academy-parity/run-8142/discover.contrastive/penguins_probe/out-r")
FEATURES <- c("island", "bill_len", "bill_dep", "flipper_len", "body_mass", "sex")
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_penguins.parquet", col_select = FEATURES))
warnings <- list()
design <- cs_ml_design(
  df, FEATURES,
  kinds = list(
    island = "categorical",
    bill_len = "numeric",
    bill_dep = "numeric",
    flipper_len = "numeric",
    body_mass = "numeric",
    sex = "categorical"
  ),
  levels = list(
    island = c("Biscoe", "Dream", "Torgersen"),
    sex = c("female", "male")
  ),
  impute = IMPUTE,
  scale = SCALE
)
fitted <- cs_ml_design_fit(design, df)
X <- unname(cs_ml_design_apply(fitted, df))  # numbers imputed / scaled; categories one-hot (missing -> all zero)
rows <- seq_len(nrow(df)) - 1L
LABEL <- "species"
if (!is.null(LABEL)) df[[LABEL]] <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_penguins.parquet", col_select = LABEL))[[LABEL]]
groups <- cs_deep_feature_groups(fitted)  # design columns of each feature: corruption swaps whole features
if (length(rows) < 3L) cs_error("CS_E_TOO_FEW_ROWS", what = "Contrastive representation", min = 3L, n = length(rows))  # map, trustworthiness, probe

# %% SCARF (torch for R, float64, one thread): corrupt round(c * P) features per row from other rows, InfoNCE on the projections
HIDDEN <- as.integer(unlist(c(32)))
EMB <- as.integer(8)
fit <- cs_deep_fit_scarf(
  X, groups, HIDDEN, EMB,
  activation = "relu",
  corruption = 0.6,
  temperature = 1,
  epochs = as.integer(60),
  lr = 0.001,
  batch_size = 64,
  weight_decay = 0,
  seed = 42
)
E <- fit$embedding  # encoder output (the representation), n x EMB
P2 <- cs_deep_pca2(E)  # its first two principal components, for the map

# %% How good is the representation? Neighborhoods, alignment / uniformity, and a label probe
sample <- cs_ml_sample_rows(length(rows))
k_eval <- min(10L, length(sample) - 2L)
trust <- cs_ml_trustworthiness(X[sample, , drop = FALSE], E[sample, , drop = FALSE], k_eval)
unif <- cs_deep_uniformity(fit$projection[sample, , drop = FALSE])
labels <- NULL
if (!is.null(LABEL)) labels <- as.character(df[[LABEL]][rows[sample] + 1L])
probe <- if (!is.null(labels)) cs_deep_knn_probe(E[sample, , drop = FALSE], labels) else NaN
probe_raw <- if (!is.null(labels)) cs_deep_knn_probe(X[sample, , drop = FALSE], labels) else NaN
Ec <- sweep(E, 2, colMeans(E))
ev <- if (EMB > 1L) sort(eigen(crossprod(Ec) / nrow(E), symmetric = TRUE, only.values = TRUE)$values, decreasing = TRUE) else mean(Ec[, 1]^2)
top_share <- if (sum(ev) > 0) ev[1] / sum(ev) else 1

# %% Artifacts
out <- cs_ml_out_dir("target/academy-parity/run-8142/discover.contrastive/penguins_probe/out-r")
emb <- data.frame(row = as.integer(rows))
for (j in seq_len(EMB)) emb[[paste0("dim_", j)]] <- E[, j]
nanoparquet::write_parquet(emb, file.path(out, "embedding.parquet"))
hist <- data.frame(epoch = vapply(fit$history, function(h) as.numeric(h$epoch), numeric(1)),
                   loss = vapply(fit$history, function(h) h$loss, numeric(1)))
nanoparquet::write_parquet(hist, file.path(out, "history.parquet"))

# %% Result
values <- list(
  n = length(rows), n_features = length(groups), embedding_dim = EMB, final_loss = hist$loss[nrow(hist)],
  epochs_run = fit$epochs_run, trustworthiness = trust, alignment = fit$alignment, uniformity = unif,
  top_pc_share = top_share, probe_acc = probe, probe_acc_raw = probe_raw
)
for (j in seq_len(EMB)) values[[sprintf("emb_check[%d]", j)]] <- cs_ml_checksum(E[, j], rows)
pick <- cs_ml_sample_rows(length(rows), 5000)
grp <- if (is.null(LABEL)) rep("All rows", length(pick)) else {
  g <- df[[LABEL]][rows[pick] + 1L]
  ifelse(is.na(g), "(missing)", as.character(g))
}
charts <- list(cs_chart("map", "cluster-scatter", "Contrastive representation (principal components 1 and 2)", list(
  x = cs_col("Component 1", P2[pick, 1], "numeric"),
  y = cs_col("Component 2", P2[pick, 2], "numeric"),
  cluster = cs_col(if (is.null(LABEL)) "Group" else LABEL, grp, "categorical")
), note = if (length(pick) == length(rows)) NULL else sprintf("%s of %s rows shown.", format(length(pick), big.mark = ","), format(length(rows), big.mark = ","))))
charts[[2]] <- cs_chart("training", "training-components", "InfoNCE loss by epoch", list(
  x = cs_col("Epoch", hist$epoch, "numeric"),
  value = cs_col("Loss", hist$loss, "numeric"),
  component = cs_col("Part", rep("InfoNCE", nrow(hist)), "categorical")
))
collapsed <- EMB > 1L && top_share > 0.9
assumptions <- list(list(
  key = "collapse", label = "The representation uses several directions",
  status = if (collapsed) "warn" else "pass",
  detail = paste0(sprintf("The first principal direction holds %.0f%% of the representation's variance", 100 * top_share),
                  if (collapsed) " — nearly everything lies on one line (dimensional collapse)." else ".")
))
if (!is.null(LABEL) && !is.nan(probe) && !is.nan(probe_raw)) {
  assumptions[[2]] <- list(
    key = "probe", label = "Neighbors share the label at least as often as in the raw data",
    status = if (probe < probe_raw - 0.05) "warn" else "pass",
    detail = sprintf("5-nearest-neighbor accuracy for %s: %.1f%% on the representation vs %.1f%% on the standardized columns.", LABEL, 100 * probe, 100 * probe_raw)
  )
}
summary <- sprintf("A SCARF contrastive encoder turned %d rows (%d features) into %d-dimensional representations (final InfoNCE loss %.3f); neighborhoods are kept with trustworthiness %.3f.",
                   length(rows), length(groups), EMB, values$final_loss, trust)
if (!is.null(LABEL) && !is.nan(probe)) summary <- paste0(summary, sprintf(" A 5-nearest-neighbor probe recovers %s for %.1f%% of rows (%.1f%% on the raw columns).", LABEL, 100 * probe, 100 * probe_raw))
statistics <- list(
  list(key = "final_loss", label = "Final InfoNCE loss", value = values$final_loss),
  list(key = "trustworthiness", label = sprintf("Trustworthiness (k = %d)", k_eval), value = trust),
  list(key = "alignment", label = "Alignment (lower = views closer)", value = values$alignment),
  list(key = "uniformity", label = "Uniformity (lower = more spread)", value = unif)
)
if (!is.null(LABEL)) statistics[[5]] <- list(key = "probe_acc", label = sprintf("5-NN probe accuracy (%s)", LABEL), value = probe, format = "percent")
cs_publish(list(
  title = "Contrastive representation (SCARF)",
  engine = cs_engine_info("torch", "nanoparquet"),
  n = length(rows),
  summary = summary,
  statistics = statistics,
  charts = charts,
  assumptions = assumptions,
  values = values,
  warnings = warnings,
  artifacts = list(
    list(key = "embedding", path = file.path(out, "embedding.parquet"), format = "parquet"),
    list(key = "history", path = file.path(out, "history.parquet"), format = "parquet")
  )
))
Python

A SCARF contrastive encoder turned 344 rows (6 features) into 8-dimensional representations (final InfoNCE loss 3.901); neighborhoods are kept with trustworthiness 0.981. A 5-nearest-neighbor probe recovers species for 98.3% of rows (98.8% on the raw columns).

Final InfoNCE loss
3.901
Trustworthiness (k = 10)
0.9807
Alignment (lower = views closer)
1.049
Uniformity (lower = more spread)
−1.514
5-NN probe accuracy (species)
98.3%

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

Assumptions

  • The representation uses several directions — The first principal direction holds 59% of the representation's variance.
  • Neighbors share the label at least as often as in the raw data — 5-nearest-neighbor accuracy for species: 98.3% on the representation vs 98.8% on the standardized columns.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Contrastive representation (SCARF)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.contrastive 1.3.0 · spec 93f6670c35f62417
# 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 import ml as csml
from codesplash.deep import generative as gen  # twin of codesplashr::cs_deep_fit_scarf (shared weights and corruption draws)
from codesplash.ml import embed as csembed

# %% Data — standardized numbers (median-imputed), one-hot categories
IMPUTE = "median"
SCALE = "standard"
from codesplash.deep import trainer as deep_trainer  # training options, live progress, checkpoints (twin: cs_deep_trainer_*)

deep_trainer.configure(
    {
        "optimizer": "default",
        "lr_schedule": "none",
        "warmup_epochs": 0,
        "grad_clip": 0,
        "ema_decay": 0,
        "swa_start": 0,
        "history_every_step": False,
        "profile": "parity",
        "checkpoint_every": None,
    },
    out_dir="target/academy-parity/run-8142/discover.contrastive/penguins_probe/out-python",
)
FEATURES = ["island", "bill_len", "bill_dep", "flipper_len", "body_mass", "sex"]
df = pd.read_parquet("tests/parity/fixtures/ml_penguins.parquet", columns=FEATURES)
warnings = []
design = csml.Design.for_frame(
    df,
    FEATURES,
    kinds={
        "island": "categorical",
        "bill_len": "numeric",
        "bill_dep": "numeric",
        "flipper_len": "numeric",
        "body_mass": "numeric",
        "sex": "categorical",
    },
    levels={
        "island": ["Biscoe", "Dream", "Torgersen"],
        "sex": ["female", "male"],
    },
    impute=IMPUTE,
    scale=SCALE,
)
fitted = design.fit(df)
X = fitted.transform(df)  # numbers imputed / scaled; categories one-hot (missing → all zero)
rows = np.arange(len(df))
LABEL = "species"
if LABEL:
    df[LABEL] = pd.read_parquet("tests/parity/fixtures/ml_penguins.parquet", columns=[LABEL])[LABEL]
groups = gen.feature_groups(fitted)  # design columns of each feature: corruption swaps whole features
if len(rows) < 3:  # the map, trustworthiness (k = n − 2) and the probe need three rows
    cs.cs_error("CS_E_TOO_FEW_ROWS", what="Contrastive representation", min=3, n=len(rows))

# %% SCARF (PyTorch, float64, one thread): corrupt round(c·P) features per row from other rows, InfoNCE on the projections
HIDDEN = [int(u) for u in [32]]
EMB = 8
fit = gen.fit_scarf(
    X, groups, HIDDEN, EMB,
    activation="relu",
    corruption=0.6,
    temperature=1,
    epochs=60,
    lr=0.001,
    batch_size=64,
    weight_decay=0,
    seed=42,
)
E = fit["embedding"]  # encoder output (the representation), n × EMB
P2 = gen.pca2(E)  # its first two principal components, for the map

# %% How good is the representation? Neighborhoods, alignment / uniformity, and a label probe
sample = csembed.sample_rows(len(rows))
k_eval = min(10, len(sample) - 2)
trust = csembed.trustworthiness(X[sample], E[sample], k_eval)
unif = gen.uniformity(fit["projection"][sample])
labels = None
if LABEL:
    labels = [None if pd.isna(v) else str(v) for v in df[LABEL].iloc[rows[sample]]]
probe = gen.knn_probe(E[sample], labels) if labels else float("nan")
probe_raw = gen.knn_probe(X[sample], labels) if labels else float("nan")
Ec = E - E.mean(axis=0)
ev = np.sort(np.linalg.eigvalsh(Ec.T @ Ec / len(E)))[::-1] if EMB > 1 else np.array([float(np.mean(Ec[:, 0] ** 2))])
top_share = float(ev[0] / ev.sum()) if ev.sum() > 0 else 1.0

# %% Artifacts
out = csml.out_dir("target/academy-parity/run-8142/discover.contrastive/penguins_probe/out-python")
emb = pd.DataFrame({"row": rows.astype(np.int64), **{f"dim_{j + 1}": E[:, j] for j in range(EMB)}})
emb.to_parquet(os.path.join(out, "embedding.parquet"), index=False)
history = pd.DataFrame({"epoch": [h["epoch"] for h in fit["history"]], "loss": [h["loss"] for h in fit["history"]]})
history.to_parquet(os.path.join(out, "history.parquet"), index=False)

# %% Result
values = {
    "n": len(rows),
    "n_features": len(groups),
    "embedding_dim": EMB,
    "final_loss": float(fit["history"][-1]["loss"]),
    "epochs_run": int(fit["epochs_run"]),
    "trustworthiness": trust,
    "alignment": float(fit["alignment"]),
    "uniformity": unif,
    "top_pc_share": top_share,
    "probe_acc": probe,
    "probe_acc_raw": probe_raw,
}
for j in range(EMB):
    values[f"emb_check[{j + 1}]"] = csembed.checksum(E[:, j], rows)
pick = csembed.sample_rows(len(rows), 5000)
grp = [("All rows" if LABEL is None else ("(missing)" if pd.isna(v) else str(v))) for v in (df[LABEL].iloc[rows[pick]] if LABEL else [None] * len(pick))]
charts = [cs.chart("map", "cluster-scatter", "Contrastive representation (principal components 1 and 2)", {
    "x": cs.col("Component 1", P2[pick, 0], "numeric"),
    "y": cs.col("Component 2", P2[pick, 1], "numeric"),
    "cluster": cs.col(LABEL or "Group", grp, "categorical"),
}, note=None if len(pick) == len(rows) else f"{len(pick):,} of {len(rows):,} rows shown.")]
ep = [h["epoch"] for h in fit["history"]]
charts.append(cs.chart("training", "training-components", "InfoNCE loss by epoch", {
    "x": cs.col("Epoch", ep, "numeric"),
    "value": cs.col("Loss", [h["loss"] for h in fit["history"]], "numeric"),
    "component": cs.col("Part", ["InfoNCE"] * len(ep), "categorical"),
}))
assumptions = [{
    "key": "collapse",
    "label": "The representation uses several directions",
    "status": "warn" if (EMB > 1 and top_share > 0.9) else "pass",
    "detail": f"The first principal direction holds {top_share:.0%} of the representation's variance"
              + (" — nearly everything lies on one line (dimensional collapse)." if EMB > 1 and top_share > 0.9 else "."),
}]
if LABEL and probe == probe and probe_raw == probe_raw:
    assumptions.append({
        "key": "probe",
        "label": "Neighbors share the label at least as often as in the raw data",
        "status": "warn" if probe < probe_raw - 0.05 else "pass",
        "detail": f"5-nearest-neighbor accuracy for {LABEL}: {probe:.1%} on the representation vs {probe_raw:.1%} on the standardized columns.",
    })
summary = (
    f"A SCARF contrastive encoder turned {len(rows)} rows ({len(groups)} features) into {EMB}-dimensional representations "
    f"(final InfoNCE loss {values['final_loss']:.3f}); neighborhoods are kept with trustworthiness {trust:.3f}."
)
if LABEL and probe == probe:
    summary += f" A 5-nearest-neighbor probe recovers {LABEL} for {probe:.1%} of rows ({probe_raw:.1%} on the raw columns)."
cs.publish({
    "title": "Contrastive representation (SCARF)",
    "engine": cs.engine_info("torch", "numpy", "pandas"),
    "n": len(rows),
    "summary": summary,
    "statistics": [
        {"key": "final_loss", "label": "Final InfoNCE loss", "value": values["final_loss"]},
        {"key": "trustworthiness", "label": f"Trustworthiness (k = {k_eval})", "value": trust},
        {"key": "alignment", "label": "Alignment (lower = views closer)", "value": values["alignment"]},
        {"key": "uniformity", "label": "Uniformity (lower = more spread)", "value": unif},
    ] +([{"key": "probe_acc", "label": f"5-NN probe accuracy ({LABEL})", "value": probe, "format": "percent"}] if LABEL else []),
    "charts": charts,
    "assumptions": assumptions,
    "values": values,
    "warnings": warnings,
    "artifacts": [
        {"key": "embedding", "path": os.path.join(out, "embedding.parquet"), "format": "parquet"},
        {"key": "history", "path": os.path.join(out, "history.parquet"), "format": "parquet"},
    ],
})

A nearest-neighbor probeNearest-neighbor probeHow often a row's nearest neighbors in a representation share its label — a check that the representation kept the label. asks how often a penguin's five nearest neighbors share its species: 98.3% on the representation, against 98.8% on the raw columns. What does that comparison tell you about what the encoder kept?

06

When is a learned map worth it?

Reflect

These methods have many settings and train slowly. PCA or UMAP often show the same structure in seconds. A learned representation earns its place when you'll reuse it, as features for a model, for clustering, or to generate rows.

Name one dataset of yours where you'd try a learned representation, and the check you'd run before trusting it.

07

Check your understanding

Checkpoint

Check yourself

A VAE reports 1 active dimension out of 4. What does that mean?

Show the answer

Answer: a

A collapsed dimension's posterior mean doesn't vary across rows. The other dimension still works; you can lower β or shrink the bottleneck if you need more.

Check yourself

How does SCARF use a label column when you give one?

Show the answer

Answer: a

SCARF is self-supervised: its training signal is matching each row with its corrupted view. The label only checks the result afterwards.

08

Do it on your own data

In the app

In Discover, choose Map the data, then the variational autoencoder or the contrastive representation. The VAE also appears under Spot anomalies, scoring rows by their loss.

Python
import pandas as pd
from codesplash import ml as csml
from codesplash.deep import generative as gen

df = pd.read_csv("iris.csv")
F = ["sepal_length", "sepal_width", "petal_length", "petal_width"]
design = csml.Design.for_frame(df, F, kinds={f: "numeric" for f in F}, levels={}, impute="median", scale="standard")
X = design.fit(df).transform(df)
fit = gen.fit_vae(X, [8], 2, activation="tanh", epochs=200, lr=0.01, n_samples=0, seed=42)
print(fit["active"], fit["kl_dim"])
R
library(codesplashr)

df <- read.csv("iris.csv")
F <- c("sepal_length", "sepal_width", "petal_length", "petal_width")
design <- cs_ml_design(df, F, kinds = setNames(as.list(rep("numeric", 4)), F), levels = list(), impute = "median", scale = "standard")
X <- unname(cs_ml_design_apply(cs_ml_design_fit(design, df), df))
fit <- cs_deep_fit_vae(X, 8L, 2L, activation = "tanh", epochs = 200L, lr = 0.01, n_samples = 0L, seed = 42)
print(c(fit$active, fit$kl_dim))
09

Recap

Recap
  • A VAE balances rebuilding rows against keeping codes near N(0, I); β sets the balance.
  • Collapsed dimensions carry no information; the result card counts the active ones.
  • SCARF learns by matching rows with corrupted copies; the label only checks the result.
  • Check any learned representation with trustworthiness and, when you have one, a label probe.

Concepts in this lesson