Skip to content

Irregular times and event streams: neural CDEs, TGN and DenStream

Data arrive at uneven times, as timed interactions, or as an endless stream. A neural CDE lets observed changes drive its state; a temporal graph network keeps a memory per node; DenStream keeps fading summaries.

Advanced ~16 min12 steps

What runs in CodeSplash

You will be able to

  • Compute one controlled update of a neural CDE's hidden state
  • Explain why the interpolation choice decides whether a CDE can be used live
  • Compute a gated memory update and name the leak a temporal graph network must avoid
  • Compute fading weights and an effective count for a stream summary

Read first

01

When the clock is uneven

Read

A patient is measured when they visit, a machine logs when something changes, users interact whenever they like. Forcing such data onto a regular grid means filling or dropping values, and the timing itself, which may carry information, gets lost.

This lesson covers three ways to keep the timing: a continuous-time network for irregular sequences, a memory model for timed interactions between entities, and a bounded-memory summary for a stream that never ends.

02

Neural CDEs: changes drive the state

Read

A neural CDENeural controlled differential equationA hidden state that follows a sequence drawn as a continuous path: dz = f(z)·dX, so uneven gaps are handled by the path itself. first builds a control pathControl pathThe continuous curve a neural CDE builds through a sequence's observations, with time as one channel; straight lines or a cubic spline. XsX_s through the observations, usually with time as one channel. Its hidden state then changes in response to how the path changes:

zt=zt0+∫t0tfθ(zs) dXs.z_t = z_{t_0} + \int_{t_0}^{t} f_\theta(z_s)\, dX_s .

fθf_\theta outputs a matrix that turns each small change dXsdX_s into a change in zz. Long gaps with no change move the state little; a jump moves it a lot. A readout maps the final state to the prediction.

Reference · SEQ003 · Runs in CodeSplashNeural controlled differential equation (Neural CDE)A continuous-time sequence model whose hidden state is driven by an interpolated observation path. It handles irregular measurements by separating the observed control path from learned hidden dynamics.
03

One controlled step

Explore

With a straight-line path, one Euler step is z+f(z) ΔXz + f(z)\,\Delta X. The reference uses a fixed matrix for ff, the state (0.2,−0.1)(0.2, -0.1) and a path increment (0.4,0.2)(0.4, 0.2); the new state is (0.66, −0.08).

Python
import numpy as np
z = np.array([.2, -.1]); field = np.array([[1., .3], [-.2, .5]])   # f(z), fixed here
dX = np.array([.4, .2])                                            # change in the control path
print(z + field @ dX)
R
z <- c(.2, -.1); field <- rbind(c(1, .3), c(-.2, .5))               # f(z), fixed here
dX <- c(.4, .2)                                                    # change in the control path
print(drop(z + field %*% dX))

A natural cubic spline path is smoother, but its shape between two points depends on later points. A model trained that way can't be used on live data.

04

A neural CDE on irregular sequences

Explore
Neural controlled differential equation (irregular sequences)Recorded · Python and R agreeRecorded 2026-11-25 · 28 values compared
R

Neural controlled differential equation (irregular sequences): cross-validated RMSE 0.235 ± 0.060 over 3 folds; RMSE on the locked test set 0.142 (n = 92).

CV RMSE
0.2354
SD across folds
0.0604
Test RMSE
0.1422

Plots

Training curves (final model)Is the network still learning, and when did it start to overfit?
View data
NetworkEpochTraining lossValidation loss
Neural CDE14.2880.7959
Neural CDE20.88071.014
Neural CDE30.70191.067
Neural CDE40.62960.9548
Neural CDE50.53940.8177
Neural CDE60.42260.6572
Neural CDE70.34270.5430
Neural CDE80.28430.4610
Neural CDE90.23400.4003
Neural CDE100.19380.3525
Neural CDE110.16110.3127
Neural CDE120.12760.2669
Neural CDE130.10260.2300
Neural CDE140.08930.2040
Neural CDE150.07740.1946
Neural CDE160.06880.1848
Neural CDE170.06490.1805
Neural CDE180.06000.1906
Neural CDE190.05370.2013
Neural CDE200.04840.2080
Neural CDE210.04380.2081
Neural CDE220.03990.2106
Neural CDE230.03740.2109
Neural CDE240.03620.2101
Neural CDE250.03370.2064

Cross-validation

FoldRepeatnRMSEMAER²MAPE
111220.22790.12630.75830.0851
211220.17910.15480.79590.1335
311220.29920.21890.49820.3649

Training curves

NetworkEpochTraining lossValidation loss
Neural CDE14.2880.7959
Neural CDE20.88071.014
Neural CDE30.70191.067
Neural CDE40.62960.9548
Neural CDE50.53940.8177
Neural CDE60.42260.6572
Neural CDE70.34270.5430
Neural CDE80.28430.4610
Neural CDE90.23400.4003
Neural CDE100.19380.3525
Neural CDE110.16110.3127
Neural CDE120.12760.2669
Neural CDE130.10260.2300
Neural CDE140.08930.2040
Neural CDE150.07740.1946
Neural CDE160.06880.1848
Neural CDE170.06490.1805
Neural CDE180.06000.1906
Neural CDE190.05370.2013
Neural CDE200.04840.2080
Neural CDE210.04380.2081
Neural CDE220.03990.2106
Neural CDE230.03740.2109
Neural CDE240.03620.2101
Neural CDE250.03370.2064
The exact R script · R R version 4.5.1 (2025-06-13)
# Neural controlled differential equation (irregular sequences)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method learn.neural_cde 1.0.0 · spec 15b97981456297b5
# Dataset: gen_irregular_seq (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)
# torch for R (LibTorch); the network is built by codesplashr's cs_deep_fit_neural_cde twin.

# %% Data and split plan
TARGET <- "omega"
FEATURES <- c("x1", "x2")
TASK <- "regression"
CLASSES <- c()
POSITIVE <- NULL
METRIC <- "rmse"
SEED <- 42
PARAMS <- list(
  interpolation = "linear",
  solver = "euler",
  steps = 24,
  hidden_size = 6,
  width = 12,
  vf_layers = 1,
  epochs = 40,
  learning_rate = 0.01,
  batch_size = 12,
  weight_decay = 0,
  early_stopping = 8,
  validation_fraction = 0.2,
  optimizer = "default",
  lr_schedule = "none",
  warmup_epochs = 0,
  grad_clip = 0,
  ema_decay = 0,
  swa_start = 0,
  label_smoothing = 0,
  mixup_alpha = 0,
  history_every_step = FALSE,
  profile = "parity",
  checkpoint_every = NULL
)

df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/gen_irregular_seq.parquet", col_select = unique(c(TARGET, FEATURES))))
plan <- cs_ml_read_plan("target/academy-parity/run-8142/learn.neural_cde/regression_irregular_euler/folds.parquet")  # host-written folds: identical in Python and R
design <- cs_ml_design(
  df, FEATURES,
  kinds = list(
    x1 = "numeric",
    x2 = "numeric"
  ),
  levels = list(
  ),
  impute = "median",
  scale = "standard",
  indicators = FALSE
)
target <- cs_ml_encode_target(df[[TARGET]], TASK, CLASSES, POSITIVE)
y <- target$fit
y_index <- target$index
weights <- cs_ml_class_weights(y_index, TASK, "none", plan$train)
run <- cs_ml_run(TASK, CLASSES, POSITIVE, METRIC)
out <- cs_ml_out_dir("target/academy-parity/run-8142/learn.neural_cde/regression_irregular_euler/out-r")
warnings <- list()
sample_weights <- function(rows) if (is.null(weights)) NULL else weights[rows + 1L]
rows_of <- function(rows) df[rows + 1L, , drop = FALSE]
RESAMPLE <- "none"
if (RESAMPLE != "none" && TASK == "regression") {
  warnings <- c(warnings, list("Resampling applies to classification only — ignored for this regression target."))
}
resampled <- NULL  # the final model's resampling summary
notes <- list()
# A fit's design matrix, targets and weights: training rows only, resampled when asked
# (cs_ml_resample — the same rows in Python, from the shared random stream).
training_set <- function(X, rows, fold_id, repeat_) {
  yy <- y[rows + 1L]
  ww <- sample_weights(rows)
  if (RESAMPLE == "none" || TASK == "regression") return(list(X = X, y = yy, w = ww))
  r <- cs_ml_resample(X, yy, ww, RESAMPLE, ratio = 1, k = as.integer(5),
                      seed = cs_ml_resample_seed(SEED, fold_id, repeat_))
  if (fold_id == 0) resampled <<- r$info
  r
}
fit_on <- function(s) fit_model(s$X, s$y, s$w)

