Masked autoencoders and JEPA: hide part, predict it
Hide most of an input and train a network to fill it in, scored only on the hidden parts. MAE predicts raw values; I-JEPA predicts a slow encoder's representations of them. See the same idea in CodeSplash's masked imputation.
What runs in CodeSplash
- DNN074Masked autoencoder for vision (MAE) Partly runs in CodeSplash
- DNN075Image Joint-Embedding Predictive Architecture (I-JEPA) Explained here
- Autoencoder (neural map and reconstruction anomalies) Verified in Python and R
- Diffusion imputation for multivariate series (CSDI) Experimental
You will be able to
- Explain why MAE encodes only visible patches and scores only hidden ones
- Say why a high masking ratio makes the task useful
- Contrast predicting raw values (MAE) with predicting representations (I-JEPA)
- Check masked predictions against a simple baseline on hidden values
Hide most of it
ReadA masked autoencoderMasked autoencoderHides most patches of an input, encodes only the visible ones, and is scored on rebuilding the hidden ones. cuts an image into patches and hides a large random share of them, often three quarters. The encoder sees only the visible patches. A light decoder gets the encoded patches plus placeholders for the hidden ones and predicts the hidden pixels. The loss counts only the hidden patches.
Hiding so much makes the task hard enough that the encoder has to learn about objects and shapes, not copy nearby pixels. And encoding only the visible quarter makes pretraining cheap.
Only the hidden parts count
ReadIn the reference's example four patches are split into two visible and two hidden. The encoder's input has shape 2 by 4, the visible patches only. The prediction for the visible patches is made deliberately terrible, yet the loss is 0.01, because only hidden patches are scored.
import numpy as np
patches = np.arange(16.).reshape(4, 4) / 16
hidden = np.array([False, True, False, True])
visible = patches[~hidden] # all the encoder sees
pred = patches + .1
pred[~hidden] += 10 # wrong on visible patches: not scored
print(visible.shape, np.mean((pred[hidden] - patches[hidden]) ** 2))patches <- matrix(0:15, 4, byrow = TRUE) / 16
hidden <- c(FALSE, TRUE, FALSE, TRUE)
visible <- patches[!hidden, ] # all the encoder sees
pred <- patches + .1
pred[!hidden, ] <- pred[!hidden, ] + 10 # wrong on visible patches: not scored
print(c(dim(visible), mean((pred[hidden, ] - patches[hidden, ])^2)))Predict representations, not pixels
ReadPixels hold detail that doesn't matter for most uses: exact texture, noise. A joint-embedding predictive architectureJoint-embedding predictive architecturePredicts the representations of hidden regions, from a slow target encoder, instead of their raw pixels. (I-JEPA) predicts representations instead. A context encoder sees part of the image; a predictor guesses the representations of several hidden target blocks, as computed by a target encoder that is a momentum average of the context encoder and gets no gradient.
In the reference's example the predicted target representations miss by 0.03 each, a mean loss of 0.03. Like BYOL, the slow target and stopped gradient are what keep it from collapsing to a constant.
Reference · DNN075 · Explained hereImage Joint-Embedding Predictive Architecture (I-JEPA)I-JEPA predicts representations of target image regions from a context region instead of reconstructing raw pixels.Masked training on tables, in CodeSplash
ExploreThe same idea runs in CodeSplash for multivariate series: CSDI imputation hides some observed values during training and learns to predict them (masked trainingMasked self-supervised trainingTraining an imputer by hiding observed values from it and asking it to recover them, so every training target is real.). Its Hidden share for checking hides extra observed values before training and scores them afterwards, a hidden-value checkHidden-value checkHide some observed values, impute them, and compare with the truth and with straight-line filling before trusting an imputer..
44 missing values in 4 variables were imputed 8 times by conditional diffusion (CSDI). On 53 hidden values the median imputation's MAE was 24 (linear interpolation 26).
- MAE on hidden values
- 24.000
Plots
53 observed values hidden before training, grouped by variable; bars are 90% intervals of the 8 draws.
View data
| Actual | Hidden value | Interval lower | Median imputation | Interval upper |
|---|---|---|---|---|
| 23 | 1 | −12.458 | 16.283 | 59.738 |
| 14 | 2 | −8.545 | 22.088 | 59.281 |
| 45 | 3 | 13.740 | 53.331 | 67.350 |
| 39 | 4 | 26.066 | 42.550 | 92.826 |
| 20 | 5 | 23.171 | 47.884 | 76.589 |
| 79 | 6 | 36.174 | 42.348 | 68.305 |
| 20 | 7 | 33.414 | 50.830 | 65.928 |
| 78 | 8 | 6.902 | 52.980 | 83.704 |
| 9 | 9 | 38.855 | 49.812 | 87.250 |
| 32 | 10 | 1.607 | 15.606 | 36.459 |
| 24 | 11 | −1.461 | 56.273 | 114.08 |
| 13 | 12 | −30.289 | −5.528 | 35.990 |
| 290 | 13 | 123.51 | 292.80 | 473.42 |
| 65 | 14 | −66.364 | 161.44 | 319.35 |
| 44 | 15 | 10.124 | 137.94 | 257.25 |
| 98 | 16 | 94.419 | 179.50 | 442.38 |
| 272 | 17 | 107.14 | 217.71 | 256.27 |
| 207 | 18 | 111.84 | 203.93 | 309.26 |
| 51 | 19 | 95.915 | 161.72 | 240.53 |
| 259 | 20 | 67.787 | 133.46 | 252.81 |
| 212 | 21 | 140.33 | 240.15 | 356.72 |
| 189 | 22 | 64.760 | 166.96 | 368.92 |
| 92 | 23 | 90.435 | 202.84 | 263.07 |
| 20 | 24 | 80.785 | 164.37 | 484.45 |
| 223 | 25 | 111.57 | 191.24 | 312.16 |
| 8.600 | 26 | 7.056 | 10.933 | 13.240 |
| 5.700 | 27 | 5.118 | 9.018 | 11.601 |
| 5.100 | 28 | 2.470 | 8.048 | 13.836 |
| 8.600 | 29 | 3.711 | 8.109 | 15.503 |
| 10.300 | 30 | 6.809 | 12.159 | 15.577 |
| 10.300 | 31 | 2.552 | 8.420 | 20.091 |
| 5.700 | 32 | 1.447 | 6.982 | 9.963 |
| 6.300 | 33 | 3.143 | 8.490 | 11.399 |
| 7.400 | 34 | 0.8624 | 6.836 | 9.120 |
| 6.900 | 35 | 7.412 | 10.881 | 18.391 |
| 6.900 | 36 | 10.140 | 12.781 | 19.217 |
| 14.300 | 37 | 10.053 | 12.092 | 17.261 |
| 68 | 38 | 55.874 | 63.181 | 95.081 |
| 64 | 39 | 46.692 | 71.108 | 107.87 |
| 80 | 40 | 80.673 | 87.216 | 93.534 |
| 77 | 41 | 80.595 | 83.199 | 103.27 |
| 65 | 42 | 74.205 | 79.103 | 82.048 |
| 77 | 43 | 73.208 | 79.662 | 96.448 |
| 83 | 44 | 78.524 | 85.749 | 104.83 |
| 88 | 45 | 65.863 | 85.182 | 89.751 |
| 80 | 46 | 79.447 | 84.517 | 86.733 |
| 88 | 47 | 75.437 | 84.724 | 98.248 |
| 90 | 48 | 68.466 | 76.483 | 89.254 |
| 82 | 49 | 77.975 | 82.346 | 92.094 |
| 80 | 50 | 75.918 | 81.646 | 98.203 |
| 86 | 51 | 76.080 | 86.747 | 98.517 |
| 94 | 52 | 78.170 | 92.665 | 109.58 |
| 82 | 53 | 65.578 | 72.515 | 79.304 |
Mean squared error of the predicted noise on the target cells; lower is better.
View data
| Part | Loss (mean squared noise error) | Epoch |
|---|---|---|
| training windows | 1.010 | 1 |
| training windows | 0.9727 | 2 |
| training windows | 0.9339 | 3 |
| training windows | 0.9314 | 4 |
| training windows | 0.8576 | 5 |
| training windows | 0.8009 | 6 |
| training windows | 0.7440 | 7 |
| training windows | 0.7951 | 8 |
| training windows | 0.7513 | 9 |
| training windows | 0.7597 | 10 |
| training windows | 0.7081 | 11 |
| training windows | 0.6969 | 12 |
Assumptions
- Better than straight-line filling — On 53 hidden values the median imputation's mean absolute error is 24 against 26 for linear interpolation.
- Missing at random — The imputations are valid when whether a value is missing depends only on observed values (MAR); if values are missing because of what they would have been (MNAR), the imputations are biased.
- Enough observed values — The variable with the most gaps is 24% missing.
Imputed variables
| Variable | Missing | Observed mean | Imputed mean (median draws) | Mean 90% interval width |
|---|---|---|---|---|
| Ozone | 37 | 42.129 | 42.098 | 79.282 |
| Solar.R | 7 | 185.93 | 182.72 | 301.48 |
| Wind | 0 | 9.958 | — | — |
| Temp | 0 | 77.882 | — | — |
Imputed values (first 44)
| Row | Variable | Median | Lower | Upper |
|---|---|---|---|---|
| 5 | Ozone | 6.761 | −24.800 | 96.250 |
| 10 | Ozone | 16.907 | −5.232 | 62.877 |
| 25 | Ozone | 38.220 | 4.163 | 60.974 |
| 26 | Ozone | 37.242 | −7.627 | 67.069 |
| 27 | Ozone | 17.248 | −11.932 | 68.697 |
| 32 | Ozone | 36.937 | −29.022 | 90.164 |
| 33 | Ozone | 53.205 | 31.736 | 149.01 |
| 34 | Ozone | 49.806 | 35.983 | 58.109 |
| 35 | Ozone | 62.991 | −2.815 | 73.972 |
| 36 | Ozone | 51.187 | 21.369 | 122.07 |
| 37 | Ozone | 43.804 | −3.694 | 98.276 |
| 39 | Ozone | 39.711 | 3.384 | 59.510 |
| 42 | Ozone | 47.671 | 32.766 | 124.87 |
| 43 | Ozone | 34.570 | 7.578 | 125.30 |
| 45 | Ozone | 34.003 | 10.944 | 57.183 |
| 46 | Ozone | 37.492 | −13.406 | 144.97 |
| 52 | Ozone | 34.384 | 5.262 | 57.087 |
| 53 | Ozone | 45.093 | 24.360 | 101.11 |
| 54 | Ozone | 39.966 | 14.562 | 125.19 |
| 55 | Ozone | 29.332 | −17.393 | 52.024 |
| 56 | Ozone | 35.979 | −5.047 | 89.959 |
| 57 | Ozone | 32.346 | −14.679 | 50.322 |
| 58 | Ozone | 52.737 | −6.151 | 67.008 |
| 59 | Ozone | 56.061 | 10.810 | 85.408 |
| 60 | Ozone | 40.835 | 18.052 | 56.773 |
| 61 | Ozone | 42.616 | −15.459 | 63.957 |
| 65 | Ozone | 42.710 | 14.625 | 63.421 |
| 72 | Ozone | 46.490 | −0.1781 | 96.153 |
| 75 | Ozone | 56.577 | 24.099 | 97.345 |
| 83 | Ozone | 39.877 | −3.810 | 59.896 |
| 84 | Ozone | 49.599 | 33.931 | 92.942 |
| 102 | Ozone | 56.753 | 26.123 | 98.475 |
| 103 | Ozone | 43.805 | 6.892 | 73.946 |
| 107 | Ozone | 43.586 | 12.299 | 98.083 |
| 115 | Ozone | 82.808 | 33.606 | 109.78 |
| 119 | Ozone | 55.637 | 45.169 | 128.71 |
| 150 | Ozone | 22.673 | −16.793 | 46.233 |
| 5 | Solar.R | 136.41 | 51.901 | 362.64 |
| 6 | Solar.R | 142.38 | 105.92 | 273.75 |
| 11 | Solar.R | 208.95 | 146.78 | 274.85 |
First 40 of 44 rows.
- Seed 42; the 8 completed data sets are saved as imputed.parquet (long format with .imp and .id).
The exact R script · R R version 4.5.1 (2025-06-13)
# Diffusion imputation for multivariate series (CSDI)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method missing.csdi 1.0.0 · spec 8e48b7fb55d51dcd
# Dataset: airquality (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr) # cs_csdi_* (score network on torch, shared draws), cs_ml_fc_to_days
# 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/missing.csdi/airquality_default_check/out-r")
# %% Data (no rows are dropped: the missing values are imputed)
VARIABLES <- c("Ozone", "Solar.R", "Wind", "Temp")
TIME <- NULL
SERIES <- NULL
SEED <- 42
M <- as.integer(8)
LEVEL <- 0.9
cols <- unique(c(VARIABLES, TIME, SERIES))
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/airquality.parquet", col_select = cols))
n <- nrow(df)
K <- length(VARIABLES)
warnings <- list()
cs_check_finite_columns(df, c(VARIABLES, TIME)) # infinite values stop the run (registry/errors.yaml)
values_raw <- do.call(cbind, lapply(VARIABLES, function(v) suppressWarnings(as.numeric(df[[v]]))))
values_raw <- matrix(values_raw, nrow = n, ncol = K)
for (j in seq_len(K)) if (all(is.na(values_raw[, j]))) cs_error("CS_E_ALL_MISSING", column = VARIABLES[j])
cs_check_rows(n, 4, "CSDI imputation")
times <- NULL
if (!is.null(TIME)) {
times <- cs_ml_fc_to_days(df[[TIME]])$values
if (any(is.na(times))) cs_error("CS_E_INVALID_VALUES", column = TIME, requirement = "present on every row (it orders the rows)", count = sum(is.na(times)))
}
series <- NULL
if (!is.null(SERIES)) {
s <- df[[SERIES]]
if (sum(is.na(s))) cs_error("CS_E_INVALID_VALUES", column = SERIES, requirement = "present on every row (it names each row's series)", count = sum(is.na(s)))
series <- as.character(s)
}
if (8 %% 2 != 0) {
cs_error("CS_E_INVALID_OPTION", option = "Attention heads", allowed = "a divisor of the channels (8)", value = 2)
}
groups <- cs_csdi_grids(values_raw, series, times)
observed <- !is.na(values_raw)
L <- min(as.integer(16), min(vapply(groups, length, integer(1))))
if (L < 2L) cs_error("CS_E_TOO_FEW_ROWS", what = "Every series", min = 2, n = L)
# Hidden cells for the evaluation (a seeded share of the observed cells, row by row).
SHARE <- 0.1
hidden <- matrix(FALSE, n, K)
if (SHARE > 0) {
u <- matrix(cs_runif(cs_rng(SEED + 404), n * K), nrow = n, ncol = K, byrow = TRUE)
hidden <- observed & (u < SHARE)
}
known <- observed & !hidden
st <- cs_csdi_standardize(values_raw, known)
mu <- st$mu; sd <- st$sd
v0 <- values_raw; v0[is.na(v0)] <- 0
std <- sweep(sweep(v0, 2L, mu, "-"), 2L, sd, "/")
Z <- ifelse(known, std, 0)
# %% Train the score network and impute
model <- cs_csdi_fit(
Z, known, groups, L,
channels = 8,
layers = 1,
heads = 2,
diffusion_steps = 10,
online = FALSE,
epochs = 12,
lr = 0.005,
batch_size = 32,
seed = SEED
)
values <- list(n = n, n_vars = K, m = M, window_length = L, windows = model$windows, epochs_run = model$epochs_run, final_loss = model$final_loss)
assumptions <- list()
charts <- list()
tables <- list()
unstd <- function(d) { for (j in seq_len(K)) d[, , j] <- d[, , j] * sd[j] + mu[j]; d }
if (any(hidden)) {
ev <- unstd(cs_csdi_impute(model, Z, known, groups, M, SEED + 505))
sm <- cs_csdi_summarize(ev, LEVEL)
interp <- cs_csdi_interpolate(values_raw, known, groups)
idx <- which(t(hidden), arr.ind = TRUE) # row by row, as in Python
cells <- cbind(idx[, 2], idx[, 1])
truth <- values_raw[cells]
err <- abs(sm$med[cells] - truth)
values$eval_n <- nrow(cells)
values$eval_mae <- sum(err) / length(err)
values$eval_rmse <- sqrt(sum(err * err) / length(err))
values$eval_crps <- sum(vapply(seq_len(nrow(cells)), function(q) cs_tg_crps(ev[, cells[q, 1], cells[q, 2]], truth[q]), numeric(1))) / nrow(cells)
values$eval_coverage <- sum(as.numeric(sm$lo[cells] <= truth & truth <= sm$hi[cells])) / nrow(cells)
ip <- interp[cells]
ierr <- abs(ip - truth)[!is.na(ip)]
if (length(ierr)) values$interp_mae <- sum(ierr) / length(ierr)
for (j in seq_len(K)) {
e_j <- err[cells[, 2] == j]
if (length(e_j)) values[[sprintf("eval_mae[%s]", VARIABLES[j])]] <- sum(e_j) / length(e_j)
}
better <- !is.null(values$interp_mae) && values$eval_mae <= values$interp_mae
assumptions[[length(assumptions) + 1L]] <- list(
key = "beats_interpolation", label = "Better than straight-line filling",
status = if (better) "pass" else "warn",
detail = paste0(sprintf("On %d hidden values the median imputation's mean absolute error is %s", nrow(cells), format(signif(values$eval_mae, 3))),
if (!is.null(values$interp_mae)) sprintf(" against %s for linear interpolation.", format(signif(values$interp_mae, 3))) else ".",
if (better) "" else " A simpler method may serve as well; train longer or use more layers.")
)
ord <- order(cells[, 2], cells[, 1])[seq_len(min(400L, nrow(cells)))]
charts[[length(charts) + 1L]] <- cs_chart("evaluation", "interval-plot", "Hidden values and their imputations", list(
index = cs_col("Hidden value", seq_along(ord), "numeric"),
actual = cs_col("Actual", truth[ord], "numeric"),
pred = cs_col("Median imputation", sm$med[cells[ord, , drop = FALSE]], "numeric"),
lower = cs_col("Interval lower", sm$lo[cells[ord, , drop = FALSE]], "numeric"),
upper = cs_col("Interval upper", sm$hi[cells[ord, , drop = FALSE]], "numeric")
), note = sprintf("%d observed values hidden before training, grouped by variable; bars are %s intervals of the %d draws.", length(ord), sprintf("%.0f%%", LEVEL * 100), M))
}
Zall <- ifelse(observed, std, 0) # every observed cell conditions the final draws
draws <- unstd(cs_csdi_impute(model, Zall, observed, groups, M, SEED + 303))
for (s in seq_len(M)) draws[s, , ][observed] <- values_raw[observed]
sm <- cs_csdi_summarize(draws, LEVEL)
missing <- !observed
values$n_missing <- sum(missing)
values$pct_missing <- sum(missing) / (n * K)
imp_rows <- list()
for (j in seq_len(K)) {
v <- VARIABLES[j]
mj <- missing[, j]
values[[sprintf("missing[%s]", v)]] <- sum(mj)
ob <- values_raw[observed[, j], j]
values[[sprintf("observed_mean[%s]", v)]] <- sum(ob) / length(ob)
if (any(mj)) {
values[[sprintf("imputed_mean[%s]", v)]] <- sum(sm$med[mj, j]) / sum(mj)
values[[sprintf("interval_width[%s]", v)]] <- sum(sm$hi[mj, j] - sm$lo[mj, j]) / sum(mj)
}
imp_rows[[j]] <- list(variable = v, missing = sum(mj), observed = values[[sprintf("observed_mean[%s]", v)]],
imputed = values[[sprintf("imputed_mean[%s]", v)]], width = values[[sprintf("interval_width[%s]", v)]])
}
if (!any(missing)) warnings <- c(warnings, "No values are missing; the completed data sets equal the data.")
share_max <- max(colMeans(missing))
assumptions[[length(assumptions) + 1L]] <- list(
key = "mar", label = "Missing at random", status = "info",
detail = "The imputations are valid when whether a value is missing depends only on observed values (MAR); if values are missing because of what they would have been (MNAR), the imputations are biased."
)
assumptions[[length(assumptions) + 1L]] <- list(
key = "enough_observed", label = "Enough observed values",
status = if (share_max > 0.5) "warn" else "pass",
detail = paste0(sprintf("The variable with the most gaps is %s missing", sprintf("%.0f%%", share_max * 100)),
if (share_max > 0.5) " — over half, so its imputations lean on the other variables and the model's guesses." else ".")
)
# %% Imputed data sets (long format, like mice::complete(imp, "long"))
out <- cs_ml_out_dir("target/academy-parity/run-8142/missing.csdi/airquality_default_check/out-r")
parts <- lapply(seq_len(M), function(s) {
part <- data.frame(.imp = rep(s, n), .id = seq_len(n), check.names = FALSE)
for (j in seq_len(K)) part[[VARIABLES[j]]] <- draws[s, , j]
part
})
path <- file.path(out, "imputed.parquet")
nanoparquet::write_parquet(do.call(rbind, parts), path)
cidx <- which(missing, arr.ind = TRUE)
cidx <- cidx[order(cidx[, 2], cidx[, 1]), , drop = FALSE][seq_len(min(200L, nrow(cidx))), , drop = FALSE]
hist <- model$history
charts[[length(charts) + 1L]] <- cs_chart("training", "training-components", "Denoising loss by epoch", list(
x = cs_col("Epoch", vapply(hist, function(h) as.numeric(h$epoch), numeric(1)), "numeric"),
value = cs_col("Loss (mean squared noise error)", vapply(hist, function(h) h$loss, numeric(1)), "numeric"),
component = cs_col("Part", rep("training windows", length(hist)), "categorical", levels = c("training windows"))
), note = "Mean squared error of the predicted noise on the target cells; lower is better.")
tables[[length(tables) + 1L]] <- list(key = "imputation", title = "Imputed variables",
columns = list(list(key = "variable", label = "Variable", type = "string"), list(key = "missing", label = "Missing", type = "integer"),
list(key = "observed", label = "Observed mean", type = "number"), list(key = "imputed", label = "Imputed mean (median draws)", type = "number"),
list(key = "width", label = sprintf("Mean %s interval width", sprintf("%.0f%%", LEVEL * 100)), type = "number")),
rows = imp_rows)
tables[[length(tables) + 1L]] <- list(key = "cells", title = sprintf("Imputed values (first %d)", nrow(cidx)),
columns = list(list(key = "row", label = "Row", type = "integer"), list(key = "variable", label = "Variable", type = "string"),
list(key = "median", label = "Median", type = "number"), list(key = "low", label = "Lower", type = "number"),
list(key = "high", label = "Upper", type = "number")),
rows = lapply(seq_len(nrow(cidx)), function(q) list(row = cidx[q, 1], variable = VARIABLES[cidx[q, 2]], median = sm$med[cidx[q, , drop = FALSE]],
low = sm$lo[cidx[q, , drop = FALSE]], high = sm$hi[cidx[q, , drop = FALSE]])))
summary <- sprintf("%d missing values in %d variable%s were imputed %d times by conditional diffusion (CSDI).", values$n_missing, K, if (K != 1) "s" else "", M)
if (!is.null(values$eval_mae)) {
summary <- paste0(summary, sprintf(" On %d hidden values the median imputation's MAE was %s", values$eval_n, format(signif(values$eval_mae, 3))),
if (!is.null(values$interp_mae)) sprintf(" (linear interpolation %s).", format(signif(values$interp_mae, 3))) else ".")
}
cs_publish(list(
title = "Diffusion imputation for multivariate series (CSDI)",
engine = cs_engine_info("torch", "nanoparquet", "codesplashr"),
n = n,
summary = summary,
statistics = if (!is.null(values$eval_mae)) list(list(key = "eval_mae", label = "MAE on hidden values", value = values$eval_mae)) else list(),
tables = tables,
values = values,
assumptions = assumptions,
warnings = warnings,
notes = list(sprintf("Seed %d; the %d completed data sets are saved as imputed.parquet (long format with .imp and .id).", SEED, M)),
charts = charts,
artifacts = list(list(key = "imputed", path = path, format = "parquet", title = sprintf("%d imputed data sets (long format)", M)))
))
44 missing values in 4 variables were imputed 8 times by conditional diffusion (CSDI). On 53 hidden values the median imputation's MAE was 24 (linear interpolation 26).
- MAE on hidden values
- 24.000
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Better than straight-line filling — On 53 hidden values the median imputation's mean absolute error is 24 against 26 for linear interpolation.
- Missing at random — The imputations are valid when whether a value is missing depends only on observed values (MAR); if values are missing because of what they would have been (MNAR), the imputations are biased.
- Enough observed values — The variable with the most gaps is 24% missing.
Imputed variables
| Variable | Missing | Observed mean | Imputed mean (median draws) | Mean 90% interval width |
|---|---|---|---|---|
| Ozone | 37 | 42.129 | 42.098 | 79.282 |
| Solar.R | 7 | 185.93 | 182.72 | 301.48 |
| Wind | 0 | 9.958 | — | — |
| Temp | 0 | 77.882 | — | — |
Imputed values (first 44)
| Row | Variable | Median | Lower | Upper |
|---|---|---|---|---|
| 5 | Ozone | 6.761 | −24.800 | 96.250 |
| 10 | Ozone | 16.907 | −5.232 | 62.877 |
| 25 | Ozone | 38.220 | 4.163 | 60.974 |
| 26 | Ozone | 37.242 | −7.627 | 67.069 |
| 27 | Ozone | 17.248 | −11.932 | 68.697 |
| 32 | Ozone | 36.937 | −29.022 | 90.164 |
| 33 | Ozone | 53.205 | 31.736 | 149.01 |
| 34 | Ozone | 49.806 | 35.983 | 58.109 |
| 35 | Ozone | 62.991 | −2.815 | 73.972 |
| 36 | Ozone | 51.187 | 21.369 | 122.07 |
| 37 | Ozone | 43.804 | −3.694 | 98.276 |
| 39 | Ozone | 39.711 | 3.384 | 59.510 |
| 42 | Ozone | 47.671 | 32.766 | 124.87 |
| 43 | Ozone | 34.570 | 7.578 | 125.30 |
| 45 | Ozone | 34.003 | 10.944 | 57.183 |
| 46 | Ozone | 37.492 | −13.406 | 144.97 |
| 52 | Ozone | 34.384 | 5.262 | 57.087 |
| 53 | Ozone | 45.093 | 24.360 | 101.11 |
| 54 | Ozone | 39.966 | 14.562 | 125.19 |
| 55 | Ozone | 29.332 | −17.393 | 52.024 |
| 56 | Ozone | 35.979 | −5.047 | 89.959 |
| 57 | Ozone | 32.346 | −14.679 | 50.322 |
| 58 | Ozone | 52.737 | −6.151 | 67.008 |
| 59 | Ozone | 56.061 | 10.810 | 85.408 |
| 60 | Ozone | 40.835 | 18.052 | 56.773 |
| 61 | Ozone | 42.616 | −15.459 | 63.957 |
| 65 | Ozone | 42.710 | 14.625 | 63.421 |
| 72 | Ozone | 46.490 | −0.1781 | 96.153 |
| 75 | Ozone | 56.577 | 24.099 | 97.345 |
| 83 | Ozone | 39.877 | −3.810 | 59.896 |
| 84 | Ozone | 49.599 | 33.931 | 92.942 |
| 102 | Ozone | 56.753 | 26.123 | 98.475 |
| 103 | Ozone | 43.805 | 6.892 | 73.946 |
| 107 | Ozone | 43.586 | 12.299 | 98.083 |
| 115 | Ozone | 82.808 | 33.606 | 109.78 |
| 119 | Ozone | 55.637 | 45.169 | 128.71 |
| 150 | Ozone | 22.673 | −16.793 | 46.233 |
| 5 | Solar.R | 136.41 | 51.901 | 362.64 |
| 6 | Solar.R | 142.38 | 105.92 | 273.75 |
| 11 | Solar.R | 208.95 | 146.78 | 274.85 |
First 40 of 44 rows.
- Seed 42; the 8 completed data sets are saved as imputed.parquet (long format with .imp and .id).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Diffusion imputation for multivariate series (CSDI)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method missing.csdi 1.0.0 · spec 8e48b7fb55d51dcd
# Dataset: airquality (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import math
import os
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash.deep import csdi # twin of codesplashr::cs_csdi_* (score network on torch, shared draws)
from codesplash.ml import forecast as fc # times as days; sequential sums
from codesplash.ml import run as csml # artifact directory
from codesplash.stats.rng import Rng
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/missing.csdi/airquality_default_check/out-python",
)
# %% Data (no rows are dropped: the missing values are imputed)
VARIABLES = ["Ozone", "Solar.R", "Wind", "Temp"]
TIME = None
SERIES = None
SEED = 42
M = 8
LEVEL = 0.9
cols = list(dict.fromkeys(VARIABLES + [c for c in (TIME, SERIES) if c]))
df = pd.read_parquet("tests/parity/fixtures/airquality.parquet", columns=cols)
n = len(df)
K = len(VARIABLES)
warnings = []
cs.check_finite_columns(df, VARIABLES + ([TIME] if TIME else [])) # infinite values stop the run (registry/errors.yaml)
values_raw = np.column_stack([pd.to_numeric(df[v], errors="coerce").to_numpy(dtype=np.float64) for v in VARIABLES])
for j, v in enumerate(VARIABLES):
if bool(np.isnan(values_raw[:, j]).all()):
cs.cs_error("CS_E_ALL_MISSING", column=v)
cs.check_rows(n, 4, "CSDI imputation")
times = None
if TIME:
times = fc.to_days(df[TIME].to_numpy())[0]
if bool(np.isnan(times).any()):
cs.cs_error("CS_E_INVALID_VALUES", column=TIME, requirement="present on every row (it orders the rows)", count=int(np.isnan(times).sum()))
series = None
if SERIES:
s = df[SERIES]
if int(s.isna().sum()):
cs.cs_error("CS_E_INVALID_VALUES", column=SERIES, requirement="present on every row (it names each row's series)", count=int(s.isna().sum()))
series = s.astype(str).to_numpy(dtype=object)
if 8 % 2 != 0:
cs.cs_error("CS_E_INVALID_OPTION", option="Attention heads", allowed="a divisor of the channels (8)", value=2)
groups = csdi.grids(values_raw, series, times)
observed = ~np.isnan(values_raw)
L = min(int(16), min(len(g) for g in groups))
if L < 2:
cs.cs_error("CS_E_TOO_FEW_ROWS", what="Every series", min=2, n=L)
# Hidden cells for the evaluation (a seeded share of the observed cells, row by row).
SHARE = 0.1
hidden = np.zeros_like(observed)
if SHARE > 0:
u = Rng(SEED + 404).uniform(n * K).reshape(n, K)
hidden = observed & (u < SHARE)
known = observed & ~hidden
mu, sd = csdi.standardize(values_raw, known)
Z = np.where(known, (np.nan_to_num(values_raw) - mu) / sd, 0.0)
# %% Train the score network and impute
model = csdi.fit_csdi(
Z, known, groups, L,
channels=8,
layers=1,
heads=2,
diffusion_steps=10,
online=False,
epochs=12,
lr=0.005,
batch_size=32,
seed=SEED,
)
values = {"n": n, "n_vars": K, "m": M, "window_length": L, "windows": model["windows"], "epochs_run": model["epochs_run"], "final_loss": model["final_loss"]}
assumptions = []
charts = []
tables = []
evaluation = None
if bool(hidden.any()):
ev = csdi.impute(model, Z, known, groups, M, SEED + 505) * sd + mu
med, lo, hi = csdi.summarize(ev, LEVEL)
interp = csdi.interpolate(values_raw, known, groups)
cells = [(i, j) for i in range(n) for j in range(K) if hidden[i, j]]
truth = [values_raw[i, j] for i, j in cells]
err = [abs(med[i, j] - t) for (i, j), t in zip(cells, truth)]
values["eval_n"] = len(cells)
values["eval_mae"] = fc._mean(err)
values["eval_rmse"] = math.sqrt(fc._mean([e * e for e in err]))
values["eval_crps"] = fc._mean([csdi.crps(ev[:, i, j], t) for (i, j), t in zip(cells, truth)])
values["eval_coverage"] = fc._mean([1.0 if lo[i, j] <= t <= hi[i, j] else 0.0 for (i, j), t in zip(cells, truth)])
ierr = [abs(interp[i, j] - t) for (i, j), t in zip(cells, truth) if not math.isnan(interp[i, j])]
if ierr:
values["interp_mae"] = fc._mean(ierr)
for j, v in enumerate(VARIABLES):
e_j = [e for (i, jj), e in zip(cells, err) if jj == j]
if e_j:
values[f"eval_mae[{v}]"] = fc._mean(e_j)
better = "interp_mae" in values and values["eval_mae"] <= values["interp_mae"]
assumptions.append({
"key": "beats_interpolation",
"label": "Better than straight-line filling",
"status": "pass" if better else "warn",
"detail": (f"On {len(cells)} hidden values the median imputation's mean absolute error is {values['eval_mae']:.3g}"
+ (f" against {values['interp_mae']:.3g} for linear interpolation." if "interp_mae" in values else ".")
+ ("" if better else " A simpler method may serve as well; train longer or use more layers.")),
})
order = sorted(range(len(cells)), key=lambda c: (cells[c][1], cells[c][0]))[:400]
charts.append(cs.chart("evaluation", "interval-plot", "Hidden values and their imputations", {
"index": cs.col("Hidden value", list(range(1, len(order) + 1)), "numeric"),
"actual": cs.col("Actual", [truth[c] for c in order], "numeric"),
"pred": cs.col("Median imputation", [float(med[cells[c]]) for c in order], "numeric"),
"lower": cs.col("Interval lower", [float(lo[cells[c]]) for c in order], "numeric"),
"upper": cs.col("Interval upper", [float(hi[cells[c]]) for c in order], "numeric"),
}, note=f"{len(order)} observed values hidden before training, grouped by variable; bars are {LEVEL:.0%} intervals of the {M} draws."))
Zall = np.where(observed, (np.nan_to_num(values_raw) - mu) / sd, 0.0) # every observed cell conditions the final draws
draws = csdi.impute(model, Zall, observed, groups, M, SEED + 303)
draws = np.where(observed[None, :, :], values_raw[None, :, :], draws * sd + mu)
med, lo, hi = csdi.summarize(draws, LEVEL)
missing = ~observed
values["n_missing"] = int(missing.sum())
values["pct_missing"] = float(missing.sum()) / float(n * K)
imp_rows = []
for j, v in enumerate(VARIABLES):
mj = missing[:, j]
values[f"missing[{v}]"] = int(mj.sum())
values[f"observed_mean[{v}]"] = fc._mean(values_raw[observed[:, j], j].tolist())
if mj.any():
values[f"imputed_mean[{v}]"] = fc._mean(med[mj, j].tolist())
values[f"interval_width[{v}]"] = fc._mean((hi[mj, j] - lo[mj, j]).tolist())
imp_rows.append({"variable": v, "missing": int(mj.sum()), "observed": values[f"observed_mean[{v}]"], "imputed": values.get(f"imputed_mean[{v}]"),
"width": values.get(f"interval_width[{v}]")})
if not missing.any():
warnings.append("No values are missing; the completed data sets equal the data.")
share_max = max(float(missing[:, j].mean()) for j in range(K))
assumptions.append({
"key": "mar",
"label": "Missing at random",
"status": "info",
"detail": "The imputations are valid when whether a value is missing depends only on observed values (MAR); if values are missing because of what they would have been (MNAR), the imputations are biased.",
})
assumptions.append({
"key": "enough_observed",
"label": "Enough observed values",
"status": "warn" if share_max > 0.5 else "pass",
"detail": f"The variable with the most gaps is {share_max:.0%} missing" + (" — over half, so its imputations lean on the other variables and the model's guesses." if share_max > 0.5 else "."),
})
# %% Imputed data sets (long format, like mice::complete(imp, "long"))
out = csml.out_dir("target/academy-parity/run-8142/missing.csdi/airquality_default_check/out-python")
parts = []
for s in range(M):
part = {".imp": np.full(n, s + 1), ".id": np.arange(1, n + 1)}
for j, v in enumerate(VARIABLES):
part[v] = draws[s, :, j]
parts.append(pd.DataFrame(part))
path = os.path.join(out, "imputed.parquet")
pd.concat(parts, ignore_index=True).to_parquet(path, index=False)
cells = [(i, j) for j in range(K) for i in range(n) if missing[i, j]][:200]
hist = model["history"]
charts.append(cs.chart("training", "training-components", "Denoising loss by epoch", {
"x": cs.col("Epoch", [h["epoch"] for h in hist], "numeric"),
"value": cs.col("Loss (mean squared noise error)", [h["loss"] for h in hist], "numeric"),
"component": cs.col("Part", ["training windows"] * len(hist), "categorical", levels=["training windows"]),
}, note="Mean squared error of the predicted noise on the target cells; lower is better."))
tables.append({"key": "imputation", "title": "Imputed variables",
"columns": [{"key": "variable", "label": "Variable", "type": "string"}, {"key": "missing", "label": "Missing", "type": "integer"},
{"key": "observed", "label": "Observed mean", "type": "number"}, {"key": "imputed", "label": "Imputed mean (median draws)", "type": "number"},
{"key": "width", "label": f"Mean {LEVEL:.0%} interval width", "type": "number"}],
"rows": imp_rows})
tables.append({"key": "cells", "title": f"Imputed values (first {len(cells)})",
"columns": [{"key": "row", "label": "Row", "type": "integer"}, {"key": "variable", "label": "Variable", "type": "string"},
{"key": "median", "label": "Median", "type": "number"}, {"key": "low", "label": "Lower", "type": "number"},
{"key": "high", "label": "Upper", "type": "number"}],
"rows": [{"row": i + 1, "variable": VARIABLES[j], "median": float(med[i, j]), "low": float(lo[i, j]), "high": float(hi[i, j])} for i, j in cells]})
summary = f"{values['n_missing']} missing values in {K} variable{'s' if K != 1 else ''} were imputed {M} times by conditional diffusion (CSDI)."
if "eval_mae" in values:
summary += f" On {values['eval_n']} hidden values the median imputation's MAE was {values['eval_mae']:.3g}"
summary += f" (linear interpolation {values['interp_mae']:.3g})." if "interp_mae" in values else "."
cs.publish({
"title": "Diffusion imputation for multivariate series (CSDI)",
"engine": cs.engine_info("torch", "pyarrow", "codesplash", "numpy", "pandas"),
"n": n,
"summary": summary,
"statistics": [{"key": "eval_mae", "label": "MAE on hidden values", "value": values["eval_mae"]}] if "eval_mae" in values else [],
"tables": tables,
"values": values,
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"Seed {SEED}; the {M} completed data sets are saved as imputed.parquet (long format with .imp and .id)."],
"charts": charts,
"artifacts": [{"key": "imputed", "path": path, "format": "parquet", "title": f"{M} imputed data sets (long format)"}],
})
On 53 hidden values, the imputations' mean absolute error is 24.0, against 26.0 for straight-line filling.
The baseline can win
Explore0 missing values in 2 variables were imputed 5 times by conditional diffusion (CSDI). On 95 hidden values the median imputation's MAE was 1.08 (linear interpolation 0.783).
- MAE on hidden values
- 1.079
Plots
95 observed values hidden before training, grouped by variable; bars are 90% intervals of the 5 draws.
View data
| Actual | Hidden value | Interval lower | Median imputation | Interval upper |
|---|---|---|---|---|
| 2.685 | 1 | −2.057 | −0.2515 | 1.721 |
| 2.061 | 2 | −0.1999 | −0.1245 | 2.979 |
| 1.927 | 3 | −0.2100 | 0.3394 | 0.9665 |
| −0.0900 | 4 | −3.674 | 0.7337 | 1.579 |
| 0.5983 | 5 | −0.9644 | 0.5343 | 2.312 |
| 1.292 | 6 | −4.262 | 0.2569 | 4.837 |
| 1.077 | 7 | −1.540 | −0.5038 | 1.556 |
| 0.3881 | 8 | −1.598 | −0.6115 | 3.760 |
| −1.342 | 9 | −1.624 | −0.1252 | 1.227 |
| −2.529 | 10 | −2.348 | −1.080 | −0.0344 |
| −0.2856 | 11 | −1.360 | −0.6654 | 1.456 |
| 1.854 | 12 | −3.201 | −1.283 | −0.1464 |
| 0.8614 | 13 | −2.388 | −1.365 | 1.384 |
| 1.644 | 14 | −2.795 | 1.189 | 1.589 |
| −0.2403 | 15 | −2.785 | −1.843 | 1.929 |
| −0.8521 | 16 | −2.120 | −0.0614 | 1.591 |
| −1.177 | 17 | −2.153 | −1.837 | −1.339 |
| 0.7961 | 18 | −1.496 | 0.6904 | 4.201 |
| 0.0566 | 19 | −2.822 | −0.0067 | 0.4965 |
| −0.4446 | 20 | −4.265 | −0.3905 | 1.216 |
| −0.5224 | 21 | −1.069 | 0.3283 | 2.290 |
| −0.6139 | 22 | −2.812 | −1.361 | −0.6052 |
| −1.326 | 23 | −3.595 | 0.8600 | 3.602 |
| 1.372 | 24 | −1.102 | −0.2739 | 4.191 |
| −1.318 | 25 | −3.010 | −0.2412 | 0.5942 |
| 0.6642 | 26 | −1.483 | 0.4731 | 4.141 |
| 0.6341 | 27 | −0.6155 | 0.9663 | 1.340 |
| −0.3416 | 28 | −2.240 | −0.8087 | −0.1309 |
| 0.0602 | 29 | −0.8382 | −0.5674 | 1.829 |
| 0.8233 | 30 | −2.271 | −0.8994 | 0.6844 |
| −1.466 | 31 | −1.554 | −1.093 | 0.7502 |
| −0.4464 | 32 | −3.345 | −1.445 | 2.529 |
| −1.410 | 33 | −0.3458 | 2.568 | 3.824 |
| 0.2276 | 34 | −2.235 | −0.8200 | −0.1624 |
| −0.2396 | 35 | −1.188 | 0.2142 | 1.714 |
| −1.413 | 36 | −1.778 | −0.3036 | 1.412 |
| 0.9936 | 37 | −0.7709 | −0.1249 | 3.443 |
| 0.5653 | 38 | −1.504 | −0.7204 | −0.0807 |
| −0.8335 | 39 | −2.960 | −1.101 | 0.5895 |
| −0.6382 | 40 | −0.9526 | 0.8946 | 1.471 |
| −1.405 | 41 | −0.6785 | −0.4620 | 2.091 |
| 0.1783 | 42 | −0.4142 | 0.3487 | 4.962 |
| 0.8951 | 43 | −0.0813 | 1.068 | 2.744 |
| 1.105 | 44 | −1.545 | −0.6618 | 2.488 |
| −0.0853 | 45 | −1.493 | −0.8598 | 0.9202 |
| −0.2748 | 46 | −1.363 | −0.5361 | 2.487 |
| 0.5210 | 47 | −0.4644 | −0.1042 | 4.104 |
| 0.6841 | 48 | −2.361 | 1.539 | 3.850 |
| −0.1780 | 49 | −0.5411 | 1.574 | 2.602 |
| 2.771 | 50 | −0.8576 | 0.0270 | 2.080 |
| 0.6361 | 51 | −1.278 | −0.0511 | 1.110 |
| 0.7053 | 52 | −1.929 | 0.6697 | 1.026 |
| −0.8570 | 53 | −0.8664 | −0.6197 | 2.892 |
| −0.8005 | 54 | −2.572 | 0.0123 | 0.6071 |
| −1.660 | 55 | −1.149 | −0.7034 | 0.3651 |
| −0.9770 | 56 | 0.1476 | 0.2663 | 1.769 |
| −0.3713 | 57 | −1.911 | −1.401 | 0.9401 |
| −0.3495 | 58 | −1.097 | 0.0671 | 1.318 |
| 1.021 | 59 | −1.234 | 0.1320 | 3.443 |
| 2.209 | 60 | −2.769 | −0.5245 | 3.127 |
First 60 of 95 rows.
Mean squared error of the predicted noise on the target cells; lower is better.
View data
| Part | Loss (mean squared noise error) | Epoch |
|---|---|---|
| training windows | 0.9625 | 1 |
| training windows | 1.042 | 2 |
| training windows | 0.9193 | 3 |
| training windows | 0.9493 | 4 |
| training windows | 0.9206 | 5 |
| training windows | 0.8565 | 6 |
| training windows | 0.8467 | 7 |
| training windows | 0.8384 | 8 |
Assumptions
- Better than straight-line filling — On 95 hidden values the median imputation's mean absolute error is 1.08 against 0.783 for linear interpolation. A simpler method may serve as well; train longer or use more layers.
- Missing at random — The imputations are valid when whether a value is missing depends only on observed values (MAR); if values are missing because of what they would have been (MNAR), the imputations are biased.
- Enough observed values — The variable with the most gaps is 0% missing.
Imputed variables
| Variable | Missing | Observed mean | Imputed mean (median draws) | Mean 90% interval width |
|---|---|---|---|---|
| y1 | 0 | −0.0640 | — | — |
| y2 | 0 | −0.0732 | — | — |
Imputed values (first 0)
| Row | Variable | Median | Lower | Upper |
|---|
- No values are missing; the completed data sets equal the data.
- Seed 42; the 5 completed data sets are saved as imputed.parquet (long format with .imp and .id).
The exact R script · R R version 4.5.1 (2025-06-13)
# Diffusion imputation for multivariate series (CSDI)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method missing.csdi 1.0.0 · spec 07c0f186e36fa3ff
# Dataset: f7_var_panel (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr) # cs_csdi_* (score network on torch, shared draws), cs_ml_fc_to_days
# 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/missing.csdi/panel_two_layers_time/out-r")
# %% Data (no rows are dropped: the missing values are imputed)
VARIABLES <- c("y1", "y2")
TIME <- "month"
SERIES <- "region"
SEED <- 42
M <- as.integer(5)
LEVEL <- 0.9
cols <- unique(c(VARIABLES, TIME, SERIES))
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/f7_var_panel.parquet", col_select = cols))
n <- nrow(df)
K <- length(VARIABLES)
warnings <- list()
cs_check_finite_columns(df, c(VARIABLES, TIME)) # infinite values stop the run (registry/errors.yaml)
values_raw <- do.call(cbind, lapply(VARIABLES, function(v) suppressWarnings(as.numeric(df[[v]]))))
values_raw <- matrix(values_raw, nrow = n, ncol = K)
for (j in seq_len(K)) if (all(is.na(values_raw[, j]))) cs_error("CS_E_ALL_MISSING", column = VARIABLES[j])
cs_check_rows(n, 4, "CSDI imputation")
times <- NULL
if (!is.null(TIME)) {
times <- cs_ml_fc_to_days(df[[TIME]])$values
if (any(is.na(times))) cs_error("CS_E_INVALID_VALUES", column = TIME, requirement = "present on every row (it orders the rows)", count = sum(is.na(times)))
}
series <- NULL
if (!is.null(SERIES)) {
s <- df[[SERIES]]
if (sum(is.na(s))) cs_error("CS_E_INVALID_VALUES", column = SERIES, requirement = "present on every row (it names each row's series)", count = sum(is.na(s)))
series <- as.character(s)
}
if (8 %% 4 != 0) {
cs_error("CS_E_INVALID_OPTION", option = "Attention heads", allowed = "a divisor of the channels (8)", value = 4)
}
groups <- cs_csdi_grids(values_raw, series, times)
observed <- !is.na(values_raw)
L <- min(as.integer(12), min(vapply(groups, length, integer(1))))
if (L < 2L) cs_error("CS_E_TOO_FEW_ROWS", what = "Every series", min = 2, n = L)
# Hidden cells for the evaluation (a seeded share of the observed cells, row by row).
SHARE <- 0.2
hidden <- matrix(FALSE, n, K)
if (SHARE > 0) {
u <- matrix(cs_runif(cs_rng(SEED + 404), n * K), nrow = n, ncol = K, byrow = TRUE)
hidden <- observed & (u < SHARE)
}
known <- observed & !hidden
st <- cs_csdi_standardize(values_raw, known)
mu <- st$mu; sd <- st$sd
v0 <- values_raw; v0[is.na(v0)] <- 0
std <- sweep(sweep(v0, 2L, mu, "-"), 2L, sd, "/")
Z <- ifelse(known, std, 0)
# %% Train the score network and impute
model <- cs_csdi_fit(
Z, known, groups, L,
channels = 8,
layers = 2,
heads = 4,
diffusion_steps = 6,
online = FALSE,
epochs = 8,
lr = 0.005,
batch_size = 64,
seed = SEED
)
values <- list(n = n, n_vars = K, m = M, window_length = L, windows = model$windows, epochs_run = model$epochs_run, final_loss = model$final_loss)
assumptions <- list()
charts <- list()
tables <- list()
unstd <- function(d) { for (j in seq_len(K)) d[, , j] <- d[, , j] * sd[j] + mu[j]; d }
if (any(hidden)) {
ev <- unstd(cs_csdi_impute(model, Z, known, groups, M, SEED + 505))
sm <- cs_csdi_summarize(ev, LEVEL)
interp <- cs_csdi_interpolate(values_raw, known, groups)
idx <- which(t(hidden), arr.ind = TRUE) # row by row, as in Python
cells <- cbind(idx[, 2], idx[, 1])
truth <- values_raw[cells]
err <- abs(sm$med[cells] - truth)
values$eval_n <- nrow(cells)
values$eval_mae <- sum(err) / length(err)
values$eval_rmse <- sqrt(sum(err * err) / length(err))
values$eval_crps <- sum(vapply(seq_len(nrow(cells)), function(q) cs_tg_crps(ev[, cells[q, 1], cells[q, 2]], truth[q]), numeric(1))) / nrow(cells)
values$eval_coverage <- sum(as.numeric(sm$lo[cells] <= truth & truth <= sm$hi[cells])) / nrow(cells)
ip <- interp[cells]
ierr <- abs(ip - truth)[!is.na(ip)]
if (length(ierr)) values$interp_mae <- sum(ierr) / length(ierr)
for (j in seq_len(K)) {
e_j <- err[cells[, 2] == j]
if (length(e_j)) values[[sprintf("eval_mae[%s]", VARIABLES[j])]] <- sum(e_j) / length(e_j)
}
better <- !is.null(values$interp_mae) && values$eval_mae <= values$interp_mae
assumptions[[length(assumptions) + 1L]] <- list(
key = "beats_interpolation", label = "Better than straight-line filling",
status = if (better) "pass" else "warn",
detail = paste0(sprintf("On %d hidden values the median imputation's mean absolute error is %s", nrow(cells), format(signif(values$eval_mae, 3))),
if (!is.null(values$interp_mae)) sprintf(" against %s for linear interpolation.", format(signif(values$interp_mae, 3))) else ".",
if (better) "" else " A simpler method may serve as well; train longer or use more layers.")
)
ord <- order(cells[, 2], cells[, 1])[seq_len(min(400L, nrow(cells)))]
charts[[length(charts) + 1L]] <- cs_chart("evaluation", "interval-plot", "Hidden values and their imputations", list(
index = cs_col("Hidden value", seq_along(ord), "numeric"),
actual = cs_col("Actual", truth[ord], "numeric"),
pred = cs_col("Median imputation", sm$med[cells[ord, , drop = FALSE]], "numeric"),
lower = cs_col("Interval lower", sm$lo[cells[ord, , drop = FALSE]], "numeric"),
upper = cs_col("Interval upper", sm$hi[cells[ord, , drop = FALSE]], "numeric")
), note = sprintf("%d observed values hidden before training, grouped by variable; bars are %s intervals of the %d draws.", length(ord), sprintf("%.0f%%", LEVEL * 100), M))
}
Zall <- ifelse(observed, std, 0) # every observed cell conditions the final draws
draws <- unstd(cs_csdi_impute(model, Zall, observed, groups, M, SEED + 303))
for (s in seq_len(M)) draws[s, , ][observed] <- values_raw[observed]
sm <- cs_csdi_summarize(draws, LEVEL)
missing <- !observed
values$n_missing <- sum(missing)
values$pct_missing <- sum(missing) / (n * K)
imp_rows <- list()
for (j in seq_len(K)) {
v <- VARIABLES[j]
mj <- missing[, j]
values[[sprintf("missing[%s]", v)]] <- sum(mj)
ob <- values_raw[observed[, j], j]
values[[sprintf("observed_mean[%s]", v)]] <- sum(ob) / length(ob)
if (any(mj)) {
values[[sprintf("imputed_mean[%s]", v)]] <- sum(sm$med[mj, j]) / sum(mj)
values[[sprintf("interval_width[%s]", v)]] <- sum(sm$hi[mj, j] - sm$lo[mj, j]) / sum(mj)
}
imp_rows[[j]] <- list(variable = v, missing = sum(mj), observed = values[[sprintf("observed_mean[%s]", v)]],
imputed = values[[sprintf("imputed_mean[%s]", v)]], width = values[[sprintf("interval_width[%s]", v)]])
}
if (!any(missing)) warnings <- c(warnings, "No values are missing; the completed data sets equal the data.")
share_max <- max(colMeans(missing))
assumptions[[length(assumptions) + 1L]] <- list(
key = "mar", label = "Missing at random", status = "info",
detail = "The imputations are valid when whether a value is missing depends only on observed values (MAR); if values are missing because of what they would have been (MNAR), the imputations are biased."
)
assumptions[[length(assumptions) + 1L]] <- list(
key = "enough_observed", label = "Enough observed values",
status = if (share_max > 0.5) "warn" else "pass",
detail = paste0(sprintf("The variable with the most gaps is %s missing", sprintf("%.0f%%", share_max * 100)),
if (share_max > 0.5) " — over half, so its imputations lean on the other variables and the model's guesses." else ".")
)
# %% Imputed data sets (long format, like mice::complete(imp, "long"))
out <- cs_ml_out_dir("target/academy-parity/run-8142/missing.csdi/panel_two_layers_time/out-r")
parts <- lapply(seq_len(M), function(s) {
part <- data.frame(.imp = rep(s, n), .id = seq_len(n), check.names = FALSE)
for (j in seq_len(K)) part[[VARIABLES[j]]] <- draws[s, , j]
part
})
path <- file.path(out, "imputed.parquet")
nanoparquet::write_parquet(do.call(rbind, parts), path)
cidx <- which(missing, arr.ind = TRUE)
cidx <- cidx[order(cidx[, 2], cidx[, 1]), , drop = FALSE][seq_len(min(200L, nrow(cidx))), , drop = FALSE]
hist <- model$history
charts[[length(charts) + 1L]] <- cs_chart("training", "training-components", "Denoising loss by epoch", list(
x = cs_col("Epoch", vapply(hist, function(h) as.numeric(h$epoch), numeric(1)), "numeric"),
value = cs_col("Loss (mean squared noise error)", vapply(hist, function(h) h$loss, numeric(1)), "numeric"),
component = cs_col("Part", rep("training windows", length(hist)), "categorical", levels = c("training windows"))
), note = "Mean squared error of the predicted noise on the target cells; lower is better.")
tables[[length(tables) + 1L]] <- list(key = "imputation", title = "Imputed variables",
columns = list(list(key = "variable", label = "Variable", type = "string"), list(key = "missing", label = "Missing", type = "integer"),
list(key = "observed", label = "Observed mean", type = "number"), list(key = "imputed", label = "Imputed mean (median draws)", type = "number"),
list(key = "width", label = sprintf("Mean %s interval width", sprintf("%.0f%%", LEVEL * 100)), type = "number")),
rows = imp_rows)
tables[[length(tables) + 1L]] <- list(key = "cells", title = sprintf("Imputed values (first %d)", nrow(cidx)),
columns = list(list(key = "row", label = "Row", type = "integer"), list(key = "variable", label = "Variable", type = "string"),
list(key = "median", label = "Median", type = "number"), list(key = "low", label = "Lower", type = "number"),
list(key = "high", label = "Upper", type = "number")),
rows = lapply(seq_len(nrow(cidx)), function(q) list(row = cidx[q, 1], variable = VARIABLES[cidx[q, 2]], median = sm$med[cidx[q, , drop = FALSE]],
low = sm$lo[cidx[q, , drop = FALSE]], high = sm$hi[cidx[q, , drop = FALSE]])))
summary <- sprintf("%d missing values in %d variable%s were imputed %d times by conditional diffusion (CSDI).", values$n_missing, K, if (K != 1) "s" else "", M)
if (!is.null(values$eval_mae)) {
summary <- paste0(summary, sprintf(" On %d hidden values the median imputation's MAE was %s", values$eval_n, format(signif(values$eval_mae, 3))),
if (!is.null(values$interp_mae)) sprintf(" (linear interpolation %s).", format(signif(values$interp_mae, 3))) else ".")
}
cs_publish(list(
title = "Diffusion imputation for multivariate series (CSDI)",
engine = cs_engine_info("torch", "nanoparquet", "codesplashr"),
n = n,
summary = summary,
statistics = if (!is.null(values$eval_mae)) list(list(key = "eval_mae", label = "MAE on hidden values", value = values$eval_mae)) else list(),
tables = tables,
values = values,
assumptions = assumptions,
warnings = warnings,
notes = list(sprintf("Seed %d; the %d completed data sets are saved as imputed.parquet (long format with .imp and .id).", SEED, M)),
charts = charts,
artifacts = list(list(key = "imputed", path = path, format = "parquet", title = sprintf("%d imputed data sets (long format)", M)))
))
0 missing values in 2 variables were imputed 5 times by conditional diffusion (CSDI). On 95 hidden values the median imputation's MAE was 1.08 (linear interpolation 0.783).
- MAE on hidden values
- 1.079
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Better than straight-line filling — On 95 hidden values the median imputation's mean absolute error is 1.08 against 0.783 for linear interpolation. A simpler method may serve as well; train longer or use more layers.
- Missing at random — The imputations are valid when whether a value is missing depends only on observed values (MAR); if values are missing because of what they would have been (MNAR), the imputations are biased.
- Enough observed values — The variable with the most gaps is 0% missing.
Imputed variables
| Variable | Missing | Observed mean | Imputed mean (median draws) | Mean 90% interval width |
|---|---|---|---|---|
| y1 | 0 | −0.0640 | — | — |
| y2 | 0 | −0.0732 | — | — |
Imputed values (first 0)
| Row | Variable | Median | Lower | Upper |
|---|
- No values are missing; the completed data sets equal the data.
- Seed 42; the 5 completed data sets are saved as imputed.parquet (long format with .imp and .id).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Diffusion imputation for multivariate series (CSDI)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method missing.csdi 1.0.0 · spec 07c0f186e36fa3ff
# Dataset: f7_var_panel (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import math
import os
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash.deep import csdi # twin of codesplashr::cs_csdi_* (score network on torch, shared draws)
from codesplash.ml import forecast as fc # times as days; sequential sums
from codesplash.ml import run as csml # artifact directory
from codesplash.stats.rng import Rng
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/missing.csdi/panel_two_layers_time/out-python",
)
# %% Data (no rows are dropped: the missing values are imputed)
VARIABLES = ["y1", "y2"]
TIME = "month"
SERIES = "region"
SEED = 42
M = 5
LEVEL = 0.9
cols = list(dict.fromkeys(VARIABLES + [c for c in (TIME, SERIES) if c]))
df = pd.read_parquet("tests/parity/fixtures/f7_var_panel.parquet", columns=cols)
n = len(df)
K = len(VARIABLES)
warnings = []
cs.check_finite_columns(df, VARIABLES + ([TIME] if TIME else [])) # infinite values stop the run (registry/errors.yaml)
values_raw = np.column_stack([pd.to_numeric(df[v], errors="coerce").to_numpy(dtype=np.float64) for v in VARIABLES])
for j, v in enumerate(VARIABLES):
if bool(np.isnan(values_raw[:, j]).all()):
cs.cs_error("CS_E_ALL_MISSING", column=v)
cs.check_rows(n, 4, "CSDI imputation")
times = None
if TIME:
times = fc.to_days(df[TIME].to_numpy())[0]
if bool(np.isnan(times).any()):
cs.cs_error("CS_E_INVALID_VALUES", column=TIME, requirement="present on every row (it orders the rows)", count=int(np.isnan(times).sum()))
series = None
if SERIES:
s = df[SERIES]
if int(s.isna().sum()):
cs.cs_error("CS_E_INVALID_VALUES", column=SERIES, requirement="present on every row (it names each row's series)", count=int(s.isna().sum()))
series = s.astype(str).to_numpy(dtype=object)
if 8 % 4 != 0:
cs.cs_error("CS_E_INVALID_OPTION", option="Attention heads", allowed="a divisor of the channels (8)", value=4)
groups = csdi.grids(values_raw, series, times)
observed = ~np.isnan(values_raw)
L = min(int(12), min(len(g) for g in groups))
if L < 2:
cs.cs_error("CS_E_TOO_FEW_ROWS", what="Every series", min=2, n=L)
# Hidden cells for the evaluation (a seeded share of the observed cells, row by row).
SHARE = 0.2
hidden = np.zeros_like(observed)
if SHARE > 0:
u = Rng(SEED + 404).uniform(n * K).reshape(n, K)
hidden = observed & (u < SHARE)
known = observed & ~hidden
mu, sd = csdi.standardize(values_raw, known)
Z = np.where(known, (np.nan_to_num(values_raw) - mu) / sd, 0.0)
# %% Train the score network and impute
model = csdi.fit_csdi(
Z, known, groups, L,
channels=8,
layers=2,
heads=4,
diffusion_steps=6,
online=False,
epochs=8,
lr=0.005,
batch_size=64,
seed=SEED,
)
values = {"n": n, "n_vars": K, "m": M, "window_length": L, "windows": model["windows"], "epochs_run": model["epochs_run"], "final_loss": model["final_loss"]}
assumptions = []
charts = []
tables = []
evaluation = None
if bool(hidden.any()):
ev = csdi.impute(model, Z, known, groups, M, SEED + 505) * sd + mu
med, lo, hi = csdi.summarize(ev, LEVEL)
interp = csdi.interpolate(values_raw, known, groups)
cells = [(i, j) for i in range(n) for j in range(K) if hidden[i, j]]
truth = [values_raw[i, j] for i, j in cells]
err = [abs(med[i, j] - t) for (i, j), t in zip(cells, truth)]
values["eval_n"] = len(cells)
values["eval_mae"] = fc._mean(err)
values["eval_rmse"] = math.sqrt(fc._mean([e * e for e in err]))
values["eval_crps"] = fc._mean([csdi.crps(ev[:, i, j], t) for (i, j), t in zip(cells, truth)])
values["eval_coverage"] = fc._mean([1.0 if lo[i, j] <= t <= hi[i, j] else 0.0 for (i, j), t in zip(cells, truth)])
ierr = [abs(interp[i, j] - t) for (i, j), t in zip(cells, truth) if not math.isnan(interp[i, j])]
if ierr:
values["interp_mae"] = fc._mean(ierr)
for j, v in enumerate(VARIABLES):
e_j = [e for (i, jj), e in zip(cells, err) if jj == j]
if e_j:
values[f"eval_mae[{v}]"] = fc._mean(e_j)
better = "interp_mae" in values and values["eval_mae"] <= values["interp_mae"]
assumptions.append({
"key": "beats_interpolation",
"label": "Better than straight-line filling",
"status": "pass" if better else "warn",
"detail": (f"On {len(cells)} hidden values the median imputation's mean absolute error is {values['eval_mae']:.3g}"
+ (f" against {values['interp_mae']:.3g} for linear interpolation." if "interp_mae" in values else ".")
+ ("" if better else " A simpler method may serve as well; train longer or use more layers.")),
})
order = sorted(range(len(cells)), key=lambda c: (cells[c][1], cells[c][0]))[:400]
charts.append(cs.chart("evaluation", "interval-plot", "Hidden values and their imputations", {
"index": cs.col("Hidden value", list(range(1, len(order) + 1)), "numeric"),
"actual": cs.col("Actual", [truth[c] for c in order], "numeric"),
"pred": cs.col("Median imputation", [float(med[cells[c]]) for c in order], "numeric"),
"lower": cs.col("Interval lower", [float(lo[cells[c]]) for c in order], "numeric"),
"upper": cs.col("Interval upper", [float(hi[cells[c]]) for c in order], "numeric"),
}, note=f"{len(order)} observed values hidden before training, grouped by variable; bars are {LEVEL:.0%} intervals of the {M} draws."))
Zall = np.where(observed, (np.nan_to_num(values_raw) - mu) / sd, 0.0) # every observed cell conditions the final draws
draws = csdi.impute(model, Zall, observed, groups, M, SEED + 303)
draws = np.where(observed[None, :, :], values_raw[None, :, :], draws * sd + mu)
med, lo, hi = csdi.summarize(draws, LEVEL)
missing = ~observed
values["n_missing"] = int(missing.sum())
values["pct_missing"] = float(missing.sum()) / float(n * K)
imp_rows = []
for j, v in enumerate(VARIABLES):
mj = missing[:, j]
values[f"missing[{v}]"] = int(mj.sum())
values[f"observed_mean[{v}]"] = fc._mean(values_raw[observed[:, j], j].tolist())
if mj.any():
values[f"imputed_mean[{v}]"] = fc._mean(med[mj, j].tolist())
values[f"interval_width[{v}]"] = fc._mean((hi[mj, j] - lo[mj, j]).tolist())
imp_rows.append({"variable": v, "missing": int(mj.sum()), "observed": values[f"observed_mean[{v}]"], "imputed": values.get(f"imputed_mean[{v}]"),
"width": values.get(f"interval_width[{v}]")})
if not missing.any():
warnings.append("No values are missing; the completed data sets equal the data.")
share_max = max(float(missing[:, j].mean()) for j in range(K))
assumptions.append({
"key": "mar",
"label": "Missing at random",
"status": "info",
"detail": "The imputations are valid when whether a value is missing depends only on observed values (MAR); if values are missing because of what they would have been (MNAR), the imputations are biased.",
})
assumptions.append({
"key": "enough_observed",
"label": "Enough observed values",
"status": "warn" if share_max > 0.5 else "pass",
"detail": f"The variable with the most gaps is {share_max:.0%} missing" + (" — over half, so its imputations lean on the other variables and the model's guesses." if share_max > 0.5 else "."),
})
# %% Imputed data sets (long format, like mice::complete(imp, "long"))
out = csml.out_dir("target/academy-parity/run-8142/missing.csdi/panel_two_layers_time/out-python")
parts = []
for s in range(M):
part = {".imp": np.full(n, s + 1), ".id": np.arange(1, n + 1)}
for j, v in enumerate(VARIABLES):
part[v] = draws[s, :, j]
parts.append(pd.DataFrame(part))
path = os.path.join(out, "imputed.parquet")
pd.concat(parts, ignore_index=True).to_parquet(path, index=False)
cells = [(i, j) for j in range(K) for i in range(n) if missing[i, j]][:200]
hist = model["history"]
charts.append(cs.chart("training", "training-components", "Denoising loss by epoch", {
"x": cs.col("Epoch", [h["epoch"] for h in hist], "numeric"),
"value": cs.col("Loss (mean squared noise error)", [h["loss"] for h in hist], "numeric"),
"component": cs.col("Part", ["training windows"] * len(hist), "categorical", levels=["training windows"]),
}, note="Mean squared error of the predicted noise on the target cells; lower is better."))
tables.append({"key": "imputation", "title": "Imputed variables",
"columns": [{"key": "variable", "label": "Variable", "type": "string"}, {"key": "missing", "label": "Missing", "type": "integer"},
{"key": "observed", "label": "Observed mean", "type": "number"}, {"key": "imputed", "label": "Imputed mean (median draws)", "type": "number"},
{"key": "width", "label": f"Mean {LEVEL:.0%} interval width", "type": "number"}],
"rows": imp_rows})
tables.append({"key": "cells", "title": f"Imputed values (first {len(cells)})",
"columns": [{"key": "row", "label": "Row", "type": "integer"}, {"key": "variable", "label": "Variable", "type": "string"},
{"key": "median", "label": "Median", "type": "number"}, {"key": "low", "label": "Lower", "type": "number"},
{"key": "high", "label": "Upper", "type": "number"}],
"rows": [{"row": i + 1, "variable": VARIABLES[j], "median": float(med[i, j]), "low": float(lo[i, j]), "high": float(hi[i, j])} for i, j in cells]})
summary = f"{values['n_missing']} missing values in {K} variable{'s' if K != 1 else ''} were imputed {M} times by conditional diffusion (CSDI)."
if "eval_mae" in values:
summary += f" On {values['eval_n']} hidden values the median imputation's MAE was {values['eval_mae']:.3g}"
summary += f" (linear interpolation {values['interp_mae']:.3g})." if "interp_mae" in values else "."
cs.publish({
"title": "Diffusion imputation for multivariate series (CSDI)",
"engine": cs.engine_info("torch", "pyarrow", "codesplash", "numpy", "pandas"),
"n": n,
"summary": summary,
"statistics": [{"key": "eval_mae", "label": "MAE on hidden values", "value": values["eval_mae"]}] if "eval_mae" in values else [],
"tables": tables,
"values": values,
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"Seed {SEED}; the {M} completed data sets are saved as imputed.parquet (long format with .imp and .id)."],
"charts": charts,
"artifacts": [{"key": "imputed", "path": path, "format": "parquet", "title": f"{M} imputed data sets (long format)"}],
})
On this smooth panel the result flips: 1.079 for the masked model against 0.783 for straight lines. A masked-prediction model is only worth its cost where it beats the simple filler on hidden values. The same holds for MAE features: check them against simpler features on the task you care about.
What runs here
ReadCheck: masked prediction
CheckpointCheck yourself
Which patches does a masked autoencoder's loss score?
Show the answer
Answer: b
Scoring visible patches would reward copying. The task is to fill in what the encoder never saw.
Check yourself
Why do masked autoencoders for images hide a large share of patches, such as three quarters?
Show the answer
Answer: a
Images are redundant. A high masking ratio removes easy shortcuts, and encoding only the visible patches cuts the cost.
Check yourself
Where does CodeSplash run masked self-supervised training today?
Show the answer
Answer: b
The autoencoder's masked-feature objective isn't built yet; MAE is marked partly running. CSDI's training hides observed values and learns to predict them.
Check yourself
What does I-JEPA predict for hidden regions?
Show the answer
Answer: b
Predicting in representation space lets the model skip unpredictable pixel detail. The target encoder is a momentum average with no gradient.
Check yourself
Predicting representations invites a trivial answer: make every representation the same. What guards against it in I-JEPA?
Show the answer
Answer: a
The slowly moving, stop-gradient target is the asymmetry that prevents collapse, as in the teacher–student methods.
Recap
Recap- MAE hides most patches, encodes the visible ones and scores only the hidden ones.
- I-JEPA predicts a slow target encoder's representations of hidden blocks instead of pixels.
- Masked training runs in CodeSplash's CSDI imputation, with a hidden-value check against straight-line filling.
- The simple baseline can win; check masked models against it.
Concepts in this lesson