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.
What runs in CodeSplash
- Variational autoencoder (latent map, anomalies and generated rows) Experimental
- Contrastive representation (SCARF) Experimental
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
A description the network learns
ReadPCA 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.
Two forces in one loss
PredictPredict 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 β?
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.
Read a VAE's latent map
ExploreRun the VAE on iris and open Latent means against the N(0, I) prior.
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
View data
| species | Latent 1 (μ) | Latent 2 (μ) |
|---|---|---|
| setosa | 1.176 | 0.3987 |
| setosa | 1.151 | −0.3919 |
| setosa | 1.291 | −0.1713 |
| setosa | 1.287 | −0.3178 |
| setosa | 1.216 | 0.4858 |
| setosa | 0.9957 | 1.062 |
| setosa | 1.326 | 0.0476 |
| setosa | 1.196 | 0.2171 |
| setosa | 1.299 | −0.6013 |
| setosa | 1.195 | −0.2248 |
| setosa | 1.062 | 0.8139 |
| setosa | 1.261 | 0.1357 |
| setosa | 1.212 | −0.3913 |
| setosa | 1.401 | −0.4933 |
| setosa | 0.9543 | 1.329 |
| setosa | 0.8756 | 1.628 |
| setosa | 1.038 | 1.057 |
| setosa | 1.157 | 0.3926 |
| setosa | 0.9139 | 1.076 |
| setosa | 1.147 | 0.7914 |
| setosa | 1.012 | 0.3939 |
| setosa | 1.132 | 0.6660 |
| setosa | 1.376 | 0.2936 |
| setosa | 1.053 | 0.0777 |
| setosa | 1.232 | 0.1401 |
| setosa | 1.090 | −0.3562 |
| setosa | 1.145 | 0.2015 |
| setosa | 1.129 | 0.4465 |
| setosa | 1.126 | 0.2994 |
| setosa | 1.267 | −0.1591 |
| setosa | 1.205 | −0.2643 |
| setosa | 0.9870 | 0.3600 |
| setosa | 1.113 | 1.155 |
| setosa | 1.005 | 1.393 |
| setosa | 1.175 | −0.2433 |
| setosa | 1.187 | −0.0832 |
| setosa | 1.025 | 0.5760 |
| setosa | 1.268 | 0.4352 |
| setosa | 1.340 | −0.4887 |
| setosa | 1.157 | 0.2596 |
| setosa | 1.203 | 0.3455 |
| setosa | 0.9491 | −1.270 |
| setosa | 1.387 | −0.2521 |
| setosa | 1.109 | 0.3276 |
| setosa | 1.084 | 0.7959 |
| setosa | 1.170 | −0.4365 |
| setosa | 1.155 | 0.7866 |
| setosa | 1.318 | −0.1957 |
| setosa | 1.099 | 0.7653 |
| setosa | 1.191 | 0.0722 |
| versicolor | −0.7822 | 0.5444 |
| versicolor | −0.5493 | 0.3661 |
| versicolor | −0.8450 | 0.3862 |
| versicolor | −0.0362 | −1.121 |
| versicolor | −0.6487 | −0.1629 |
| versicolor | −0.1764 | −0.4722 |
| versicolor | −0.5748 | 0.4935 |
| versicolor | 0.4366 | −1.172 |
| versicolor | −0.5992 | 0.0041 |
| versicolor | 0.1325 | −0.8017 |
First 60 of 150 rows.
View data
| Anomaly | Per-row loss |
|---|---|
| false | 1.315 |
| false | 1.521 |
| false | 1.439 |
| false | 1.607 |
| false | 1.447 |
| false | 2.103 |
| false | 1.513 |
| false | 1.256 |
| false | 2.173 |
| false | 1.447 |
| false | 1.670 |
| false | 1.346 |
| false | 1.629 |
| false | 2.195 |
| false | 3.030 |
| true | 4.902 |
| false | 2.189 |
| false | 1.291 |
| false | 2.056 |
| false | 1.816 |
| false | 1.316 |
| false | 1.577 |
| false | 1.776 |
| false | 1.197 |
| false | 1.390 |
| false | 1.463 |
| false | 1.235 |
| false | 1.315 |
| false | 1.268 |
| false | 1.437 |
| false | 1.440 |
| false | 1.268 |
| false | 3.056 |
| true | 3.605 |
| false | 1.389 |
| false | 1.322 |
| false | 1.514 |
| false | 1.527 |
| false | 1.994 |
| false | 1.245 |
| false | 1.321 |
| true | 4.088 |
| false | 1.772 |
| false | 1.399 |
| false | 1.808 |
| false | 1.546 |
| false | 1.840 |
| false | 1.524 |
| false | 1.625 |
| false | 1.251 |
| false | 1.800 |
| false | 1.094 |
| false | 1.385 |
| false | 1.944 |
| false | 0.9980 |
| false | 0.8023 |
| false | 1.252 |
| false | 2.226 |
| false | 1.176 |
| false | 1.287 |
First 60 of 150 rows.
View data
| Part | Loss per row | Epoch |
|---|---|---|
| total | 5.289 | 1 |
| total | 4.931 | 2 |
| total | 4.907 | 3 |
| total | 4.597 | 4 |
| total | 4.359 | 5 |
| total | 4.254 | 6 |
| total | 4.013 | 7 |
| total | 4.176 | 8 |
| total | 3.925 | 9 |
| total | 3.803 | 10 |
| total | 3.695 | 11 |
| total | 3.666 | 12 |
| total | 3.498 | 13 |
| total | 3.508 | 14 |
| total | 3.288 | 15 |
| total | 3.405 | 16 |
| total | 3.289 | 17 |
| total | 3.099 | 18 |
| total | 3.077 | 19 |
| total | 2.741 | 20 |
| total | 2.695 | 21 |
| total | 2.857 | 22 |
| total | 2.831 | 23 |
| total | 2.777 | 24 |
| total | 2.936 | 25 |
| total | 3.031 | 26 |
| total | 2.904 | 27 |
| total | 2.756 | 28 |
| total | 2.762 | 29 |
| total | 2.678 | 30 |
| total | 2.718 | 31 |
| total | 2.730 | 32 |
| total | 2.485 | 33 |
| total | 2.564 | 34 |
| total | 2.607 | 35 |
| total | 2.527 | 36 |
| total | 2.674 | 37 |
| total | 2.597 | 38 |
| total | 2.680 | 39 |
| total | 2.474 | 40 |
| total | 2.685 | 41 |
| total | 2.623 | 42 |
| total | 2.750 | 43 |
| total | 2.712 | 44 |
| total | 2.497 | 45 |
| total | 2.564 | 46 |
| total | 2.446 | 47 |
| total | 2.577 | 48 |
| total | 2.516 | 49 |
| total | 2.452 | 50 |
| total | 2.507 | 51 |
| total | 2.410 | 52 |
| total | 2.433 | 53 |
| total | 2.332 | 54 |
| total | 2.369 | 55 |
| total | 2.496 | 56 |
| total | 2.520 | 57 |
| total | 2.474 | 58 |
| total | 2.656 | 59 |
| total | 2.405 | 60 |
First 60 of 600 rows.
View data
| Density | Source | sepal_length |
|---|---|---|
| 0.2222 | real | 4.360 |
| 0.0556 | real | 4.480 |
| 0.2222 | real | 4.600 |
| 0.1111 | real | 4.720 |
| 0.2778 | real | 4.840 |
| 0.8889 | real | 4.960 |
| 0.5000 | real | 5.080 |
| 0.2222 | real | 5.200 |
| 0.0556 | real | 5.320 |
| 0.3333 | real | 5.440 |
| 0.7222 | real | 5.560 |
| 0.4444 | real | 5.680 |
| 0.3889 | real | 5.800 |
| 0.1667 | real | 5.920 |
| 0.6667 | real | 6.040 |
| 0.2222 | real | 6.160 |
| 0.5000 | real | 6.280 |
| 0.3889 | real | 6.400 |
| 0.2778 | real | 6.520 |
| 0.1111 | real | 6.640 |
| 0.6111 | real | 6.760 |
| 0.2222 | real | 6.880 |
| 0.0556 | real | 7 |
| 0.0556 | real | 7.120 |
| 0.2222 | real | 7.240 |
| 0.0556 | real | 7.360 |
| 0 | real | 7.480 |
| 0.0556 | real | 7.600 |
| 0.2222 | real | 7.720 |
| 0.0556 | real | 7.840 |
| 0 | synthetic | 4.360 |
| 0.0556 | synthetic | 4.480 |
| 0.1111 | synthetic | 4.600 |
| 0.2778 | synthetic | 4.720 |
| 0.4444 | synthetic | 4.840 |
| 0.3333 | synthetic | 4.960 |
| 0.3889 | synthetic | 5.080 |
| 0.3333 | synthetic | 5.200 |
| 0.6111 | synthetic | 5.320 |
| 0.2778 | synthetic | 5.440 |
| 0.5000 | synthetic | 5.560 |
| 0.5000 | synthetic | 5.680 |
| 0.6111 | synthetic | 5.800 |
| 0.3889 | synthetic | 5.920 |
| 0.3333 | synthetic | 6.040 |
| 0.4444 | synthetic | 6.160 |
| 0.6111 | synthetic | 6.280 |
| 0.5000 | synthetic | 6.400 |
| 0.4444 | synthetic | 6.520 |
| 0.4444 | synthetic | 6.640 |
| 0.4444 | synthetic | 6.760 |
| 0.1667 | synthetic | 6.880 |
| 0.1111 | synthetic | 7 |
| 0 | synthetic | 7.120 |
| 0 | synthetic | 7.240 |
| 0 | synthetic | 7.360 |
| 0 | synthetic | 7.480 |
| 0 | synthetic | 7.600 |
| 0 | synthetic | 7.720 |
| 0 | synthetic | 7.840 |
Assumptions
- Latent dimensions in use — 2 of 2 latent dimensions vary across rows (variance of μ > 0.01).
Rows the model finds least typical
| Rank | Row | Per-row loss | sepal_length | sepal_width | petal_length | petal_width |
|---|---|---|---|---|---|---|
| 1 | 132 | 5.870 | 7.900 | 3.800 | 6.400 | 2 |
| 2 | 118 | 5.550 | 7.700 | 3.800 | 6.700 | 2.200 |
| 3 | 16 | 4.902 | 5.700 | 4.400 | 1.500 | 0.4000 |
| 4 | 119 | 4.342 | 7.700 | 2.600 | 6.900 | 2.300 |
| 5 | 42 | 4.088 | 4.500 | 2.300 | 1.300 | 0.3000 |
| 6 | 61 | 3.918 | 5 | 2 | 3.500 | 1 |
| 7 | 34 | 3.605 | 5.500 | 4.200 | 1.400 | 0.2000 |
| 8 | 110 | 3.530 | 7.200 | 3.600 | 6.100 | 2.500 |
| 9 | 123 | 3.279 | 7.700 | 2.800 | 6.700 | 2 |
| 10 | 33 | 3.056 | 5.200 | 4.100 | 1.500 | 0.1000 |
| 11 | 15 | 3.030 | 5.800 | 4 | 1.200 | 0.2000 |
| 12 | 136 | 2.754 | 7.700 | 3 | 6.100 | 2.300 |
| 13 | 63 | 2.688 | 6 | 2.200 | 4 | 1 |
| 14 | 106 | 2.661 | 7.600 | 3 | 6.600 | 2.100 |
| 15 | 69 | 2.616 | 6.200 | 2.200 | 4.500 | 1.500 |
| 16 | 120 | 2.555 | 6 | 2.200 | 5 | 1.500 |
| 17 | 107 | 2.491 | 4.900 | 2.500 | 4.500 | 1.700 |
| 18 | 94 | 2.426 | 5 | 2.300 | 3.300 | 1 |
| 19 | 137 | 2.333 | 6.300 | 3.400 | 5.600 | 2.400 |
| 20 | 101 | 2.324 | 6.300 | 3.300 | 6 | 2.500 |
Latent dimensions
| Dimension | Mean KL (nats) | Variance of μ | Active |
|---|---|---|---|
| 1 | 0.8634 | 0.8815 | yes |
| 2 | 0.2468 | 0.3660 | yes |
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
))
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
| Rank | Row | Per-row loss | sepal_length | sepal_width | petal_length | petal_width |
|---|---|---|---|---|---|---|
| 1 | 132 | 5.870 | 7.900 | 3.800 | 6.400 | 2 |
| 2 | 118 | 5.550 | 7.700 | 3.800 | 6.700 | 2.200 |
| 3 | 16 | 4.902 | 5.700 | 4.400 | 1.500 | 0.4000 |
| 4 | 119 | 4.342 | 7.700 | 2.600 | 6.900 | 2.300 |
| 5 | 42 | 4.088 | 4.500 | 2.300 | 1.300 | 0.3000 |
| 6 | 61 | 3.918 | 5 | 2 | 3.500 | 1 |
| 7 | 34 | 3.605 | 5.500 | 4.200 | 1.400 | 0.2000 |
| 8 | 110 | 3.530 | 7.200 | 3.600 | 6.100 | 2.500 |
| 9 | 123 | 3.279 | 7.700 | 2.800 | 6.700 | 2 |
| 10 | 33 | 3.056 | 5.200 | 4.100 | 1.500 | 0.1000 |
| 11 | 15 | 3.030 | 5.800 | 4 | 1.200 | 0.2000 |
| 12 | 136 | 2.754 | 7.700 | 3 | 6.100 | 2.300 |
| 13 | 63 | 2.688 | 6 | 2.200 | 4 | 1 |
| 14 | 106 | 2.661 | 7.600 | 3 | 6.600 | 2.100 |
| 15 | 69 | 2.616 | 6.200 | 2.200 | 4.500 | 1.500 |
| 16 | 120 | 2.555 | 6 | 2.200 | 5 | 1.500 |
| 17 | 107 | 2.491 | 4.900 | 2.500 | 4.500 | 1.700 |
| 18 | 94 | 2.426 | 5 | 2.300 | 3.300 | 1 |
| 19 | 137 | 2.333 | 6.300 | 3.400 | 5.600 | 2.400 |
| 20 | 101 | 2.324 | 6.300 | 3.300 | 6 | 2.500 |
Latent dimensions
| Dimension | Mean KL (nats) | Variance of μ | Active |
|---|---|---|---|
| 1 | 0.8634 | 0.8815 | yes |
| 2 | 0.2468 | 0.3660 | yes |
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.
Generate, then check
ReadBecause 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.
Learning by telling rows apart
ExploreSCARF 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.
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
View data
| species | Component 1 | Component 2 |
|---|---|---|
| Adelie | 2.774 | −1.047 |
| Adelie | 1.915 | 0.9130 |
| Adelie | 1.737 | 0.7030 |
| Adelie | 1.223 | −0.5208 |
| Adelie | 2.398 | 0.7307 |
| Adelie | 2.956 | −1.940 |
| Adelie | 2.208 | 0.9186 |
| Adelie | 2.202 | −2.159 |
| Adelie | 2.042 | −0.1045 |
| Adelie | 2.501 | −1.059 |
| Adelie | 1.786 | 0.0384 |
| Adelie | 2.070 | 0.2609 |
| Adelie | 2.020 | 0.7916 |
| Adelie | 3.030 | −2.232 |
| Adelie | 2.725 | −2.541 |
| Adelie | 2.269 | 1.018 |
| Adelie | 2.099 | 0.6687 |
| Adelie | 2.068 | −2.496 |
| Adelie | 2.651 | 0.9900 |
| Adelie | 2.310 | −2.618 |
| Adelie | 1.740 | 1.707 |
| Adelie | 2.039 | −0.2494 |
| Adelie | 1.250 | 1.983 |
| Adelie | 1.506 | −0.2852 |
| Adelie | 1.601 | −0.1191 |
| Adelie | 1.231 | 1.961 |
| Adelie | 1.825 | −0.2493 |
| Adelie | 1.107 | 1.849 |
| Adelie | 1.894 | 1.726 |
| Adelie | 1.734 | −0.3572 |
| Adelie | 1.568 | 1.551 |
| Adelie | 2.251 | −0.3916 |
| Adelie | 1.624 | 1.375 |
| Adelie | 1.983 | −0.6697 |
| Adelie | 0.9698 | 1.364 |
| Adelie | 1.553 | −2.436 |
| Adelie | 2.011 | −1.594 |
| Adelie | 1.716 | 1.386 |
| Adelie | 2.267 | 1.418 |
| Adelie | 1.615 | −1.332 |
| Adelie | 2.042 | 1.448 |
| Adelie | 1.462 | −0.9915 |
| Adelie | 2.026 | 1.413 |
| Adelie | 0.8182 | −1.880 |
| Adelie | 1.573 | 1.424 |
| Adelie | 1.345 | −1.448 |
| Adelie | 2.450 | −0.3963 |
| Adelie | 2.277 | 0.4321 |
| Adelie | 1.476 | 1.368 |
| Adelie | 1.655 | −2.335 |
| Adelie | 0.9192 | 1.819 |
| Adelie | 1.112 | −0.8849 |
| Adelie | 0.9390 | 1.951 |
| Adelie | 0.5064 | −1.033 |
| Adelie | 1.408 | 1.915 |
| Adelie | 1.230 | −0.4059 |
| Adelie | 0.8233 | 1.800 |
| Adelie | 1.120 | −0.5507 |
| Adelie | 1.085 | 1.582 |
| Adelie | 1.310 | −0.5862 |
First 60 of 344 rows.
View data
| Part | Loss | Epoch |
|---|---|---|
| InfoNCE | 4.024 | 1 |
| InfoNCE | 4.025 | 2 |
| InfoNCE | 4.036 | 3 |
| InfoNCE | 3.985 | 4 |
| InfoNCE | 4.015 | 5 |
| InfoNCE | 3.964 | 6 |
| InfoNCE | 3.979 | 7 |
| InfoNCE | 3.981 | 8 |
| InfoNCE | 3.952 | 9 |
| InfoNCE | 3.956 | 10 |
| InfoNCE | 3.983 | 11 |
| InfoNCE | 3.921 | 12 |
| InfoNCE | 3.946 | 13 |
| InfoNCE | 3.941 | 14 |
| InfoNCE | 3.962 | 15 |
| InfoNCE | 3.968 | 16 |
| InfoNCE | 3.921 | 17 |
| InfoNCE | 3.936 | 18 |
| InfoNCE | 3.923 | 19 |
| InfoNCE | 3.938 | 20 |
| InfoNCE | 3.930 | 21 |
| InfoNCE | 3.928 | 22 |
| InfoNCE | 3.936 | 23 |
| InfoNCE | 3.907 | 24 |
| InfoNCE | 3.954 | 25 |
| InfoNCE | 3.877 | 26 |
| InfoNCE | 3.935 | 27 |
| InfoNCE | 3.921 | 28 |
| InfoNCE | 3.901 | 29 |
| InfoNCE | 3.910 | 30 |
| InfoNCE | 3.908 | 31 |
| InfoNCE | 3.915 | 32 |
| InfoNCE | 3.874 | 33 |
| InfoNCE | 3.882 | 34 |
| InfoNCE | 3.930 | 35 |
| InfoNCE | 3.900 | 36 |
| InfoNCE | 3.896 | 37 |
| InfoNCE | 3.907 | 38 |
| InfoNCE | 3.952 | 39 |
| InfoNCE | 3.915 | 40 |
| InfoNCE | 3.918 | 41 |
| InfoNCE | 3.885 | 42 |
| InfoNCE | 3.902 | 43 |
| InfoNCE | 3.893 | 44 |
| InfoNCE | 3.892 | 45 |
| InfoNCE | 3.903 | 46 |
| InfoNCE | 3.904 | 47 |
| InfoNCE | 3.907 | 48 |
| InfoNCE | 3.877 | 49 |
| InfoNCE | 3.906 | 50 |
| InfoNCE | 3.937 | 51 |
| InfoNCE | 3.886 | 52 |
| InfoNCE | 3.927 | 53 |
| InfoNCE | 3.861 | 54 |
| InfoNCE | 3.875 | 55 |
| InfoNCE | 3.894 | 56 |
| InfoNCE | 3.887 | 57 |
| InfoNCE | 3.892 | 58 |
| InfoNCE | 3.861 | 59 |
| InfoNCE | 3.901 | 60 |
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")
)
))
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?
When is a learned map worth it?
ReflectThese 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.
Check your understanding
CheckpointCheck 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.
Do it on your own data
In the appIn 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.
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"])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))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