# %% Model
# 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,
  label_smoothing = 0,
  mixup_alpha = 0,
  history_every_step = FALSE,
  profile = "parity",
  checkpoint_every = NULL
), out_dir = "target/academy-parity/run-8142/learn.neural_cde/regression_irregular_euler/out-r")
.deep_folds <- length(if (0 > 0) utils::head(plan$folds, 0) else plan$folds)
.deep_training_set <- training_set
# Tell the trainer which fit comes next (cross-validation fold i, or the final model), then build the
# training set as _ml_learn does.
training_set <- function(X, rows, fold_id, repeat_) {
  cs_deep_trainer_set_fold(as.integer(fold_id), .deep_folds, if (fold_id > 0) "cv" else "final")
  .deep_training_set(X, rows, fold_id, repeat_)
}
# A neural controlled differential equation on torch for R (float64, one thread): rows that share a sequence id
# form one irregularly sampled path X(u) = [time, features], interpolated linear; a hidden state z
# follows dz = f(z) dX with a fixed-step euler solver, and the label is read from z at the end.
# Initial weights, batches of sequences and the early-stopping split come from the shared random stream, so
# Python's torch trains the same network.
SEQ_ID <- "seq"  # the Sequence id role (rows of one sequence also stay in one fold)
OBS_TIME <- "t"  # observation times; NULL = rows are equally spaced in their order

# One input column for every row, or NULL when the input lacks it (e.g. scoring data without it).
read_sequence_column <- function(name, what) {
  if (is.null(name)) return(NULL)
  values <- tryCatch(nanoparquet::read_parquet("tests/parity/fixtures/gen_irregular_seq.parquet", col_select = name)[[name]], error = function(e) NULL)
  if (is.null(values)) return(NULL)
  missing <- sum(is.na(values))
  if (missing > 0L) cs_error("CS_E_INVALID_VALUES", column = name, requirement = sprintf("present on every row (it gives each row's %s)", what), count = missing)
  values
}

SEQ_VALUES <- read_sequence_column(SEQ_ID, "sequence")
if (is.factor(SEQ_VALUES)) SEQ_VALUES <- as.character(SEQ_VALUES)
.cs_obs <- read_sequence_column(OBS_TIME, "observation time")
TIME_VALUES <- if (is.null(.cs_obs)) NULL else cs_ml_fc_to_days(.cs_obs)$values

# Each design matrix the driver makes knows its rows' sequence ids and times (attributes cs_sets, cs_times; rows
# come from the input's row names).
.cs_seq_design_apply <- cs_ml_design_apply
cs_ml_design_apply <- function(prep, frame) {
  X <- .cs_seq_design_apply(prep, frame)
  rows <- as.integer(rownames(frame))
  if (!is.null(SEQ_VALUES)) attr(X, "cs_sets") <- SEQ_VALUES[rows]
  if (!is.null(TIME_VALUES)) attr(X, "cs_times") <- TIME_VALUES[rows]
  X
}

.cs_sequences <- function(X) {
  s <- cs_cde_seq_of(X, SEQ_VALUES, TIME_VALUES)
  if (is.null(s$seq)) {
    cs_error("CS_E_INVALID_VALUES", column = if (is.null(SEQ_ID)) "Sequence id" else SEQ_ID,
             requirement = "in the data (a neural CDE predicts whole sequences)", count = nrow(X))
  }
  s
}

fit_model <- function(X, y, w) {
  s <- cs_cde_seq_of(X)
  if (is.null(s$seq)) cs_error("CS_E_INVALID_OPTION", option = "Resampling", allowed = "none for sequence models (rows belong to sequences)", value = "on")
  if (TASK == "regression") {
    # Standardize the target (training mean and population SD); predictions are mapped back.
    mu <- mean(y); sd <- sqrt(mean((y - mu)^2)); if (!(sd > 0)) sd <- 1
    target <- (as.numeric(y) - mu) / sd; o <- 1L
  } else if (TASK == "binary") {
    mu <- 0; sd <- 1
    target <- as.numeric(y); o <- 1L
  } else {
    mu <- 0; sd <- 1
    target <- cs_deep_one_hot(y, length(CLASSES)); o <- length(CLASSES)
  }
  fit <- cs_deep_fit_neural_cde(
    unname(as.matrix(X)), s$seq, s$times, target, w, TASK, o,
    target_name = TARGET,
    interpolation = PARAMS$interpolation,
    solver = PARAMS$solver,
    steps = as.integer(PARAMS$steps),
    hidden = as.integer(PARAMS$hidden_size),
    width = as.integer(PARAMS$width),
    vf_layers = as.integer(PARAMS$vf_layers),
    epochs = as.integer(PARAMS$epochs),
    lr = PARAMS$learning_rate,
    batch_size = if (is.null(PARAMS$batch_size)) NULL else as.integer(PARAMS$batch_size),
    weight_decay = PARAMS$weight_decay,
    early_stopping = as.integer(PARAMS$early_stopping) > 0,
    validation_fraction = PARAMS$validation_fraction,
    patience = max(1L, as.integer(PARAMS$early_stopping)),
    seed = SEED
  )
  fit$mu <- mu
  fit$sd <- sd
  fit
}

predict_model <- function(model, X) {
  s <- .cs_sequences(X)
  p <- cs_cde_predict(model, unname(as.matrix(X)), s$seq, s$times, TASK)
  if (TASK == "regression") model$mu + model$sd * p else p
}

feature_importance <- function(model, names) NULL

save_model <- function(model, directory) {
  path <- file.path(directory, "model.rds")
  saveRDS(model, path)  # plain numeric weights, the solver settings, the time unit and the target scaling
  hist <- file.path(directory, "history.parquet")
  nanoparquet::write_parquet(cs_deep_history_frame(model$history), hist)
  list(list(key = "model", path = path, format = "rds"), list(key = "history", path = hist, format = "parquet"))
}

load_model <- function(directory) readRDS(file.path(directory, "model.rds"))

# %% Cross-validation
folds <- if (0 > 0) utils::head(plan$folds, 0) else plan$folds
progress <- cs_progress("Cross-validating", total = length(folds))
for (i in seq_along(folds)) {
  fold <- folds[[i]]
  prep <- cs_ml_design_fit(design, rows_of(fold$train))
  model <- fit_on(training_set(cs_ml_design_apply(prep, rows_of(fold$train)), fold$train, fold$id, fold$repeat_))
  cs_ml_add(run, fold$id, fold$repeat_, "valid", fold$valid, y, y_index,
            predict_model(model, cs_ml_design_apply(prep, rows_of(fold$valid))))
  cs_progress_update(progress, i, sprintf("Fold %d of %d", i, length(folds)))
}
cs_ml_lap(run, "cv_seconds")

# %% Final model
artifacts <- list()
importance <- NULL
prep <- cs_ml_design_fit(design, rows_of(plan$train))
names_ <- cs_ml_design_names(prep)
if (TRUE) {
  model <- fit_on(training_set(cs_ml_design_apply(prep, rows_of(plan$train)), plan$train, 0L, 0L))
  if (!is.null(resampled)) {
    warnings <- c(warnings, as.list(resampled$notes))
    notes <- c(notes, list(cs_ml_resample_describe(resampled)))
  }
  if (length(plan$test)) {
    cs_ml_add(run, 0L, 0L, "test", plan$test, y, y_index,
              predict_model(model, cs_ml_design_apply(prep, rows_of(plan$test))))
  }
  importance <- feature_importance(model, names_)
  artifacts[[length(artifacts) + 1L]] <- list(
    key = "design", path = cs_ml_save_json(cs_ml_design_json(prep), file.path(out, "design.json")), format = "json"
  )
  artifacts <- c(artifacts, save_model(model, out))
  cs_ml_lap(run, "final_seconds")
}
artifacts[[length(artifacts) + 1L]] <- list(key = "predictions", path = cs_ml_write(run, out), format = "parquet")
cs_progress_done(progress)

