Clusters that move
Stream clustering replays rows in time order and keeps small summaries that fade with age, so clusters can be born, drift and end. Learn to read cluster evolution and score each window before the model learns it.
What runs in CodeSplash
- SEQ004DenStream Runs in CodeSplash
- Stream clustering (DenStream, DBSTREAM, CluStream) Verified in Python and R
You will be able to
- Explain micro-clusters, fading weights and the half-life
- Read births, endings and drift on the cluster-evolution chart, and why cluster numbers follow overlap
- Use prequential evaluation to score a stream clusterer on rows it hasn't seen
When the groups change
ReadOrdinary clustering treats every row as present at once. Sensor readings, transactions and support tickets arrive over time, and their groups change: a new kind of fault appears, a customer segment drifts, an old pattern stops.
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. replays the rows in time order. Instead of keeping the rows, it keeps micro-clustersMicro-clusterA small summary of nearby rows (weight, sum and sum of squares) that a stream clusterer updates instead of keeping the rows.: small summaries with a weight, a sum and a sum of squares. Every weight fadesFading weight and half-lifeEach row's weight halves every half-life (2^(−λ·age)), so recent rows shape the clusters and old ones fade out. as 2^(−λ·age): after one half-life a row counts half as much. Recent rows shape the clusters; old ones fade out.
Three algorithms
Read- DenStream grows micro-clusters within a radius. Sparse ones are outlier micro-clusters until they gain weight; dense ones are grouped like DBSCAN, and rows in sparse places stay noise.
- DBSTREAM moves fixed-radius micro-clusters toward new rows and links two when many rows fell inside both (shared density).
- CluStream keeps a fixed number of micro-clusters and groups them into k clusters by weighted k-means, so it has no noise.
After each window of rows the clusters are recorded as a snapshotWindow and snapshotThe stream is cut into windows of rows; after each one the clusters are formed from the micro-clusters and recorded. and matched to the previous one by shared micro-cluster weight.
Make a guess
PredictPredict first
A cluster stops receiving rows halfway through the stream. You double the half-life. When does the chart show it ending?
Reveal
Later. Its micro-clusters fade more slowly, so they stay above the weight thresholds for longer before they're pruned. A short half-life reacts fast but forgets real clusters during quiet spells.
Read the card
ReadDenStream 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
View data
| Cluster | x | y |
|---|---|---|
| 2 | −1.127 | −0.4099 |
| 1 | 1.257 | 0.6207 |
| 2 | −0.9507 | −0.9729 |
| 2 | −0.7881 | −0.8292 |
| 1 | 1.176 | 0.6690 |
| 1 | 0.8072 | 0.7739 |
| 2 | −0.8462 | −0.6724 |
| 1 | 1.100 | 0.8137 |
| 1 | 1.346 | 0.5074 |
| 1 | 0.9605 | 0.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 |
| 1 | 1.211 | 0.6173 |
| 2 | −0.8146 | −0.6744 |
| 1 | 1.277 | 0.6906 |
| 2 | −1.137 | −0.5318 |
| 1 | 0.8502 | 0.8321 |
| 2 | −0.8335 | −0.6556 |
| 2 | −0.7553 | −0.7194 |
| 1 | 1.213 | 0.4362 |
| 1 | 1.032 | 0.2751 |
| 2 | −0.9747 | −0.6412 |
| 2 | −0.5998 | −0.8745 |
| 1 | 1.272 | 0.5336 |
| 1 | 1.177 | 0.6567 |
| 2 | −0.9367 | −0.7815 |
| 1 | 1.022 | 0.8654 |
| 2 | −0.7915 | −0.6880 |
| 1 | 1.049 | 0.3958 |
| 1 | 1.064 | 0.7189 |
| 1 | 0.9545 | 0.8472 |
| 2 | −0.9969 | −0.3585 |
| 1 | 1.085 | 0.8443 |
| 2 | −1.015 | −0.5637 |
| 2 | −1.203 | −0.4886 |
| 1 | 1.252 | 0.5667 |
| 2 | −0.7127 | −0.5275 |
| 2 | −0.5086 | −1.292 |
| 2 | −0.6538 | −0.6344 |
| 1 | 1.225 | 0.4769 |
| 2 | −0.9953 | −0.4040 |
| 1 | 1.284 | 0.3511 |
| 2 | −0.5294 | −0.6070 |
| 1 | 1.080 | 0.7250 |
| 2 | −0.8389 | −0.5509 |
| 1 | 0.9155 | 0.6039 |
| 2 | −0.7965 | −0.7222 |
| 1 | 1.080 | 0.7361 |
| 1 | 1.069 | 0.9785 |
| 1 | 0.8846 | 0.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 |
| 1 | 1.125 | 0.7294 |
| 2 | −0.9260 | −0.4401 |
First 60 of 600 rows.
View data
| Cluster | Center: x | time | Weight |
|---|---|---|---|
| 2 | −0.8904 | 60 | 25.947 |
| 1 | 1.100 | 60 | 20.766 |
| 2 | −0.9156 | 90 | 30.168 |
| 1 | 1.078 | 90 | 27.639 |
| 2 | −0.9236 | 120 | 32.582 |
| 1 | 1.109 | 120 | 33.795 |
| 2 | −0.9235 | 150 | 32.831 |
| 1 | 1.105 | 150 | 38.713 |
| 2 | −0.9169 | 180 | 39.775 |
| 1 | 1.115 | 180 | 36.315 |
| 2 | −0.9040 | 210 | 37.240 |
| 1 | 1.087 | 210 | 42.063 |
| 2 | −0.8941 | 240 | 40.764 |
| 1 | 1.079 | 240 | 40.813 |
| 2 | −0.8861 | 270 | 40.366 |
| 1 | 1.066 | 270 | 42.817 |
| 2 | −0.8590 | 300 | 40.527 |
| 1 | 1.079 | 300 | 43.792 |
| 2 | −0.8508 | 330 | 36.872 |
| 1 | 1.097 | 330 | 36.918 |
| 3 | −0.7776 | 330 | 10.389 |
| 2 | −0.8854 | 360 | 33.698 |
| 1 | 1.118 | 360 | 32.963 |
| 3 | −0.8579 | 360 | 17.502 |
| 2 | −0.9071 | 390 | 31.280 |
| 1 | 1.129 | 390 | 29.252 |
| 3 | −0.8755 | 390 | 22.665 |
| 2 | −0.8940 | 420 | 31.739 |
| 1 | 1.119 | 420 | 27.598 |
| 3 | −0.8870 | 420 | 24.991 |
| 2 | −0.8975 | 450 | 34.409 |
| 1 | 1.105 | 450 | 27.307 |
| 3 | −0.8817 | 450 | 23.413 |
| 2 | −0.8975 | 480 | 24.331 |
| 3 | −0.8256 | 480 | 28.407 |
| 1 | 1.097 | 480 | 24.769 |
| 2 | −0.8975 | 510 | 17.205 |
| 3 | −0.8496 | 510 | 32.907 |
| 1 | 1.109 | 510 | 30.194 |
| 3 | −0.8500 | 540 | 39.655 |
| 1 | 1.121 | 540 | 29.542 |
| 3 | −0.8282 | 570 | 40.089 |
| 1 | 1.092 | 570 | 32.621 |
| 3 | −0.8403 | 600 | 39.962 |
| 1 | 1.094 | 600 | 36.952 |
View data
| Measure | time | Value |
|---|---|---|
| Coverage | 90 | 0.9667 |
| Coverage | 120 | 1 |
| Coverage | 150 | 0.9667 |
| Coverage | 180 | 1 |
| Coverage | 210 | 1 |
| Coverage | 240 | 1 |
| Coverage | 270 | 1 |
| Coverage | 300 | 0.9667 |
| Coverage | 330 | 0.4667 |
| Coverage | 360 | 0.9333 |
| Coverage | 390 | 0.9333 |
| Coverage | 420 | 0.9667 |
| Coverage | 450 | 1 |
| Coverage | 480 | 0.9667 |
| Coverage | 510 | 1 |
| Coverage | 540 | 0.9333 |
| Coverage | 570 | 0.9333 |
| Coverage | 600 | 0.9000 |
| Purity | 90 | 1 |
| Purity | 120 | 1 |
| Purity | 150 | 1 |
| Purity | 180 | 1 |
| Purity | 210 | 1 |
| Purity | 240 | 1 |
| Purity | 270 | 0.9667 |
| Purity | 300 | 1 |
| Purity | 330 | 1 |
| Purity | 360 | 0.9643 |
| Purity | 390 | 1 |
| Purity | 420 | 1 |
| Purity | 450 | 0.9667 |
| Purity | 480 | 1 |
| Purity | 510 | 0.9667 |
| Purity | 540 | 0.9286 |
| Purity | 570 | 0.9643 |
| Purity | 600 | 1 |
| Adjusted Rand index | 90 | 1 |
| Adjusted Rand index | 120 | 1 |
| Adjusted Rand index | 150 | 1 |
| Adjusted Rand index | 180 | 1 |
| Adjusted Rand index | 210 | 1 |
| Adjusted Rand index | 240 | 1 |
| Adjusted Rand index | 270 | 0.9308 |
| Adjusted Rand index | 300 | 0.9308 |
| Adjusted Rand index | 330 | 0.8233 |
| Adjusted Rand index | 360 | 0.9039 |
| Adjusted Rand index | 390 | 0.9236 |
| Adjusted Rand index | 420 | 1 |
| Adjusted Rand index | 450 | 0.9320 |
| Adjusted Rand index | 480 | 1 |
| Adjusted Rand index | 510 | 0.9354 |
| Adjusted Rand index | 540 | 0.8552 |
| Adjusted Rand index | 570 | 0.9287 |
| Adjusted Rand index | 600 | 0.8196 |
View data
| Cluster | Silhouette width |
|---|---|
| 1 | 0.6387 |
| 1 | 0.6381 |
| 1 | 0.6371 |
| 1 | 0.6362 |
| 1 | 0.6354 |
| 1 | 0.6347 |
| 1 | 0.6344 |
| 1 | 0.6344 |
| 1 | 0.6339 |
| 1 | 0.6338 |
| 1 | 0.6337 |
| 1 | 0.6332 |
| 1 | 0.6316 |
| 1 | 0.6312 |
| 1 | 0.6309 |
| 1 | 0.6308 |
| 1 | 0.6277 |
| 1 | 0.6260 |
| 1 | 0.6259 |
| 1 | 0.6248 |
| 1 | 0.6244 |
| 1 | 0.6220 |
| 1 | 0.6217 |
| 1 | 0.6210 |
| 1 | 0.6206 |
| 1 | 0.6197 |
| 1 | 0.6176 |
| 1 | 0.6169 |
| 1 | 0.6166 |
| 1 | 0.6164 |
| 1 | 0.6156 |
| 1 | 0.6154 |
| 1 | 0.6153 |
| 1 | 0.6137 |
| 1 | 0.6125 |
| 1 | 0.6122 |
| 1 | 0.6119 |
| 1 | 0.6102 |
| 1 | 0.6089 |
| 1 | 0.6082 |
| 1 | 0.6080 |
| 1 | 0.6076 |
| 1 | 0.6066 |
| 1 | 0.6058 |
| 1 | 0.6053 |
| 1 | 0.6052 |
| 1 | 0.6049 |
| 1 | 0.6048 |
| 1 | 0.6035 |
| 1 | 0.6025 |
| 1 | 0.6018 |
| 1 | 0.6006 |
| 1 | 0.6000 |
| 1 | 0.5999 |
| 1 | 0.5996 |
| 1 | 0.5972 |
| 1 | 0.5959 |
| 1 | 0.5958 |
| 1 | 0.5952 |
| 1 | 0.5950 |
First 60 of 593 rows.
Clusters
| Cluster | Size | Share | x | y |
|---|---|---|---|---|
| 1 | 263 | 43.8% | 1.989 | 0.5768 |
| 2 | 200 | 33.3% | −2.039 | −0.0270 |
| 3 | 130 | 21.7% | −1.936 | 3.079 |
Windows: snapshots and prequential evaluation
| Window | Ends at (time) | Rows so far | Clusters | Micro-clusters | Outlier micro-clusters | Born | Ended | Coverage (prequential) | Mean squared distance | Purity | Adjusted Rand index |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 2 | 60 | 60 | 2 | 4 | 0 | 2, 1 | — | — | — | — | |
| 3 | 90 | 90 | 2 | 4 | 0 | 96.7% | 0.0876 | 1 | 1 | ||
| 4 | 120 | 120 | 2 | 4 | 0 | 100.0% | 0.0897 | 1 | 1 | ||
| 5 | 150 | 150 | 2 | 4 | 0 | 96.7% | 0.0777 | 1 | 1 | ||
| 6 | 180 | 180 | 2 | 4 | 0 | 100.0% | 0.0901 | 1 | 1 | ||
| 7 | 210 | 210 | 2 | 4 | 0 | 100.0% | 0.0774 | 1 | 1 | ||
| 8 | 240 | 240 | 2 | 4 | 0 | 100.0% | 0.1614 | 1 | 1 | ||
| 9 | 270 | 270 | 2 | 4 | 0 | 100.0% | 0.1561 | 0.9667 | 0.9308 | ||
| 10 | 300 | 300 | 2 | 4 | 0 | 96.7% | 0.1867 | 1 | 0.9308 | ||
| 11 | 330 | 330 | 3 | 5 | 0 | 3 | 46.7% | 0.1241 | 1 | 0.8233 | |
| 12 | 360 | 360 | 3 | 6 | 1 | 93.3% | 0.1541 | 0.9643 | 0.9039 | ||
| 13 | 390 | 390 | 3 | 5 | 0 | 93.3% | 0.1429 | 1 | 0.9236 | ||
| 14 | 420 | 420 | 3 | 5 | 0 | 96.7% | 0.2141 | 1 | 1 | ||
| 15 | 450 | 450 | 3 | 5 | 0 | 100.0% | 0.2353 | 0.9667 | 0.9320 | ||
| 16 | 480 | 480 | 3 | 5 | 0 | 96.7% | 0.2582 | 1 | 1 | ||
| 17 | 510 | 510 | 3 | 5 | 0 | 100.0% | 0.1228 | 0.9667 | 0.9354 | ||
| 18 | 540 | 540 | 2 | 6 | 1 | 2 | 93.3% | 0.0970 | 0.9286 | 0.8552 | |
| 19 | 570 | 570 | 2 | 5 | 0 | 93.3% | 0.0958 | 0.9643 | 0.9287 | ||
| 20 | 600 | 600 | 2 | 5 | 0 | 90.0% | 0.1610 | 1 | 0.8196 |
Micro-clusters at the end of the stream
| Id | Kind | Weight | Created (clock) | Radius | Cluster | Center: x | Center: y |
|---|---|---|---|---|---|---|---|
| 1 | potential | 2.426 | 30 | 0.3468 | noise | −0.9007 | −0.3211 |
| 2 | potential | 2.047 | 30 | 0.4157 | noise | 1.136 | −0.0394 |
| 3 | potential | 3.656 | 30 | 0.2983 | noise | −0.8953 | −0.7614 |
| 7 | potential | 39.962 | 304 | 0.3190 | 3 | −0.8403 | 1.404 |
| 10 | potential | 36.952 | 362 | 0.4034 | 1 | 1.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"
))
))
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
| Cluster | Size | Share | x | y |
|---|---|---|---|---|
| 1 | 263 | 43.8% | 1.989 | 0.5768 |
| 2 | 200 | 33.3% | −2.039 | −0.0270 |
| 3 | 130 | 21.7% | −1.936 | 3.079 |
Windows: snapshots and prequential evaluation
| Window | Ends at (time) | Rows so far | Clusters | Micro-clusters | Outlier micro-clusters | Born | Ended | Coverage (prequential) | Mean squared distance | Purity | Adjusted Rand index |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 2 | 60 | 60 | 2 | 4 | 0 | 2, 1 | — | — | — | — | |
| 3 | 90 | 90 | 2 | 4 | 0 | 96.7% | 0.0876 | 1 | 1 | ||
| 4 | 120 | 120 | 2 | 4 | 0 | 100.0% | 0.0897 | 1 | 1 | ||
| 5 | 150 | 150 | 2 | 4 | 0 | 96.7% | 0.0777 | 1 | 1 | ||
| 6 | 180 | 180 | 2 | 4 | 0 | 100.0% | 0.0901 | 1 | 1 | ||
| 7 | 210 | 210 | 2 | 4 | 0 | 100.0% | 0.0774 | 1 | 1 | ||
| 8 | 240 | 240 | 2 | 4 | 0 | 100.0% | 0.1614 | 1 | 1 | ||
| 9 | 270 | 270 | 2 | 4 | 0 | 100.0% | 0.1561 | 0.9667 | 0.9308 | ||
| 10 | 300 | 300 | 2 | 4 | 0 | 96.7% | 0.1867 | 1 | 0.9308 | ||
| 11 | 330 | 330 | 3 | 5 | 0 | 3 | 46.7% | 0.1241 | 1 | 0.8233 | |
| 12 | 360 | 360 | 3 | 6 | 1 | 93.3% | 0.1541 | 0.9643 | 0.9039 | ||
| 13 | 390 | 390 | 3 | 5 | 0 | 93.3% | 0.1429 | 1 | 0.9236 | ||
| 14 | 420 | 420 | 3 | 5 | 0 | 96.7% | 0.2141 | 1 | 1 | ||
| 15 | 450 | 450 | 3 | 5 | 0 | 100.0% | 0.2353 | 0.9667 | 0.9320 | ||
| 16 | 480 | 480 | 3 | 5 | 0 | 96.7% | 0.2582 | 1 | 1 | ||
| 17 | 510 | 510 | 3 | 5 | 0 | 100.0% | 0.1228 | 0.9667 | 0.9354 | ||
| 18 | 540 | 540 | 2 | 6 | 1 | 2 | 93.3% | 0.0970 | 0.9286 | 0.8552 | |
| 19 | 570 | 570 | 2 | 5 | 0 | 93.3% | 0.0958 | 0.9643 | 0.9287 | ||
| 20 | 600 | 600 | 2 | 5 | 0 | 90.0% | 0.1610 | 1 | 0.8196 |
Micro-clusters at the end of the stream
| Id | Kind | Weight | Created (clock) | Radius | Cluster | Center: x | Center: y |
|---|---|---|---|---|---|---|---|
| 1 | potential | 2.426 | 30 | 0.3468 | noise | −0.9007 | −0.3211 |
| 2 | potential | 2.047 | 30 | 0.4157 | noise | 1.136 | −0.0394 |
| 3 | potential | 3.656 | 30 | 0.2983 | noise | −0.8953 | −0.7614 |
| 7 | potential | 39.962 | 304 | 0.3190 | 3 | −0.8403 | 1.404 |
| 10 | potential | 36.952 | 362 | 0.4034 | 1 | 1.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.
This stream has a stable cluster, one that drifts, one born at row 300 and one that stops after row 450. The run found 3 births and 1 endings.
View data
| week | cluster | weight | center (x) |
|---|---|---|---|
| 1,767,225,600,000 | 1 | 43.600 | −2.073 |
| 1,767,225,600,000 | 2 | 39.800 | 2.082 |
| 1,767,830,400,000 | 1 | 38.300 | −1.917 |
| 1,767,830,400,000 | 2 | 42 | 1.770 |
| 1,768,435,200,000 | 1 | 35 | −1.987 |
| 1,768,435,200,000 | 2 | 42.700 | 1.752 |
| 1,769,040,000,000 | 1 | 36.700 | −2.025 |
| 1,769,040,000,000 | 2 | 43.900 | 1.498 |
| 1,769,644,800,000 | 1 | 40.400 | −1.980 |
| 1,769,644,800,000 | 2 | 40.300 | 1.364 |
| 1,770,249,600,000 | 1 | 44.600 | −1.989 |
| 1,770,249,600,000 | 2 | 41.600 | 1.096 |
| 1,770,854,400,000 | 1 | 40.100 | −2.015 |
| 1,770,854,400,000 | 2 | 35.400 | 0.9580 |
| 1,771,459,200,000 | 1 | 39 | −2.018 |
| 1,771,459,200,000 | 2 | 36 | 0.7360 |
| 1,772,064,000,000 | 1 | 44.900 | −1.965 |
| 1,772,064,000,000 | 2 | 36.600 | 0.6140 |
| 1,772,064,000,000 | 3 | 5 | 0.4210 |
| 1,772,668,800,000 | 1 | 48.100 | −2.065 |
| 1,772,668,800,000 | 2 | 31.100 | 0.4420 |
| 1,772,668,800,000 | 3 | 10 | 0.5150 |
| 1,773,273,600,000 | 1 | 40.700 | −2.033 |
| 1,773,273,600,000 | 2 | 41 | 0.2390 |
| 1,773,273,600,000 | 3 | 13.900 | 0.5290 |
| 1,773,878,400,000 | 1 | 45.500 | −1.972 |
| 1,773,878,400,000 | 2 | 30.600 | 0.0780 |
| 1,773,878,400,000 | 3 | 20.500 | 0.4870 |
| 1,774,483,200,000 | 1 | 40.900 | −1.865 |
| 1,774,483,200,000 | 2 | 40.600 | −0.0280 |
| 1,774,483,200,000 | 3 | 21.600 | 0.4840 |
| 1,775,088,000,000 | 1 | 43.800 | −2.044 |
| 1,775,088,000,000 | 2 | 39.300 | −0.3950 |
| 1,775,088,000,000 | 3 | 23.600 | 0.4270 |
| 1,775,088,000,000 | 4 | 9 | 2.982 |
| 1,775,692,800,000 | 1 | 39 | −1.972 |
| 1,775,692,800,000 | 2 | 37.500 | −0.5020 |
| 1,775,692,800,000 | 3 | 33.800 | 0.5180 |
| 1,775,692,800,000 | 4 | 9 | 2.944 |
| 1,776,297,600,000 | 1 | 30 | −1.976 |
| 1,776,297,600,000 | 2 | 39.400 | −0.5450 |
| 1,776,297,600,000 | 3 | 33.800 | 0.5120 |
| 1,776,297,600,000 | 4 | 10.900 | 2.927 |
| 1,776,902,400,000 | 1 | 20.300 | −1.988 |
| 1,776,902,400,000 | 2 | 41.400 | −0.7590 |
| 1,776,902,400,000 | 3 | 33.200 | 0.4970 |
| 1,776,902,400,000 | 4 | 6.600 | 3.085 |
| 1,777,507,200,000 | 1 | 12 | −1.961 |
| 1,777,507,200,000 | 2 | 42.500 | −0.9570 |
| 1,777,507,200,000 | 3 | 34.800 | 0.4150 |
| 1,778,112,000,000 | 2 | 36.300 | −1.120 |
| 1,778,112,000,000 | 3 | 34.300 | 0.4450 |
| 1,778,716,800,000 | 2 | 39.300 | −1.269 |
| 1,778,716,800,000 | 3 | 39 | 0.4730 |
| 1,779,321,600,000 | 2 | 42.800 | −1.445 |
| 1,779,321,600,000 | 3 | 39.800 | 0.5200 |
| 1,779,926,400,000 | 2 | 33.300 | −1.587 |
| 1,779,926,400,000 | 3 | 38.900 | 0.4150 |
| 1,780,531,200,000 | 2 | 40.500 | −1.808 |
| 1,780,531,200,000 | 3 | 41.600 | 0.4190 |
First 60 of 62 rows.
Each band is a cluster's weight per snapshot. A ▲ marks its first snapshot and a ✕ its last. Switch the view to Centers to see the drifting cluster slide along a feature while it keeps its number. Numbers follow overlapCluster births and endingsA cluster is born in the first snapshot it appears in and ends after its last; numbers carry over by shared micro-cluster weight., not identity: after a split, either part can keep the number.
Score before you learn
ReadDBSTREAM over 600 rows in 20 windows: 3 clusters at the end, up to 5 at once, 6 born and 3 ended; prequential coverage 80%.
- Clusters
- 6
- Mean silhouette
- 0.2941
Clusters
| Cluster | Size | Share | x | y |
|---|---|---|---|---|
| 1 | 233 | 38.8% | 1.983 | 0.7286 |
| 2 | 188 | 31.3% | −2.046 | −0.0342 |
| 3 | 107 | 17.8% | −1.991 | 3.099 |
| 4 | 8 | 1.3% | −1.777 | 2.346 |
| 5 | 3 | 0.5% | −2.102 | 3.509 |
| 6 | 2 | 0.3% | 1.398 | −0.7110 |
Windows: snapshots and prequential evaluation
| Window | Ends at (time) | Rows so far | Clusters | Micro-clusters | Born | Ended | Coverage (prequential) | Mean squared distance | Purity | Adjusted Rand index |
|---|---|---|---|---|---|---|---|---|---|---|
| 1 | 30 | 30 | 2 | 6 | 2, 1 | — | — | — | — | |
| 2 | 60 | 60 | 2 | 7 | 96.7% | 0.0668 | 1 | 1 | ||
| 3 | 90 | 90 | 2 | 11 | 80.0% | 0.0672 | 1 | 0.6628 | ||
| 4 | 120 | 120 | 2 | 11 | 96.7% | 0.0827 | 1 | 0.9448 | ||
| 5 | 150 | 150 | 2 | 13 | 86.7% | 0.0574 | 1 | 0.7849 | ||
| 6 | 180 | 180 | 2 | 13 | 96.7% | 0.0780 | 1 | 0.9540 | ||
| 7 | 210 | 210 | 2 | 12 | 93.3% | 0.0690 | 1 | 0.8671 | ||
| 8 | 240 | 240 | 2 | 14 | 76.7% | 0.0793 | 1 | 0.6304 | ||
| 9 | 270 | 270 | 2 | 17 | 76.7% | 0.1281 | 0.9565 | 0.5239 | ||
| 10 | 300 | 300 | 2 | 18 | 80.0% | 0.1636 | 1 | 0.6611 | ||
| 11 | 330 | 330 | 4 | 24 | 4, 3 | 46.7% | 0.1314 | 1 | 0.8233 | |
| 12 | 360 | 360 | 5 | 26 | 5 | 83.3% | 0.1274 | 1 | 0.7322 | |
| 13 | 390 | 390 | 4 | 24 | 5 | 93.3% | 0.1559 | 1 | 0.8317 | |
| 14 | 420 | 420 | 4 | 27 | 76.7% | 0.1536 | 1 | 0.5990 | ||
| 15 | 450 | 450 | 5 | 28 | 6 | 73.3% | 0.0965 | 0.9545 | 0.7852 | |
| 16 | 480 | 480 | 3 | 28 | 4, 6 | 53.3% | 0.0760 | 1 | 0.5807 | |
| 17 | 510 | 510 | 3 | 28 | 86.7% | 0.0958 | 1 | 0.7973 | ||
| 18 | 540 | 540 | 3 | 30 | 83.3% | 0.0748 | 0.9600 | 0.8108 | ||
| 19 | 570 | 570 | 3 | 31 | 80.0% | 0.0681 | 1 | 0.8084 | ||
| 20 | 600 | 600 | 3 | 29 | 56.7% | 0.0911 | 1 | 0.8196 |
Micro-clusters at the end of the stream
| Id | Kind | Weight | Created (clock) | Radius | Cluster | Center: x | Center: y |
|---|---|---|---|---|---|---|---|
| 1 | micro | 2.690 | 1 | 0.2130 | noise | −0.9163 | −0.4570 |
| 3 | micro | 3.236 | 3 | 0 | 2 | −0.9076 | −0.8076 |
| 5 | micro | 2.524 | 7 | 0.5586 | noise | −0.6051 | −0.5902 |
| 6 | micro | 0.6569 | 24 | 0.2876 | noise | 1.027 | 0.3255 |
| 11 | micro | 1.708 | 73 | 0 | noise | −1.185 | −0.6338 |
| 17 | micro | 0.7810 | 206 | 0.3045 | noise | −0.6198 | −0.2171 |
| 18 | micro | 0.7521 | 215 | 0 | noise | −0.7110 | −1.042 |
| 20 | micro | 1.150 | 233 | 0.2716 | noise | 1.144 | −0.3693 |
| 21 | micro | 0.6662 | 243 | 0.1156 | noise | 1.173 | −0.0207 |
| 22 | micro | 0.5586 | 252 | 0.2876 | noise | −1.112 | −0.1956 |
| 25 | micro | 5.510 | 301 | 0.5722 | 3 | −0.8410 | 0.9519 |
| 26 | micro | 24.922 | 304 | 0.5421 | 3 | −0.8224 | 1.269 |
| 27 | micro | 2.504 | 306 | 0 | noise | 1.199 | −0.7659 |
| 28 | micro | 11.801 | 319 | 0.5093 | 3 | −0.5773 | 1.465 |
| 29 | micro | 5.435 | 320 | 0 | 3 | −0.7373 | 1.873 |
| 32 | micro | 8.996 | 346 | 0 | 3 | −1.124 | 1.121 |
| 34 | micro | 10.841 | 364 | 0 | 3 | −1.214 | 1.446 |
| 37 | micro | 2.568 | 408 | 0.5113 | noise | 0.6952 | −1.008 |
| 39 | micro | 12.953 | 416 | 0 | 1 | 1.275 | −1.312 |
| 40 | micro | 14.208 | 440 | 0.4639 | 1 | 0.9709 | −1.253 |
| 41 | micro | 4.005 | 464 | 0.5428 | 3 | −0.4973 | 1.090 |
| 44 | micro | 9.923 | 496 | 0 | 1 | 1.193 | −1.798 |
| 46 | micro | 1.071 | 523 | 0 | noise | 1.662 | −1.390 |
| 47 | micro | 11.529 | 532 | 0.1404 | 3 | −0.8959 | 1.569 |
| 49 | micro | 0.5484 | 548 | 0 | noise | 0.8797 | −2.864 |
| 50 | micro | 6.689 | 553 | 0.6377 | 1 | 0.9143 | −1.599 |
| 51 | micro | 0.6674 | 565 | 0 | noise | −0.5735 | −2.537 |
| 52 | micro | 2.772 | 586 | 0 | noise | 1.042 | −2.185 |
| 53 | micro | 0.8807 | 589 | 0 | noise | 1.568 | −1.985 |
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 7799d97909832599
# 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_dbstream_shared/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 <- "dbstream"
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 <- 0.3
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 = "dbstream",
clock = "rows",
window = NULL,
half_life = NULL,
radius = 0.3,
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"
))
))
DBSTREAM over 600 rows in 20 windows: 3 clusters at the end, up to 5 at once, 6 born and 3 ended; prequential coverage 80%.
- Clusters
- 6
- Mean silhouette
- 0.2941
Clusters
| Cluster | Size | Share | x | y |
|---|---|---|---|---|
| 1 | 233 | 38.8% | 1.983 | 0.7286 |
| 2 | 188 | 31.3% | −2.046 | −0.0342 |
| 3 | 107 | 17.8% | −1.991 | 3.099 |
| 4 | 8 | 1.3% | −1.777 | 2.346 |
| 5 | 3 | 0.5% | −2.102 | 3.509 |
| 6 | 2 | 0.3% | 1.398 | −0.7110 |
Windows: snapshots and prequential evaluation
| Window | Ends at (time) | Rows so far | Clusters | Micro-clusters | Born | Ended | Coverage (prequential) | Mean squared distance | Purity | Adjusted Rand index |
|---|---|---|---|---|---|---|---|---|---|---|
| 1 | 30 | 30 | 2 | 6 | 2, 1 | — | — | — | — | |
| 2 | 60 | 60 | 2 | 7 | 96.7% | 0.0668 | 1 | 1 | ||
| 3 | 90 | 90 | 2 | 11 | 80.0% | 0.0672 | 1 | 0.6628 | ||
| 4 | 120 | 120 | 2 | 11 | 96.7% | 0.0827 | 1 | 0.9448 | ||
| 5 | 150 | 150 | 2 | 13 | 86.7% | 0.0574 | 1 | 0.7849 | ||
| 6 | 180 | 180 | 2 | 13 | 96.7% | 0.0780 | 1 | 0.9540 | ||
| 7 | 210 | 210 | 2 | 12 | 93.3% | 0.0690 | 1 | 0.8671 | ||
| 8 | 240 | 240 | 2 | 14 | 76.7% | 0.0793 | 1 | 0.6304 | ||
| 9 | 270 | 270 | 2 | 17 | 76.7% | 0.1281 | 0.9565 | 0.5239 | ||
| 10 | 300 | 300 | 2 | 18 | 80.0% | 0.1636 | 1 | 0.6611 | ||
| 11 | 330 | 330 | 4 | 24 | 4, 3 | 46.7% | 0.1314 | 1 | 0.8233 | |
| 12 | 360 | 360 | 5 | 26 | 5 | 83.3% | 0.1274 | 1 | 0.7322 | |
| 13 | 390 | 390 | 4 | 24 | 5 | 93.3% | 0.1559 | 1 | 0.8317 | |
| 14 | 420 | 420 | 4 | 27 | 76.7% | 0.1536 | 1 | 0.5990 | ||
| 15 | 450 | 450 | 5 | 28 | 6 | 73.3% | 0.0965 | 0.9545 | 0.7852 | |
| 16 | 480 | 480 | 3 | 28 | 4, 6 | 53.3% | 0.0760 | 1 | 0.5807 | |
| 17 | 510 | 510 | 3 | 28 | 86.7% | 0.0958 | 1 | 0.7973 | ||
| 18 | 540 | 540 | 3 | 30 | 83.3% | 0.0748 | 0.9600 | 0.8108 | ||
| 19 | 570 | 570 | 3 | 31 | 80.0% | 0.0681 | 1 | 0.8084 | ||
| 20 | 600 | 600 | 3 | 29 | 56.7% | 0.0911 | 1 | 0.8196 |
Micro-clusters at the end of the stream
| Id | Kind | Weight | Created (clock) | Radius | Cluster | Center: x | Center: y |
|---|---|---|---|---|---|---|---|
| 1 | micro | 2.690 | 1 | 0.2130 | noise | −0.9163 | −0.4570 |
| 3 | micro | 3.236 | 3 | 0 | 2 | −0.9076 | −0.8076 |
| 5 | micro | 2.524 | 7 | 0.5586 | noise | −0.6051 | −0.5902 |
| 6 | micro | 0.6569 | 24 | 0.2876 | noise | 1.027 | 0.3255 |
| 11 | micro | 1.708 | 73 | 0 | noise | −1.185 | −0.6338 |
| 17 | micro | 0.7810 | 206 | 0.3045 | noise | −0.6198 | −0.2171 |
| 18 | micro | 0.7521 | 215 | 0 | noise | −0.7110 | −1.042 |
| 20 | micro | 1.150 | 233 | 0.2716 | noise | 1.144 | −0.3693 |
| 21 | micro | 0.6662 | 243 | 0.1156 | noise | 1.173 | −0.0207 |
| 22 | micro | 0.5586 | 252 | 0.2876 | noise | −1.112 | −0.1956 |
| 25 | micro | 5.510 | 301 | 0.5722 | 3 | −0.8410 | 0.9519 |
| 26 | micro | 24.922 | 304 | 0.5421 | 3 | −0.8224 | 1.269 |
| 27 | micro | 2.504 | 306 | 0 | noise | 1.199 | −0.7659 |
| 28 | micro | 11.801 | 319 | 0.5093 | 3 | −0.5773 | 1.465 |
| 29 | micro | 5.435 | 320 | 0 | 3 | −0.7373 | 1.873 |
| 32 | micro | 8.996 | 346 | 0 | 3 | −1.124 | 1.121 |
| 34 | micro | 10.841 | 364 | 0 | 3 | −1.214 | 1.446 |
| 37 | micro | 2.568 | 408 | 0.5113 | noise | 0.6952 | −1.008 |
| 39 | micro | 12.953 | 416 | 0 | 1 | 1.275 | −1.312 |
| 40 | micro | 14.208 | 440 | 0.4639 | 1 | 0.9709 | −1.253 |
| 41 | micro | 4.005 | 464 | 0.5428 | 3 | −0.4973 | 1.090 |
| 44 | micro | 9.923 | 496 | 0 | 1 | 1.193 | −1.798 |
| 46 | micro | 1.071 | 523 | 0 | noise | 1.662 | −1.390 |
| 47 | micro | 11.529 | 532 | 0.1404 | 3 | −0.8959 | 1.569 |
| 49 | micro | 0.5484 | 548 | 0 | noise | 0.8797 | −2.864 |
| 50 | micro | 6.689 | 553 | 0.6377 | 1 | 0.9143 | −1.599 |
| 51 | micro | 0.6674 | 565 | 0 | noise | −0.5735 | −2.537 |
| 52 | micro | 2.772 | 586 | 0 | noise | 1.042 | −2.185 |
| 53 | micro | 0.8807 | 589 | 0 | noise | 1.568 | −1.985 |
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 7799d97909832599
# 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_dbstream_shared/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 = "dbstream"
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 = 0.3
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": "dbstream",
"clock": "rows",
"window": None,
"half_life": None,
"radius": 0.3,
"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; 4 chart(s) dropped to stay under 100 KB.
Prequential evaluationPrequential evaluationEach window is scored by the model built before it, then learned from: every score is on rows the model hadn't seen. scores each window with the snapshot built before it, then learns from the window. Coverage is the share of rows the earlier model could place: 79.8% here. With a Known groups column you also get purity and the adjusted Rand index per window.
Check your understanding
CheckpointCheck yourself
Why do stream clusterers keep micro-clusters instead of the rows?
Show the answer
Answer: a
A weight, a sum and a sum of squares are enough to update a center and a spread, and fading them is one multiplication.
Check yourself
What makes prequential coverage an honest score?
Show the answer
Answer: b
Test-then-train: every row is scored before the model has seen it.
Check yourself
Cluster 2 splits into two parts. What happens to its number?
Show the answer
Answer: b
Snapshots are matched by shared micro-cluster weight, largest overlap first, so one part carries the number on.
Try it
In the appIn Discover, pick Stream clustering (DenStream, DBSTREAM, CluStream), the feature columns and the Time column. Start with DenStream's defaults; raise the radius if every row ends up as noise, and set the half-life to how long a pattern should be remembered.
Recap
Read- Stream clustering replays rows in time order and keeps fading micro-clusters.
- The cluster-evolution chart shows births (▲), endings (✕) and drift; numbers follow overlap.
- Prequential evaluation scores each window with the model built before it.
Concepts in this lesson