Skip to content

Diffusion imputation for series (CSDI)

Fill the gaps in several daily measurements with a conditional diffusion model, check it on values you hid on purpose, and compare it with straight-line filling before you use its imputations.

Advanced ~12 min6 steps

What runs in CodeSplash

You will be able to

  • Explain how CSDI learns to impute by hiding observed values from itself
  • Check an imputation method on hidden values against a simple baseline
  • Read an imputed value's interval, and say what missing-at-random still requires

Read first

01

Gaps in measurements over time

Read

Ozone readings in the New York air-quality data have 37 gaps over five months. Neighbors in time and the other measurements (wind, temperature) both hint at a missing value. MICE uses the other variables row by row and ignores time.

CSDICSDI (conditional score-based diffusion imputation)Imputes series by denoising each gap from random noise, conditioned on every observed value, several times over. uses both. During training it hides a random share of the observed cells (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.) and learns to denoise them back from the rest, attending across time and variables. To impute, each real gap starts as noise and is denoised step by step, conditioned on every observed cell. Repeating it m times gives each filled value an interval.

02

Hide some values, then check

Predict

Predict first

Before imputing, the run hides 10% of the observed values, trains a small CSDI model for a few epochs, and imputes the hidden values. How does its median imputation compare with joining the neighboring values by straight lines?

Straight-line filling wins easilyAbout the same, maybe a little betterFar better, errors cut in half
Reveal

About the same, a little better: the mean absolute error on the hidden values is 24.0 against 26.0 for linear interpolation. A larger model trained longer often pulls ahead; when it doesn't, the simple method is the honest choice.

Diffusion imputation for multivariate series (CSDI)Recorded · Python and R agreeRecorded 2026-11-25 · 31 values compared
R

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

Hidden values and their imputationsWhich observations fall outside their prediction intervals, and how wide are the intervals?

53 observed values hidden before training, grouped by variable; bars are 90% intervals of the 8 draws.

View data
ActualHidden valueInterval lowerMedian imputationInterval upper
231−12.45816.28359.738
142−8.54522.08859.281
45313.74053.33167.350
39426.06642.55092.826
20523.17147.88476.589
79636.17442.34868.305
20733.41450.83065.928
7886.90252.98083.704
9938.85549.81287.250
32101.60715.60636.459
2411−1.46156.273114.08
1312−30.289−5.52835.990
29013123.51292.80473.42
6514−66.364161.44319.35
441510.124137.94257.25
981694.419179.50442.38
27217107.14217.71256.27
20718111.84203.93309.26
511995.915161.72240.53
2592067.787133.46252.81
21221140.33240.15356.72
1892264.760166.96368.92
922390.435202.84263.07
202480.785164.37484.45
22325111.57191.24312.16
8.600267.05610.93313.240
5.700275.1189.01811.601
5.100282.4708.04813.836
8.600293.7118.10915.503
10.300306.80912.15915.577
10.300312.5528.42020.091
5.700321.4476.9829.963
6.300333.1438.49011.399
7.400340.86246.8369.120
6.900357.41210.88118.391
6.9003610.14012.78119.217
14.3003710.05312.09217.261
683855.87463.18195.081
643946.69271.108107.87
804080.67387.21693.534
774180.59583.199103.27
654274.20579.10382.048
774373.20879.66296.448
834478.52485.749104.83
884565.86385.18289.751
804679.44784.51786.733
884775.43784.72498.248
904868.46676.48389.254
824977.97582.34692.094
805075.91881.64698.203
865176.08086.74798.517
945278.17092.665109.58
825365.57872.51579.304
Denoising loss by epochIs the network still learning, and which part of its loss moves?

Mean squared error of the predicted noise on the target cells; lower is better.

View data
PartLoss (mean squared noise error)Epoch
training windows1.0101
training windows0.97272
training windows0.93393
training windows0.93144
training windows0.85765
training windows0.80096
training windows0.74407
training windows0.79518
training windows0.75139
training windows0.759710
training windows0.708111
training windows0.696912

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

VariableMissingObserved meanImputed mean (median draws)Mean 90% interval width
Ozone3742.12942.09879.282
Solar.R7185.93182.72301.48
Wind09.958——
Temp077.882——