# %% Result
cs_publish(cs_deep_extend_neural_cde(cs_ml_result(
  run,
  title = "Neural controlled differential equation (irregular sequences)",
  engine = cs_engine_info("torch", "codesplashr", "nanoparquet"),
  n_features = length(names_),
  n_train = length(plan$train),
  n_test = length(plan$test),
  params = PARAMS,
  features = names_,
  importance = importance,
  artifacts = artifacts,
  warnings = warnings,
  notes = notes
), model, names_))
Python

Neural controlled differential equation (irregular sequences): cross-validated RMSE 0.235 ± 0.060 over 3 folds; RMSE on the locked test set 0.142 (n = 92).

CV RMSE
0.2354
SD across folds
0.0604
Test RMSE
0.1422

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

Cross-validation

FoldRepeatnRMSEMAER²MAPE
111220.22790.12630.75830.0851
211220.17910.15480.79590.1335
311220.29920.21890.49820.3649

Training curves

NetworkEpochTraining lossValidation loss
Neural CDE14.2880.7959
Neural CDE20.88071.014
Neural CDE30.70191.067
Neural CDE40.62960.9548
Neural CDE50.53940.8177
Neural CDE60.42260.6572
Neural CDE70.34270.5430
Neural CDE80.28430.4610
Neural CDE90.23400.4003
Neural CDE100.19380.3525
Neural CDE110.16110.3127
Neural CDE120.12760.2669
Neural CDE130.10260.2300
Neural CDE140.08930.2040
Neural CDE150.07740.1946
Neural CDE160.06880.1848
Neural CDE170.06490.1805
Neural CDE180.06000.1906
Neural CDE190.05370.2013
Neural CDE200.04840.2080
Neural CDE210.04380.2081
Neural CDE220.03990.2106
Neural CDE230.03740.2109
Neural CDE240.03620.2101
Neural CDE250.03370.2064
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Neural controlled differential equation (irregular sequences)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method learn.neural_cde 1.0.0 · spec 15b97981456297b5
# Dataset: gen_irregular_seq (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os

import numpy as np
import pandas as pd

import codesplash as cs
from codesplash import ml as csml
from codesplash.deep import core as deep
from codesplash.deep import neural_cde as cde  # twin of codesplashr::cs_deep_fit_neural_cde (shared weights, Adam written out)
from codesplash.ml import forecast as _fc  # times as days (the R twin's cs_ml_fc_to_days)

# %% Data and split plan
TARGET = "omega"
FEATURES = ["x1", "x2"]
TASK = "regression"
CLASSES = []
POSITIVE = None
METRIC = "rmse"
SEED = 42
PARAMS = {
    "interpolation": "linear",
    "solver": "euler",
    "steps": 24,
    "hidden_size": 6,
    "width": 12,
    "vf_layers": 1,
    "epochs": 40,
    "learning_rate": 0.01,
    "batch_size": 12,
    "weight_decay": 0,
    "early_stopping": 8,
    "validation_fraction": 0.2,
    "optimizer": "default",
    "lr_schedule": "none",
    "warmup_epochs": 0,
    "grad_clip": 0,
    "ema_decay": 0,
    "swa_start": 0,
    "label_smoothing": 0,
    "mixup_alpha": 0,
    "history_every_step": False,
    "profile": "parity",
    "checkpoint_every": None,
}

df = pd.read_parquet("tests/parity/fixtures/gen_irregular_seq.parquet", columns=list(dict.fromkeys([TARGET] + FEATURES)))
plan = csml.read_plan("target/academy-parity/run-8142/learn.neural_cde/regression_irregular_euler/folds.parquet")  # host-written folds: identical in Python and R
design = csml.Design.for_frame(
    df,
    FEATURES,
    kinds={
        "x1": "numeric",
        "x2": "numeric",
    },
    levels={
    },
    impute="median",
    scale="standard",
    indicators=False,
)
y, y_index = csml.encode_target(df[TARGET], TASK, CLASSES, POSITIVE)
weights = csml.class_weights(y_index, TASK, "none", plan.train)
run = csml.LearnerRun(TASK, CLASSES, POSITIVE, METRIC)
out = csml.out_dir("target/academy-parity/run-8142/learn.neural_cde/regression_irregular_euler/out-python")
warnings = []


def sample_weights(rows):
    return None if weights is None else weights[rows]


RESAMPLE = "none"
if RESAMPLE != "none" and TASK == "regression":
    warnings.append("Resampling applies to classification only — ignored for this regression target.")
resampled = None  # the final model's resampling summary
notes = []


def training_set(X, rows, fold_id, repeat):
    """A fit's design matrix, targets and weights: training rows only, resampled when asked
    (codesplash.ml.resample — the same rows in R, from the shared random stream)."""
    yy, ww = y[rows], sample_weights(rows)
    if RESAMPLE == "none" or TASK == "regression":
        return X, yy, ww
    from codesplash.ml import resample as csres

    X2, y2, w2, info = csres.resample(
        X, yy, ww, RESAMPLE, ratio=1, k=5, seed=csres.resample_seed(SEED, fold_id, repeat)
    )
    if fold_id == 0:
        global resampled
        resampled = info
    return X2, y2, w2


# %% Model
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,
        "label_smoothing": 0,
        "mixup_alpha": 0,
        "history_every_step": False,
        "profile": "parity",
        "checkpoint_every": None,
    },
    out_dir="target/academy-parity/run-8142/learn.neural_cde/regression_irregular_euler/out-python",
)
_DEEP_FOLDS = len(plan.folds[: 0] if 0 else plan.folds)
_deep_training_set = training_set


def training_set(X, rows, fold_id, repeat):
    """Tell the trainer which fit comes next (cross-validation fold i, or the final model), then build
    the training set as _ml_learn does."""
    deep_trainer.set_fold(int(fold_id), _DEEP_FOLDS, "cv" if fold_id else "final")
    return _deep_training_set(X, rows, fold_id, repeat)


# A neural controlled differential equation on PyTorch (float64, one thread): rows that share a sequence id form
# one irregularly sampled path X(u) = [time, features], interpolated linear; a hidden state z
# follows dz = f(z) dX with a fixed-step euler solver, and the label is read from z at the end.
# Initial weights, batches of sequences and the early-stopping split come from the shared random stream, so R's
# torch trains the same network.
SEQ_ID = "seq"  # the Sequence id role (rows of one sequence also stay in one fold)
OBS_TIME = "t"  # observation times; None = rows are equally spaced in their order


def read_sequence_column(name, what):
    """One input column for every row, or None when the input lacks it (e.g. scoring data without it)."""
    if name is None:
        return None
    try:
        values = pd.read_parquet("tests/parity/fixtures/gen_irregular_seq.parquet", columns=[name])[name]
    except Exception:  # noqa: BLE001 — the column is not in this input
        return None
    missing = int(values.isna().sum())
    if missing:
        cs.cs_error("CS_E_INVALID_VALUES", column=name, requirement=f"present on every row (it gives each row's {what})", count=missing)
    return values


_seq = read_sequence_column(SEQ_ID, "sequence")
SEQ_VALUES = None if _seq is None else _seq.to_numpy(dtype=object)
_obs = read_sequence_column(OBS_TIME, "observation time")
TIME_VALUES = None if _obs is None else _fc.to_days(_obs.to_numpy())[0]


class SeqDesign:
    """The driver's design; each design matrix it makes knows its rows' sequence ids and times."""

    def __init__(self, inner):
        self._inner = inner

    def fit(self, frame):
        return SeqPrep(self._inner.fit(frame))

    def __getattr__(self, name):
        return getattr(self._inner, name)


class SeqPrep:
    def __init__(self, inner):
        self._inner = inner

    def transform(self, frame):
        rows = frame.index.to_numpy()
        return cde.with_seq(self._inner.transform(frame), SEQ_VALUES[rows], None if TIME_VALUES is None else TIME_VALUES[rows])

    def __getattr__(self, name):
        return getattr(self._inner, name)


design = SeqDesign(design)


def _sequences(X):
    seq, times = cde.seq_of(X, SEQ_VALUES, TIME_VALUES)
    if seq is None:
        cs.cs_error("CS_E_INVALID_VALUES", column=SEQ_ID or "Sequence id", requirement="in the data (a neural CDE predicts whole sequences)", count=int(np.asarray(X).shape[0]))
    return seq, times


def fit_model(X, y, w):
    seq, times = cde.seq_of(X)
    if seq is None:
        cs.cs_error("CS_E_INVALID_OPTION", option="Resampling", allowed="none for sequence models (rows belong to sequences)", value="on")
    if TASK == "regression":
        # Standardize the target (training mean and population SD); predictions are mapped back.
        mu, sd = float(np.mean(y)), float(np.std(y)) or 1.0
        target, o = (np.asarray(y, dtype=np.float64) - mu) / sd, 1
    elif TASK == "binary":
        mu, sd = 0.0, 1.0
        target, o = np.asarray(y, dtype=np.float64), 1
    else:
        mu, sd = 0.0, 1.0
        target, o = deep.one_hot(y, len(CLASSES)), len(CLASSES)
    fit = cde.fit_neural_cde(
        np.asarray(X), seq, times, target, w, TASK, o,
        target_name=TARGET,
        interpolation=PARAMS["interpolation"],
        solver=PARAMS["solver"],
        steps=int(PARAMS["steps"]),
        hidden=int(PARAMS["hidden_size"]),
        width=int(PARAMS["width"]),
        vf_layers=int(PARAMS["vf_layers"]),
        epochs=int(PARAMS["epochs"]),
        lr=PARAMS["learning_rate"],
        batch_size=None if PARAMS["batch_size"] is None else int(PARAMS["batch_size"]),
        weight_decay=PARAMS["weight_decay"],
        early_stopping=int(PARAMS["early_stopping"]) > 0,
        validation_fraction=PARAMS["validation_fraction"],
        patience=max(1, int(PARAMS["early_stopping"])),
        seed=SEED,
    )
    fit.update({"mu": mu, "sd": sd})
    return fit


def predict_model(model, X):
    seq, times = _sequences(X)
    p = cde.cde_predict(model, np.asarray(X), seq, times, TASK)
    if TASK == "regression":
        return model["mu"] + model["sd"] * p
    return p


def feature_importance(model, names):
    return None


def save_model(model, directory):
    import joblib

    path = os.path.join(directory, "model.joblib")
    joblib.dump(model, path)  # plain numpy weights, the solver settings, the time unit and the target scaling
    hist = os.path.join(directory, "history.parquet")
    deep.history_frame(model["history"]).to_parquet(hist, index=False)
    return [{"key": "model", "path": path, "format": "joblib"}, {"key": "history", "path": hist, "format": "parquet"}]


def load_model(directory):
    import joblib

    return joblib.load(os.path.join(directory, "model.joblib"))


# %% Cross-validation
folds = plan.folds[: 0] if 0 else plan.folds
progress = cs.progress("Cross-validating", total=len(folds))
for i, fold in enumerate(folds):
    prep = design.fit(df.iloc[fold.train])
    model = fit_model(*training_set(prep.transform(df.iloc[fold.train]), fold.train, fold.id, fold.repeat))
    run.add(fold.id, fold.repeat, "valid", fold.valid, y, y_index, predict_model(model, prep.transform(df.iloc[fold.valid])))
    progress.update(i + 1, f"Fold {i + 1} of {len(folds)}")
run.lap("cv_seconds")

# %% Final model
artifacts = []
importance = None
prep = design.fit(df.iloc[plan.train])
names = prep.names
if True:
    model = fit_model(*training_set(prep.transform(df.iloc[plan.train]), plan.train, 0, 0))
    if resampled is not None:
        from codesplash.ml import resample as csres

        warnings.extend(resampled["notes"])
        notes.append(csres.describe(resampled))
    if len(plan.test):
        run.add(0, 0, "test", plan.test, y, y_index, predict_model(model, prep.transform(df.iloc[plan.test])))
    importance = feature_importance(model, names)
    artifacts.append({"key": "design", "path": csml.save_json(prep.to_json(), os.path.join(out, "design.json")), "format": "json"})
    artifacts.extend(save_model(model, out))
    run.lap("final_seconds")
artifacts.append({"key": "predictions", "path": run.write(out), "format": "parquet"})
progress.done()

# %% Result
cs.publish(
    cde.extend_neural_cde(run.result(
        title="Neural controlled differential equation (irregular sequences)",
        engine=cs.engine_info("torch", "codesplash", "numpy", "pandas"),
        n_features=len(names),
        n_train=len(plan.train),
        n_test=len(plan.test),
        params=PARAMS,
        features=names,
        importance=importance,
        artifacts=artifacts,
        warnings=warnings,
        notes=notes,
    ), model, names)
)

The 39 simulated training sequences are each observed at uneven times, about 9 observations apiece. The model predicts the frequency ω\omega of the noisy sine wave in each one, with Euler steps along a straight-line path, and reaches a cross-validated R² of 0.68.

Rows of one sequence stay in one fold, so the score counts sequences, not rows.

05

Temporal graph networks: memory per node

Read

A temporal graph networkTemporal graph networkA model for timed interactions that keeps a memory vector per node and updates it, in time order, from each new event. models timed interactions, such as user–item clicks or payments between accounts. Each node keeps a memory vector sis_i. When an event links ii and jj at time tt, a message is built from both memories, the event's features and the time since the last update, and each memory is updated, often by a gated recurrent unit:

mij(t)=ϕ(si(t−),sj(t−),eij,Δt),si(t)=Update(si(t−),mi).m_{ij}(t) = \phi\big(s_i(t^-), s_j(t^-), e_{ij}, \Delta t\big), \qquad s_i(t) = \text{Update}\big(s_i(t^-), m_i\big).

An embedding module combines memory with recent neighbors to predict the next link or a node's label.

That embedding step is message passing over the recent neighbors; the explorable shows what each round does to node features.

DExplorable · Message passing and oversmoothing

Why does a graph network get better with a few layers and worse with many?

Each layer averages over neighbors. At which depth (0–32) will the communities be best separated?

16
How sure?

Graph

2

Normalization

1.2
  • Community separation
  • Mean cosine distance
  • Energy, share of input (dashed)
Aggregating the neighbor multisets {a, b} and {a, a, b, b} (a = 1, b = 2)
Aggregator{a, b}{a, a, b, b}Tells them apart
sum3.006.00yes
mean1.501.50no
max2.002.00no

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

Reference · SEQ005 · Needs a data type CodeSplash doesn't load yetTemporal Graph Networks (TGN)A framework for graph learning from timed interactions using node memories, event messages, memory updates, and temporal embeddings.
06

A gated memory update

Explore

A gate decides how much of the old memory to keep. The reference blends an old memory (0.2,−0.1)(0.2, -0.1) and a candidate (0.6,0.3)(0.6, 0.3) with gates σ(0.4)\sigma(0.4) and σ(−0.2)\sigma(-0.2); the new memory is (0.439, 0.080).

Python
import numpy as np
old = np.array([.2, -.1]); candidate = np.array([.6, .3])
gate = 1 / (1 + np.exp(-np.array([.4, -.2])))
print((1 - gate) * old + gate * candidate)
R
old <- c(.2, -.1); candidate <- c(.6, .3)
gate <- 1 / (1 + exp(-c(.4, -.2)))
print((1 - gate) * old + gate * candidate)
07

The memory leak to avoid

Predict

Predict first

To predict whether an event between ii and jj happens at time tt, an implementation first updates both memories with that very event, then scores it. Fine or a leak?

Fine: the memory is part of the modelA leak: the memory already saw the event being predicted
Reveal

A leak. Memories must be read as they were right before tt, and updated only after the prediction. The memory is state, not a learned weight, so also reset or carry it consistently across training and test periods. Unobserved pairs aren't necessarily true negatives either.

08

DenStream: fading summaries of a stream

Read

An endless stream can't be stored. Stream clusteringStream clusteringClustering rows one at a time in arrival order with small summaries that fade with age, so clusters can appear, drift and end. keeps a few micro-clustersMicro-clusterA small summary of nearby rows (weight, sum and sum of squares) that a stream clusterer updates instead of keeping the rows.: decayed counts and sums that give each one a center and radius. DenStream fades every observation's weight with age, 2−λ(t−ti)2^{-\lambda (t - t_i)}. Dense micro-clusters become potential clusters, sparse ones stay outliers, and stale ones are pruned.

In the reference's example, points that arrived at times 0, 2 and 4 are weighted at time 5 with λ=0.5\lambda = 0.5: 0.177, 0.354 and 0.707, an effective count of 1.237 instead of 3.

Reference · SEQ004 · Runs in CodeSplashDenStreamA density-based stream-clustering algorithm using fading micro-clusters to summarize evolving data and separate potential clusters from outliers.
09