Imputed values (first 44)

RowVariableMedianLowerUpper
5Ozone6.761−24.80096.250
10Ozone16.907−5.23262.877
25Ozone38.2204.16360.974
26Ozone37.242−7.62767.069
27Ozone17.248−11.93268.697
32Ozone36.937−29.02290.164
33Ozone53.20531.736149.01
34Ozone49.80635.98358.109
35Ozone62.991−2.81573.972
36Ozone51.18721.369122.07
37Ozone43.804−3.69498.276
39Ozone39.7113.38459.510
42Ozone47.67132.766124.87
43Ozone34.5707.578125.30
45Ozone34.00310.94457.183
46Ozone37.492−13.406144.97
52Ozone34.3845.26257.087
53Ozone45.09324.360101.11
54Ozone39.96614.562125.19
55Ozone29.332−17.39352.024
56Ozone35.979−5.04789.959
57Ozone32.346−14.67950.322
58Ozone52.737−6.15167.008
59Ozone56.06110.81085.408
60Ozone40.83518.05256.773
61Ozone42.616−15.45963.957
65Ozone42.71014.62563.421
72Ozone46.490−0.178196.153
75Ozone56.57724.09997.345
83Ozone39.877−3.81059.896
84Ozone49.59933.93192.942
102Ozone56.75326.12398.475
103Ozone43.8056.89273.946
107Ozone43.58612.29998.083
115Ozone82.80833.606109.78
119Ozone55.63745.169128.71
150Ozone22.673−16.79346.233
5Solar.R136.4151.901362.64
6Solar.R142.38105.92273.75
11Solar.R208.95146.78274.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)))
))
Python

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

VariableMissingObserved meanImputed mean (median draws)Mean 90% interval width
Ozone3742.12942.09879.282
Solar.R7185.93182.72301.48
Wind09.958——
Temp077.882——

Imputed values (first 44)

RowVariableMedianLowerUpper
5Ozone6.761−24.80096.250
10Ozone16.907−5.23262.877
25Ozone38.2204.16360.974
26Ozone37.242−7.62767.069
27Ozone17.248−11.93268.697
32Ozone36.937−29.02290.164
33Ozone53.20531.736149.01
34Ozone49.80635.98358.109
35Ozone62.991−2.81573.972
36Ozone51.18721.369122.07
37Ozone43.804−3.69498.276
39Ozone39.7113.38459.510
42Ozone47.67132.766124.87
43Ozone34.5707.578125.30
45Ozone34.00310.94457.183
46Ozone37.492−13.406144.97
52Ozone34.3845.26257.087
53Ozone45.09324.360101.11
54Ozone39.96614.562125.19
55Ozone29.332−17.39352.024
56Ozone35.979−5.04789.959
57Ozone32.346−14.67950.322
58Ozone52.737−6.15167.008
59Ozone56.06110.81085.408
60Ozone40.83518.05256.773
61Ozone42.616−15.45963.957
65Ozone42.71014.62563.421
72Ozone46.490−0.178196.153
75Ozone56.57724.09997.345
83Ozone39.877−3.81059.896
84Ozone49.59933.93192.942
102Ozone56.75326.12398.475
103Ozone43.8056.89273.946
107Ozone43.58612.29998.083
115Ozone82.80833.606109.78
119Ozone55.63745.169128.71
150Ozone22.673−16.79346.233
5Solar.R136.4151.901362.64
6Solar.R142.38105.92273.75
11Solar.R208.95146.78274.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)"}],
})

The hidden-value checkHidden-value checkHide some observed values, impute them, and compare with the truth and with straight-line filling before trusting an imputer. scored 53 values. In Hidden values and their imputations each bar is a 90% interval from the draws, the truth a dot. 71.7% fall inside; a calibrated model covers about 90%.

03

Only the past, or both sides?

Explore

Cleaning a finished series can use observations after a gap. Imputing as data arrives can't. With Past only, the attention over time is masked so a step sees only itself and earlier steps. This run also treats each month as its own series.

Diffusion imputation for multivariate series (CSDI)Recorded · Python and R agreeRecorded 2026-11-25 · 17 values compared
R

37 missing values in 3 variables were imputed 6 times by conditional diffusion (CSDI).