DenStream on a drifting stream

Explore
Stream clustering (DenStream, DBSTREAM, CluStream)Recorded · Python and R agreeRecorded 2026-11-25 · 34 values compared · largest relative difference 1.1e-15
R

DenStream over 600 rows in 19 windows: 2 clusters at the end, up to 3 at once, 3 born and 1 ended; prequential coverage 94%.

Clusters
3
Mean silhouette
0.6611

Plots

ClustersWhich rows group together, and how well separated are the groups?
View data
Clusterxy
2−1.127−0.4099
11.2570.6207
2−0.9507−0.9729
2−0.7881−0.8292
11.1760.6690
10.80720.7739
2−0.8462−0.6724
11.1000.8137
11.3460.5074
10.96050.5483
2−1.188−0.8311
2−0.9297−0.4858
2−1.102−0.1629
2−0.9823−0.9340
2−0.8308−0.5300
11.2110.6173
2−0.8146−0.6744
11.2770.6906
2−1.137−0.5318
10.85020.8321
2−0.8335−0.6556
2−0.7553−0.7194
11.2130.4362
11.0320.2751
2−0.9747−0.6412
2−0.5998−0.8745
11.2720.5336
11.1770.6567
2−0.9367−0.7815
11.0220.8654
2−0.7915−0.6880
11.0490.3958
11.0640.7189
10.95450.8472
2−0.9969−0.3585
11.0850.8443
2−1.015−0.5637
2−1.203−0.4886
11.2520.5667
2−0.7127−0.5275
2−0.5086−1.292
2−0.6538−0.6344
11.2250.4769
2−0.9953−0.4040
11.2840.3511
2−0.5294−0.6070
11.0800.7250
2−0.8389−0.5509
10.91550.6039
2−0.7965−0.7222
11.0800.7361
11.0690.9785
10.88460.8225
2−1.167−0.7427
2−0.9788−0.6138
2−0.6412−0.5951
2−1.026−0.4463
2−0.8724−1.182
11.1250.7294
2−0.9260−0.4401

First 60 of 600 rows.

Clusters over timeWhich clusters are born, grow, drift and end as the data arrives?
View data
ClusterCenter: xtimeWeight
2−0.89046025.947
11.1006020.766
2−0.91569030.168
11.0789027.639
2−0.923612032.582
11.10912033.795
2−0.923515032.831
11.10515038.713
2−0.916918039.775
11.11518036.315
2−0.904021037.240
11.08721042.063
2−0.894124040.764
11.07924040.813
2−0.886127040.366
11.06627042.817
2−0.859030040.527
11.07930043.792
2−0.850833036.872
11.09733036.918
3−0.777633010.389
2−0.885436033.698
11.11836032.963
3−0.857936017.502
2−0.907139031.280
11.12939029.252
3−0.875539022.665
2−0.894042031.739
11.11942027.598
3−0.887042024.991
2−0.897545034.409
11.10545027.307
3−0.881745023.413
2−0.897548024.331
3−0.825648028.407
11.09748024.769
2−0.897551017.205
3−0.849651032.907
11.10951030.194
3−0.850054039.655
11.12154029.542
3−0.828257040.089
11.09257032.621
3−0.840360039.962
11.09460036.952
Prequential evaluation per windowHow does the series move over time, and where is an estimated break?
View data
MeasuretimeValue
Coverage900.9667
Coverage1201
Coverage1500.9667
Coverage1801
Coverage2101
Coverage2401
Coverage2701
Coverage3000.9667
Coverage3300.4667
Coverage3600.9333
Coverage3900.9333
Coverage4200.9667
Coverage4501
Coverage4800.9667
Coverage5101
Coverage5400.9333
Coverage5700.9333
Coverage6000.9000
Purity901
Purity1201
Purity1501
Purity1801
Purity2101
Purity2401
Purity2700.9667
Purity3001
Purity3301
Purity3600.9643
Purity3901
Purity4201
Purity4500.9667
Purity4801
Purity5100.9667
Purity5400.9286
Purity5700.9643
Purity6001
Adjusted Rand index901
Adjusted Rand index1201
Adjusted Rand index1501
Adjusted Rand index1801
Adjusted Rand index2101
Adjusted Rand index2401
Adjusted Rand index2700.9308
Adjusted Rand index3000.9308
Adjusted Rand index3300.8233
Adjusted Rand index3600.9039
Adjusted Rand index3900.9236
Adjusted Rand index4201
Adjusted Rand index4500.9320
Adjusted Rand index4801
Adjusted Rand index5100.9354
Adjusted Rand index5400.8552
Adjusted Rand index5700.9287
Adjusted Rand index6000.8196
Silhouette widthsHow well does each row fit its cluster compared with the next-nearest cluster?
View data
ClusterSilhouette width
10.6387
10.6381
10.6371
10.6362
10.6354
10.6347
10.6344
10.6344
10.6339
10.6338
10.6337
10.6332
10.6316
10.6312
10.6309
10.6308
10.6277
10.6260
10.6259
10.6248
10.6244
10.6220
10.6217
10.6210
10.6206
10.6197
10.6176
10.6169
10.6166
10.6164
10.6156
10.6154
10.6153
10.6137
10.6125
10.6122
10.6119
10.6102
10.6089
10.6082
10.6080
10.6076
10.6066
10.6058
10.6053
10.6052
10.6049
10.6048
10.6035
10.6025
10.6018
10.6006
10.6000
10.5999
10.5996
10.5972
10.5959
10.5958
10.5952
10.5950

First 60 of 593 rows.

Clusters

ClusterSizeSharexy
126343.8%1.9890.5768
220033.3%−2.039−0.0270
313021.7%−1.9363.079

Windows: snapshots and prequential evaluation

WindowEnds at (time)Rows so farClustersMicro-clustersOutlier micro-clustersBornEndedCoverage (prequential)Mean squared distancePurityAdjusted Rand index
260602402, 1————
3909024096.7%0.087611
4120120240100.0%0.089711
515015024096.7%0.077711
6180180240100.0%0.090111
7210210240100.0%0.077411
8240240240100.0%0.161411
9270270240100.0%0.15610.96670.9308
1030030024096.7%0.186710.9308
11330330350346.7%0.124110.8233
1236036036193.3%0.15410.96430.9039
1339039035093.3%0.142910.9236
1442042035096.7%0.214111
15450450350100.0%0.23530.96670.9320
1648048035096.7%0.258211
17510510350100.0%0.12280.96670.9354
18540540261293.3%0.09700.92860.8552
1957057025093.3%0.09580.96430.9287
2060060025090.0%0.161010.8196

Micro-clusters at the end of the stream

IdKindWeightCreated (clock)RadiusClusterCenter: xCenter: y
1potential2.426300.3468noise−0.9007−0.3211
2potential2.047300.4157noise1.136−0.0394
3potential3.656300.2983noise−0.8953−0.7614
7potential39.9623040.31903−0.84031.404
10potential36.9523620.403411.094−1.467
The exact R script · R R version 4.5.1 (2025-06-13)
# Stream clustering (DenStream, DBSTREAM, CluStream)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.stream_clusters 1.0.0 · spec ea5f79a148cd185c
# Dataset: seq_stream (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)
# DenStream, DBSTREAM and CluStream are codesplashr's cs_stream_* twins of codesplash.ml.stream_cluster (clean-room).

# %% Data
FEATURES <- c("x", "y")
LABEL <- "source"  # known groups (external validation only)
ROW_ID <- NULL  # row labels for charts
SEED <- 42
KINDS <- list(
  x = "numeric",
  y = "numeric"
)
LEVELS <- list(
)
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/seq_stream.parquet", col_select = unique(c(FEATURES, LABEL, ROW_ID))))
n_input <- nrow(df)
prep <- cs_ml_cluster_prepare(df, FEATURES, KINDS, LEVELS, missing = "drop", scale = "standard")
X <- prep$X; rows <- prep$rows; names_ <- prep$names; frame <- prep$frame
warnings <- list()
if (length(rows) < n_input) {
  warnings <- c(warnings, sprintf("%d of %d rows were left out because a feature was missing.", n_input - length(rows), n_input))
}
if (length(rows) < 3) stop("Clustering needs at least three rows with every feature present.")
truth <- if (!is.null(LABEL)) as.character(frame[[LABEL]]) else NULL
out <- cs_ml_out_dir("target/academy-parity/run-8142/discover.stream_clusters/stream_denstream_defaults/out-r")
values <- list(n_used = length(rows))
centers <- NULL
center_ids <- NULL
D <- NULL
extra <- list()
tables <- list()
charts <- list()
summary <- NULL

# %% Clustering
# Rows replayed in time order through an online clusterer; at the end of each window the offline step forms the
# clusters (a snapshot), which are matched to the previous snapshot's so a cluster keeps its id while it lives.
TIME <- "time"
ALGORITHM <- "denstream"
CLOCK <- "rows"
.tdf <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/seq_stream.parquet", col_select = TIME))
cs_check_finite_columns(.tdf, c(TIME))
t_all <- suppressWarnings(as.numeric(.tdf[[TIME]]))
TIME_UNIT <- 1
t_kept <- t_all[rows + 1L]
has_t <- !is.na(t_kept)
if (!all(has_t)) {
  warnings <- c(warnings, sprintf("%d rows have no %s and are left out.", sum(!has_t), TIME))
  keep <- which(has_t)
  X <- X[keep, , drop = FALSE]; rows <- rows[keep]; frame <- frame[keep, , drop = FALSE]; t_kept <- t_kept[keep]
  if (!is.null(truth)) truth <- truth[keep]
  values$n_used <- length(rows)
}
cs_check_rows(length(rows), 3L, "Stream clustering")
ord <- order(t_kept, method = "radix")  # time order; ties keep the input order
n <- length(ord)
Xs <- X[ord, , drop = FALSE]
ts <- t_kept[ord]
WINDOW <- NULL
WINDOW <- if (!is.null(WINDOW)) as.integer(WINDOW) else max(5L, as.integer(ceiling(n / 20)))
n_windows <- as.integer(ceiling(n / WINDOW))
if (CLOCK == "time") {
  clock <- ts / TIME_UNIT
  span <- clock[n] - clock[1]
  if (!(span > 0)) cs_error("CS_E_CONSTANT", column = TIME)
  unit <- span / n_windows  # clock units per window
} else {
  clock <- as.numeric(seq_len(n))
  unit <- as.numeric(WINDOW)
}
HALF_LIFE <- NULL
HALF_LIFE <- if (!is.null(HALF_LIFE)) as.numeric(HALF_LIFE) else 2 * unit
RADIUS <- NULL
RADIUS <- if (!is.null(RADIUS)) as.numeric(RADIUS) else 0.3 * sqrt(ncol(X))
INIT_ROWS <- NULL
INIT_ROWS <- if (!is.null(INIT_ROWS)) as.integer(INIT_ROWS) else WINDOW
K <- as.integer(3)
GAP <- NULL
HORIZON <- NULL
MICRO <- NULL
opts <- list(
  radius = RADIUS, mu = as.numeric(10), beta = as.numeric(0.2),
  t_gap = if (!is.null(GAP)) as.numeric(GAP) else unit, alpha = as.numeric(0.1),
  min_weight = as.numeric(3), shared_density = TRUE,
  micro_clusters = if (!is.null(MICRO)) as.integer(MICRO) else 10L * K, k = K, boundary = as.numeric(2),
  horizon = if (!is.null(HORIZON)) as.numeric(HORIZON) else 2 * unit, m_last = as.integer(10)
)
res <- cs_stream_run(Xs, clock, ALGORITHM, WINDOW, INIT_ROWS, 1 / HALF_LIFE, opts,
                     truth = if (is.null(truth)) NULL else truth[ord], seed = SEED)
raw <- integer(n)
raw[ord] <- res$labels
names_of <- cs_stream_track_names(raw, res$snapshots)  # track -> displayed cluster (canonical ids first)
parts <- cs_stream_publish_parts(res, names_of, names_, ALGORITHM, ts, FALSE, TIME, !is.null(truth))
values <- c(values, parts$values)
values$window_rows <- WINDOW
values$n_windows <- n_windows
values$half_life <- HALF_LIFE
values$clock <- CLOCK
if (ALGORITHM %in% c("denstream", "dbstream")) values$radius <- RADIUS
tables <- c(tables, parts$tables)
charts <- c(charts, parts$charts)
warnings <- c(warnings, parts$warnings)
summary <- parts$summary

# %% Canonical labels and validation
labels <- cs_ml_canonical(raw)
ids <- sort(unique(labels[labels != -1]))
k <- length(ids)
values$k <- k
values$n_noise <- sum(labels == -1)
if (!is.null(centers)) {
  cid <- if (is.null(center_ids)) seq_len(nrow(centers)) - 1L else center_ids
  raw_of <- vapply(ids, function(c) raw[which(labels == c)[1]], numeric(1))
  centers <- centers[match(raw_of, cid), , drop = FALSE]
  for (i in seq_along(ids)) for (j in seq_along(names_)) {
    values[[sprintf("center[%d,%s]", ids[i], names_[j])]] <- centers[i, j]
  }
}
sz <- cs_ml_cluster_sizes(labels)
for (c in names(sz)) values[[sprintf("size[%s]", c)]] <- sz[[c]]
check <- cs_ml_cluster_validation(X, labels, truth, D = D, cap = 3000, seed = SEED)
widths <- check$.widths
check$.widths <- NULL
values <- c(values, check)
profile_rows <- list()
for (c in ids) {
  member <- labels == c
  row <- list(cluster = c, size = sum(member), share = mean(member))
  for (f in FEATURES) {
    if (identical(KINDS[[f]], "numeric")) {
      m <- mean(suppressWarnings(as.numeric(frame[[f]]))[member], na.rm = TRUE)
      row[[f]] <- m
      values[[sprintf("mean[%d,%s]", c, f)]] <- m
    } else {
      v <- as.character(frame[[f]])[member]
      v <- v[!is.na(v)]
      top <- if (length(v)) sort(table(v), decreasing = TRUE) else NULL
      row[[f]] <- if (length(top)) sprintf("%s (%.0f%%)", names(top)[1], 100 * top[[1]] / sum(member)) else ""
    }
  }
  profile_rows[[length(profile_rows) + 1L]] <- row
}
tables <- c(list(list(
  key = "clusters", title = "Clusters",
  columns = c(list(list(key = "cluster", label = "Cluster", type = "integer"),
                   list(key = "size", label = "Size", type = "integer"),
                   list(key = "share", label = "Share", type = "percent")),
              lapply(FEATURES, function(f) list(key = f, label = f, type = if (identical(KINDS[[f]], "numeric")) "number" else "string"))),
  rows = profile_rows
)), tables)

# %% Labels file and charts
path <- do.call(cs_ml_write_labels, c(list(out, rows, labels), extra))
name_of <- function(c) as.character(c)  # noise stays "-1" (drawn gray, listed last)
pr <- cs_ml_project2(X, centers, names_)
show <- cs_ml_even_sample(length(rows))
xs <- pr$P[show + 1L, 1]; ys <- pr$P[show + 1L, 2]
cl <- name_of(labels[show + 1L])
cent <- rep(FALSE, length(show))
lab <- if (!is.null(ROW_ID)) as.character(frame[[ROW_ID]])[show + 1L] else NULL
if (!is.null(pr$C)) {
  xs <- c(xs, pr$C[, 1]); ys <- c(ys, pr$C[, 2])
  cl <- c(cl, name_of(ids)); cent <- c(cent, rep(TRUE, length(ids)))
  if (!is.null(lab)) lab <- c(lab, sprintf("center %d", ids))
}
level_names <- c(as.character(ids), if (values$n_noise > 0) "-1")
charts <- c(list(cs_chart(
  "clusters", "cluster-scatter", "Clusters",
  list(x = cs_col(pr$labels[1], xs, "numeric"), y = cs_col(pr$labels[2], ys, "numeric"),
       cluster = cs_col("Cluster", cl, "categorical", levels = level_names),
       centroid = if (!is.null(pr$C)) cs_col("Center", cent, "boolean"),
       label = if (!is.null(lab)) cs_col("Row", lab, "categorical")),
  note = if (length(show) == length(rows)) NULL else sprintf("%s of %s rows shown.", format(length(show), big.mark = ","), format(length(rows), big.mark = ","))
)), charts)
if (!is.nan(values$silhouette)) {
  wl <- labels[widths$pick + 1L]
  o <- order(wl, -widths$width)
  charts[[length(charts) + 1L]] <- cs_chart(
    "silhouette", "silhouette-plot", "Silhouette widths",
    list(cluster = cs_col("Cluster", as.character(wl[o]), "categorical", levels = as.character(ids)),
         width = cs_col("Silhouette width", widths$width[o], "numeric")),
    note = if (length(widths$pick) == sum(labels != -1)) NULL else sprintf("%s rows sampled for the silhouette.", format(length(widths$pick), big.mark = ","))
  )
}