Plots

Denoising loss by epochIs the network still learning, and which part of its loss moves?

Mean squared error of the predicted noise on the target cells; lower is better.

View data
PartLoss (mean squared noise error)Epoch
training windows0.95461
training windows1.0692
training windows1.0383
training windows0.93594
training windows0.93785
training windows0.95596
training windows0.92597
training windows0.96208
training windows0.98389
training windows1.00910

Assumptions

  • 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

VariableMissingObserved meanImputed mean (median draws)Mean 80% interval width
Ozone3742.12937.040159.31
Wind09.958——
Temp077.882——

Imputed values (first 37)

RowVariableMedianLowerUpper
5Ozone24.541−10.66288.340
10Ozone64.5198.938114.95
25Ozone18.910−44.09276.710
26Ozone11.428−57.69882.410
27Ozone140.6431.309152.24
32Ozone56.822−0.0612195.93
33Ozone68.426−45.997173.71
34Ozone25.042−68.40997.120
35Ozone39.793−145.92154.74
36Ozone64.31217.36082.977
37Ozone25.488−46.794123.56
39Ozone45.734−4.76480.762
42Ozone23.230−41.99079.085
43Ozone38.870−20.678118.69
45Ozone12.022−73.452131.12
46Ozone88.62222.166156.69
52Ozone32.972−46.344138.43
53Ozone27.063−40.20594.029
54Ozone29.189−30.47964.859
55Ozone26.991−105.7754.571
56Ozone53.664−29.387120.32
57Ozone32.612−15.087103.57
58Ozone−1.339−34.40689.212
59Ozone94.891−30.920110.75
60Ozone39.059−47.058107.56
61Ozone42.372−104.55165.27
65Ozone72.182−86.923119.00
72Ozone29.230−43.089127.52
75Ozone−2.015−125.7284.455
83Ozone−16.809−71.363106.91
84Ozone1.963−105.04140.90
102Ozone64.680−20.25593.437
103Ozone−51.543−113.52118.50
107Ozone70.607−24.924185.17
115Ozone55.264−13.14473.131
119Ozone1.897−17.51791.201
150Ozone19.145−87.011123.29
  • Seed 42; the 6 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 0294d600684cd8b8
# 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_online_by_month/out-r")

# %% Data (no rows are dropped: the missing values are imputed)
VARIABLES <- c("Ozone", "Wind", "Temp")
TIME <- NULL
SERIES <- "month_f"
SEED <- 42
M <- as.integer(6)
LEVEL <- 0.8
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 %% 1 != 0) {
  cs_error("CS_E_INVALID_OPTION", option = "Attention heads", allowed = "a divisor of the channels (8)", value = 1)
}
groups <- cs_csdi_grids(values_raw, series, times)
observed <- !is.na(values_raw)
L <- min(as.integer(10), 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
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 = 1,
  diffusion_steps = 8,
  online = TRUE,
  epochs = 10,
  lr = 0.005,
  batch_size = NULL,
  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_online_by_month/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)))
))
Python

37 missing values in 3 variables were imputed 6 times by conditional diffusion (CSDI).

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

Assumptions

  • 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

VariableMissingObserved meanImputed mean (median draws)Mean 80% interval width
Ozone3742.12937.040159.31
Wind09.958——
Temp077.882——

Imputed values (first 37)

RowVariableMedianLowerUpper
5Ozone24.541−10.66288.340
10Ozone64.5198.938114.95
25Ozone18.910−44.09276.710
26Ozone11.428−57.69882.410
27Ozone140.6431.309152.24
32Ozone56.822−0.0612195.93
33Ozone68.426−45.997173.71
34Ozone25.042−68.40997.120
35Ozone39.793−145.92154.74
36Ozone64.31217.36082.977
37Ozone25.488−46.794123.56
39Ozone45.734−4.76480.762
42Ozone23.230−41.99079.085
43Ozone38.870−20.678118.69
45Ozone12.022−73.452131.12
46Ozone88.62222.166156.69
52Ozone32.972−46.344138.43
53Ozone27.063−40.20594.029
54Ozone29.189−30.47964.859
55Ozone26.991−105.7754.571
56Ozone53.664−29.387120.32
57Ozone32.612−15.087103.57
58Ozone−1.339−34.40689.212
59Ozone94.891−30.920110.75
60Ozone39.059−47.058107.56
61Ozone42.372−104.55165.27
65Ozone72.182−86.923119.00
72Ozone29.230−43.089127.52
75Ozone−2.015−125.7284.455
83Ozone−16.809−71.363106.91
84Ozone1.963−105.04140.90
102Ozone64.680−20.25593.437
103Ozone−51.543−113.52118.50
107Ozone70.607−24.924185.17
115Ozone55.264−13.14473.131
119Ozone1.897−17.51791.201
150Ozone19.145−87.011123.29
  • Seed 42; the 6 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 0294d600684cd8b8