# %% Result
if (is.null(summary)) {
  summary <- sprintf("%d cluster%s in %s rows", k, if (k != 1) "s" else "", format(length(rows), big.mark = ","))
  if (values$n_noise > 0) summary <- paste0(summary, sprintf(" (%s noise points)", format(values$n_noise, big.mark = ",")))
  if (!is.nan(values$silhouette)) summary <- paste0(summary, sprintf("; mean silhouette %.2f", values$silhouette))
  summary <- paste0(summary, ".")
}
cs_publish(list(
  title = "Stream clustering (DenStream, DBSTREAM, CluStream)",
  engine = cs_engine_info("codesplashr", "nanoparquet"),
  n = length(rows),
  summary = summary,
  statistics = list(list(key = "k", label = "Clusters", value = k, format = "integer"),
                    list(key = "silhouette", label = "Mean silhouette", value = values$silhouette)),
  tables = tables,
  values = values,
  charts = charts,
  warnings = warnings,
  artifacts = list(list(key = "labels", path = path, format = "parquet")),
  model = list(kind = "clusterer", features = I(names_), params = list(
    algorithm = "denstream",
    clock = "rows",
    window = NULL,
    half_life = NULL,
    radius = NULL,
    mu = 10,
    beta = 0.2,
    init_rows = NULL,
    alpha = 0.1,
    min_weight = 3,
    shared_density = TRUE,
    gap = NULL,
    macro_clusters = 3,
    micro_clusters = NULL,
    boundary = 2,
    horizon = NULL,
    recent = 10,
    scale = "standard",
    missing = "drop"
  ))
))
Python

DenStream over 600 rows in 19 windows: 2 clusters at the end, up to 3 at once, 3 born and 1 ended; prequential coverage 94%.

Clusters
3
Mean silhouette
0.6611

Clusters

ClusterSizeSharexy
126343.8%1.9890.5768
220033.3%−2.039−0.0270
313021.7%−1.9363.079

Windows: snapshots and prequential evaluation

WindowEnds at (time)Rows so farClustersMicro-clustersOutlier micro-clustersBornEndedCoverage (prequential)Mean squared distancePurityAdjusted Rand index
260602402, 1————
3909024096.7%0.087611
4120120240100.0%0.089711
515015024096.7%0.077711
6180180240100.0%0.090111
7210210240100.0%0.077411
8240240240100.0%0.161411
9270270240100.0%0.15610.96670.9308
1030030024096.7%0.186710.9308
11330330350346.7%0.124110.8233
1236036036193.3%0.15410.96430.9039
1339039035093.3%0.142910.9236
1442042035096.7%0.214111
15450450350100.0%0.23530.96670.9320
1648048035096.7%0.258211
17510510350100.0%0.12280.96670.9354
18540540261293.3%0.09700.92860.8552
1957057025093.3%0.09580.96430.9287
2060060025090.0%0.161010.8196

Micro-clusters at the end of the stream

IdKindWeightCreated (clock)RadiusClusterCenter: xCenter: y
1potential2.426300.3468noise−0.9007−0.3211
2potential2.047300.4157noise1.136−0.0394
3potential3.656300.2983noise−0.8953−0.7614
7potential39.9623040.31903−0.84031.404
10potential36.9523620.403411.094−1.467
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Stream clustering (DenStream, DBSTREAM, CluStream)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.stream_clusters 1.0.0 · spec ea5f79a148cd185c
# Dataset: seq_stream (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd

import codesplash as cs
from codesplash import ml as csml
from codesplash.ml import cluster as csc
from codesplash.stats.rng import Rng
import math

from codesplash.ml import stream_cluster as csstream  # clean-room twin of codesplashr cs_stream_* (DenStream, DBSTREAM, CluStream)

# %% Data
FEATURES = ["x", "y"]
LABEL = "source"  # known groups (external validation only)
ROW_ID = None  # row labels for charts
SEED = 42
KINDS = {
    "x": "numeric",
    "y": "numeric",
}
LEVELS = {
}
df = pd.read_parquet("tests/parity/fixtures/seq_stream.parquet", columns=list(dict.fromkeys(FEATURES + [c for c in (LABEL, ROW_ID) if c])))
n_input = len(df)
X, rows, names, frame = csc.prepare(df, FEATURES, KINDS, LEVELS, missing="drop", scale="standard")
warnings = []
if len(rows) < n_input:
    warnings.append(f"{n_input - len(rows)} of {n_input} rows were left out because a feature was missing.")
if len(rows) < 3:
    raise ValueError("Clustering needs at least three rows with every feature present.")
truth = frame[LABEL].astype("object").to_numpy() if LABEL else None
out = csml.out_dir("target/academy-parity/run-8142/discover.stream_clusters/stream_denstream_defaults/out-python")
values = {"n_used": len(rows)}
centers = None
center_ids = None
D = None
extra = {}
tables = []
charts = []
summary = None

# %% Clustering
# Rows replayed in time order through an online clusterer; at the end of each window the offline step forms the
# clusters (a snapshot), which are matched to the previous snapshot's so a cluster keeps its id while it lives.
TIME = "time"
ALGORITHM = "denstream"
CLOCK = "rows"
tcol = pd.read_parquet("tests/parity/fixtures/seq_stream.parquet", columns=[TIME])[TIME]
cs.check_finite_columns(tcol.to_frame(), [TIME])
t_all = pd.to_numeric(tcol, errors="coerce").to_numpy(dtype=float)
TIME_UNIT = 1.0
t_kept = t_all[rows]
has_t = ~np.isnan(t_kept)
if not bool(np.all(has_t)):
    warnings.append(f"{int(np.sum(~has_t))} rows have no {TIME} and are left out.")
    keep = np.flatnonzero(has_t)
    X, rows, frame, t_kept = X[keep], rows[keep], frame.iloc[keep], t_kept[keep]
    truth = None if truth is None else truth[keep]
    values["n_used"] = len(rows)
cs.check_rows(len(rows), 3, "Stream clustering")
order = np.argsort(t_kept, kind="stable")  # time order; ties keep the input order
n = len(order)
Xs = X[order]
ts = t_kept[order]
WINDOW = None
WINDOW = int(WINDOW) if WINDOW is not None else max(5, math.ceil(n / 20))
n_windows = math.ceil(n / WINDOW)
if CLOCK == "time":
    clock = ts / TIME_UNIT
    span = float(clock[-1] - clock[0])
    if span <= 0:
        cs.cs_error("CS_E_CONSTANT", column=TIME)
    unit = span / n_windows  # clock units per window
else:
    clock = np.arange(1, n + 1, dtype=np.float64)
    unit = float(WINDOW)
HALF_LIFE = None
HALF_LIFE = float(HALF_LIFE) if HALF_LIFE is not None else 2.0 * unit
RADIUS = None
RADIUS = float(RADIUS) if RADIUS is not None else 0.3 * math.sqrt(X.shape[1])
INIT_ROWS = None
INIT_ROWS = int(INIT_ROWS) if INIT_ROWS is not None else WINDOW
K = int(3)
GAP = None
HORIZON = None
MICRO = None
opts = {
    "radius": RADIUS, "mu": float(10), "beta": float(0.2),
    "t_gap": float(GAP) if GAP is not None else unit, "alpha": float(0.1),
    "min_weight": float(3), "shared_density": True,
    "micro_clusters": int(MICRO) if MICRO is not None else 10 * K, "k": K, "boundary": float(2),
    "horizon": float(HORIZON) if HORIZON is not None else 2.0 * unit, "m_last": int(10),
}
res = csstream.run(Xs, clock, ALGORITHM, WINDOW, INIT_ROWS, 1.0 / HALF_LIFE, opts,
                   truth=None if truth is None else truth[order], seed=SEED)