# 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_online_by_month/out-python",
)

# %% Data (no rows are dropped: the missing values are imputed)
VARIABLES = ["Ozone", "Wind", "Temp"]
TIME = None
SERIES = "month_f"
SEED = 42
M = 6
LEVEL = 0.8
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 % 1 != 0:
    cs.cs_error("CS_E_INVALID_OPTION", option="Attention heads", allowed="a divisor of the channels (8)", value=1)
groups = csdi.grids(values_raw, series, times)
observed = ~np.isnan(values_raw)
L = min(int(10), 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
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=1,
    diffusion_steps=8,
    online=True,
    epochs=10,
    lr=0.005,
    batch_size=None,
    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_online_by_month/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)"}],
})

Its intervals for ozone are wider (a mean width of 159 against 79 with both sides): without the values that come after a gap, the model is less sure.

04

Check your understanding

Checkpoint

Check yourself

How does CSDI learn to impute when the true values of the real gaps are never known?

Show the answer

Answer: a

Training hides a random share of the observed cells in each window and learns to denoise exactly those, so every training target is a real value.

Check yourself

On the hidden values, CSDI's mean absolute error is 1.08 and linear interpolation's is 0.78. What should you do?

Show the answer

Answer: a

The hidden-value check is the evidence. If a straight line does better, the model has not learned the series well enough; more training or a larger model may change that, but only a new check can tell.

Check yourself

Ozone sensors fail more often on very hot, very polluted days. What does that mean for CSDI's imputations?

Show the answer

Answer: a

If values are missing because of what they would have been, the observed values give a skewed picture. CSDI, like MICE, assumes missingness depends only on what is observed (MAR).

05

Do it on your own data

In the app

Under Analyze, ask to describe missing values, then pick Diffusion imputation for multivariate series (CSDI). Keep the hidden share for checking, compare with linear interpolation, and save the completed data sets if it wins.

Python
import numpy as np
from codesplash.deep import csdi

# X: n × K values with NaN for gaps, rows in time order (one series)
obs = ~np.isnan(X)
groups = csdi.grids(X, None, None)
mu, sd = csdi.standardize(X, obs)
Z = np.where(obs, (np.nan_to_num(X) - mu) / sd, 0.0)
model = csdi.fit_csdi(Z, obs, groups, 16, channels=8, layers=1, heads=2, diffusion_steps=10, epochs=12, lr=0.005, seed=7)
draws = csdi.impute(model, Z, obs, groups, 8, 7 + 303) * sd + mu  # 8 imputations
R
library(codesplashr)

obs <- !is.na(X)
groups <- cs_csdi_grids(X, NULL, NULL)
st <- cs_csdi_standardize(X, obs)
Z <- ifelse(obs, sweep(sweep(ifelse(obs, X, 0), 2, st$mu), 2, st$sd, "/"), 0)
model <- cs_csdi_fit(Z, obs, groups, 16L, channels = 8L, layers = 1L, heads = 2L, diffusion_steps = 10L, epochs = 12L, lr = 0.005, seed = 7)
draws <- cs_csdi_impute(model, Z, obs, groups, 8L, 7 + 303)  # standardized; multiply by st$sd and add st$mu
06

Recap

Recap
  • CSDI learns to impute by hiding observed values from itself, using neighbors in time and the other variables.
  • Several draws per gap give an interval; check calibration and accuracy on hidden values against straight-line filling.
  • Past-only conditioning suits data that arrive over time; like MICE, CSDI still assumes values are missing at random.

Concepts in this lesson