raw = np.empty(n, dtype=np.int64)
raw[order] = res["labels"]
names_of = csstream.track_names(raw, res["snapshots"])  # track → displayed cluster (canonical ids first)
summary_extra = csstream.publish_parts(res, names_of, names, ALGORITHM, ts, False, TIME, truth is not None)
values.update(summary_extra["values"])
values.update({"window_rows": WINDOW, "n_windows": n_windows, "half_life": HALF_LIFE, "clock": CLOCK})
if ALGORITHM in ("denstream", "dbstream"):
    values["radius"] = RADIUS
tables.extend(summary_extra["tables"])
charts.extend(summary_extra["charts"])
warnings.extend(summary_extra["warnings"])
summary = summary_extra["summary"]

# %% Canonical labels and validation
labels = csc.canonical(raw)
ids = [int(c) for c in sorted(set(labels.tolist())) if c != -1]
k = len(ids)
values["k"] = k
values["n_noise"] = int(np.sum(labels == -1))
if centers is not None:
    # reorder centers to canonical ids: the raw id of each canonical cluster
    raw_of = {c: raw[np.flatnonzero(labels == c)[0]] for c in ids}
    pos = {int(r): i for i, r in enumerate(center_ids if center_ids is not None else range(len(centers)))}
    centers = np.array([centers[pos[int(raw_of[c])]] for c in ids])
    for c, row in zip(ids, centers):
        for name, v in zip(names, row):
            values[f"center[{c},{name}]"] = float(v)
for c, m in csc.sizes(labels).items():
    values[f"size[{c}]"] = m
check = csc.validation(X, labels, truth, D=D, cap=3000, seed=SEED)
widths, picked = check.pop("_widths")
values.update(check)
# per-cluster means of numeric features in their own units (interpretation)
profile_rows = []
for c in ids:
    member = labels == c
    row = {"cluster": c, "size": int(member.sum()), "share": float(member.mean())}
    for f in FEATURES:
        if KINDS[f] == "numeric":
            m = float(np.nanmean(pd.to_numeric(frame[f], errors="coerce").to_numpy(dtype=np.float64)[member]))
            row[f] = m
            values[f"mean[{c},{f}]"] = m
        else:
            top = pd.Series(frame[f].astype("object").to_numpy()[member]).dropna().astype(str).value_counts()
            row[f] = f"{top.index[0]} ({top.iloc[0] / member.sum():.0%})" if len(top) else ""
    profile_rows.append(row)
tables.insert(0, {
    "key": "clusters",
    "title": "Clusters",
    "columns": [
        {"key": "cluster", "label": "Cluster", "type": "integer"},
        {"key": "size", "label": "Size", "type": "integer"},
        {"key": "share", "label": "Share", "type": "percent"},
    ]
    + [{"key": f, "label": f, "type": "number" if KINDS[f] == "numeric" else "string"} for f in FEATURES],
    "rows": profile_rows,
})

# %% Labels file and charts
path = csc.write_labels(out, rows, labels, **extra)
name_of = lambda c: str(c)  # noqa: E731  — noise stays "-1" (drawn gray, listed last)
P, C, axes = csc.project2(X, centers, names)
show = csc.even_sample(len(rows))
point_labels = [str(v) for v in frame[ROW_ID].astype("object").to_numpy()[show]] if ROW_ID else None
xs, ys = list(P[show, 0]), list(P[show, 1])
cl = [name_of(c) for c in labels[show]]
cent = [False] * len(show)
lab = point_labels
if C is not None:
    xs += list(C[:, 0])
    ys += list(C[:, 1])
    cl += [name_of(c) for c in ids]
    cent += [True] * len(ids)
    lab = None if lab is None else lab + [f"center {c}" for c in ids]
level_names = [str(c) for c in ids] + (["-1"] if values["n_noise"] else [])
charts.insert(0, cs.chart(
    "clusters", "cluster-scatter", "Clusters",
    {
        "x": cs.col(axes[0], xs, "numeric"),
        "y": cs.col(axes[1], ys, "numeric"),
        "cluster": cs.col("Cluster", cl, "categorical", levels=level_names),
        "centroid": cs.col("Center", cent, "boolean") if C is not None else None,
        "label": cs.col("Row", lab, "categorical") if lab is not None else None,
    },
    note=None if len(show) == len(rows) else f"{len(show):,} of {len(rows):,} rows shown.",
))
if not np.isnan(values["silhouette"]):
    wl = labels[picked]
    order = np.lexsort((-widths, wl))
    charts.append(cs.chart(
        "silhouette", "silhouette-plot", "Silhouette widths",
        {"cluster": cs.col("Cluster", [str(c) for c in wl[order]], "categorical", levels=[str(c) for c in ids]),
         "width": cs.col("Silhouette width", list(widths[order]), "numeric")},
        note=None if len(picked) == int(np.sum(labels != -1)) else f"{len(picked):,} rows sampled for the silhouette.",
    ))

# %% Result
if summary is None:
    summary = f"{k} cluster{'s' if k != 1 else ''} in {len(rows):,} rows"
    if values["n_noise"]:
        summary += f" ({values['n_noise']:,} noise points)"
    if not np.isnan(values["silhouette"]):
        summary += f"; mean silhouette {values['silhouette']:.2f}"
    summary += "."
cs.publish({
    "title": "Stream clustering (DenStream, DBSTREAM, CluStream)",
    "engine": cs.engine_info("numpy", "codesplash", "numpy", "pandas"),
    "n": len(rows),
    "summary": summary,
    "statistics": [
        {"key": "k", "label": "Clusters", "value": k, "format": "integer"},
        {"key": "silhouette", "label": "Mean silhouette", "value": values["silhouette"]},
    ],
    "tables": tables,
    "values": values,
    "charts": charts,
    "warnings": warnings,
    "artifacts": [{"key": "labels", "path": path, "format": "parquet"}],
    "model": {"kind": "clusterer", "features": names, "params": {
        "algorithm": "denstream",
        "clock": "rows",
        "window": None,
        "half_life": None,
        "radius": None,
        "mu": 10,
        "beta": 0.2,
        "init_rows": None,
        "alpha": 0.1,
        "min_weight": 3,
        "shared_density": True,
        "gap": None,
        "macro_clusters": 3,
        "micro_clusters": None,
        "boundary": 2,
        "horizon": None,
        "recent": 10,
        "scale": "standard",
        "missing": "drop",
    }},
})

Shortened for the Academy: 4 chart(s) dropped to stay under 100 KB.

With default settings, DenStream reads the stream once and reports 3 cluster births and 1 death, ending with 2 clusters. Scored as it goes (prequentially), its clusters have a purity of 98.6% against the known sources. The Discover lesson on stream clusters covers the settings.

10

What runs here

Read
11

Check: irregular and streaming data

Checkpoint

Check yourself

What drives a neural CDE's hidden state between observations?

Show the answer

Answer: b

dz=fθ(z) dXdz = f_\theta(z)\,dX: no change in the path, little change in the state.

Check yourself

A neural CDE was trained with a natural cubic spline path. Can it score sequences in real time as each observation arrives?

Show the answer

Answer: b

Interpolation is a modeling choice. Use a causal path (straight lines between seen points) for online use.

Check yourself

A neural CDE is trained on 39 patients' irregular visit records. What is the unit for its folds and its sample size?

Show the answer

Answer: a

Each sequence is one example. Splitting a patient's visits across folds would leak.

Check yourself

What is a node's memory in a temporal graph network?

Show the answer

Answer: b

Memory is state, not a parameter, so it must be updated in order and carried or reset consistently across splits.

Check yourself

When must a node's memory be updated with an event, relative to predicting that event?

Show the answer

Answer: b

Updating first lets the event leak into its own prediction.

Check yourself

With fading weight 2−λ(t−ti)2^{-\lambda(t - t_i)} and λ=0.5\lambda = 0.5, how much weight does a point that is 2 time units old carry?

Show the answer

Answer: b

2−0.5×2=2−12^{-0.5 \times 2} = 2^{-1}. Every two time units halve the weight here.

Check yourself

Why does DenStream keep micro-clusters instead of rerunning DBSCAN on all past points?

Show the answer

Answer: a

Fading micro-cluster summaries give online updates with bounded memory; offline steps turn them into clusters.

12

Recap

Recap
  • A neural CDE lets changes in an interpolated path drive its hidden state; a non-causal path can't run live.
  • A temporal graph network keeps a memory per node; read it before an event, update it after.
  • DenStream keeps fading micro-clusters of a stream with bounded memory.
  • Neural CDEs and DenStream run in CodeSplash; temporal graphs need a data type it doesn't load yet.

Concepts in this lesson