TS2Vec: learning what series look like, without labels
Turn each series, or each stretch of one, into a short learned vector with TS2Vec, read the embedding map, and check with a probe whether the embeddings separate known classes.
What runs in CodeSplash
You will be able to
- Explain how TS2Vec learns from overlapping crops without labels
- Choose between whole-series and window embeddings
- Read the probe against the most common class
- Spot dimensional collapse in the map
Fixed features vs learned ones
ReadWavelet scattering turns a signal into fixed features: the same filters for every dataset, no training. TS2VecTS2VecA convolutional encoder trained without labels so overlapping crops of a series get the same representation. learns its features from your series instead, with no labels, through contrastive learningContrastive learningLearning representations without labels by pulling two views of the same row together and pushing other rows' views away.. Two overlapping random crops of a series must get the same representation where they overlap, while different series and different moments must stay apart.
Embedding whole series
ReadTS2Vec embedded 24 series of x as 8 numbers each, after 8 epochs of contrastive training. A nearest-neighbor probe on the embeddings recovers class for 62% of the series (most common class: 50%).
- Final contrastive loss
- 2.497
Plots
View data
| series | Component 1 | Component 2 |
|---|---|---|
| s01 | −0.1372 | −0.0399 |
| s02 | −0.1724 | 0.1036 |
| s03 | −0.0077 | −0.0849 |
| s04 | −0.1550 | −0.1376 |
| s05 | 0.1363 | 0.1072 |
| s06 | −0.1693 | 0.0737 |
| s07 | −0.0848 | −0.0578 |
| s08 | 0.1947 | −0.0148 |
| s09 | 0.0041 | −0.0909 |
| s10 | 0.2092 | 0.0930 |
| s11 | −0.0639 | −0.0200 |
| s12 | −0.0128 | −0.0145 |
| s13 | −0.1507 | 0.1723 |
| s14 | 0.0214 | −0.0626 |
| s15 | 0.1346 | 0.0622 |
| s16 | 0.1399 | 0.0781 |
| s17 | 0.1059 | −0.0193 |
| s18 | −0.0652 | −0.1288 |
| s19 | 0.1213 | −0.0035 |
| s20 | −0.0419 | −0.0299 |
| s21 | −0.1495 | 0.0424 |
| s22 | −0.0466 | 0.1408 |
| s23 | 0.0527 | −0.0302 |
| s24 | 0.1369 | −0.1386 |
View data
| Part | Loss | Epoch |
|---|---|---|
| Contrastive | 2.746 | 1 |
| Contrastive | 2.478 | 2 |
| Contrastive | 2.829 | 3 |
| Contrastive | 2.661 | 4 |
| Contrastive | 2.390 | 5 |
| Contrastive | 2.351 | 6 |
| Contrastive | 2.635 | 7 |
| Contrastive | 2.497 | 8 |
Assumptions
- The embeddings use several directions — The first principal direction holds 37% of the embeddings' variance.
Embeddings (first 8 of 8 numbers)
| series | e1 | e2 | e3 | e4 | e5 | e6 | e7 | e8 |
|---|---|---|---|---|---|---|---|---|
| s01 | 1.355 | 0.8915 | 0.1968 | 0.5035 | 0.5307 | 1.189 | 0.1295 | 0.3136 |
| s02 | 1.391 | 0.8583 | 0.1205 | 0.4513 | 0.4779 | 1.141 | 0.3330 | 0.2215 |
| s03 | 1.322 | 0.7592 | 0.1330 | 0.5260 | 0.4712 | 1.278 | 0.1525 | 0.2157 |
| s04 | 1.424 | 0.7538 | 0.1272 | 0.5547 | 0.4465 | 1.154 | 0.1342 | 0.2434 |
| s05 | 1.260 | 0.7658 | 0.0659 | 0.3615 | 0.5803 | 1.380 | 0.2575 | 0.2331 |
| s06 | 1.381 | 0.9242 | 0.1204 | 0.3649 | 0.4911 | 1.158 | 0.1537 | 0.3165 |
| s07 | 1.369 | 0.7521 | 0.1375 | 0.4631 | 0.4042 | 1.202 | 0.1681 | 0.2179 |
| s08 | 1.002 | 0.6941 | 0.1851 | 0.4972 | 0.5066 | 1.291 | 0.2101 | 0.2694 |
| s09 | 1.352 | 0.7812 | 0.1710 | 0.5499 | 0.5701 | 1.316 | 0.1562 | 0.2677 |
| s10 | 1.208 | 0.7354 | 0.1280 | 0.3130 | 0.5225 | 1.432 | 0.2173 | 0.2453 |
| s11 | 1.320 | 0.8090 | 0.0728 | 0.4197 | 0.4919 | 1.210 | 0.1111 | 0.3891 |
| s12 | 1.342 | 0.7956 | 0.1589 | 0.4335 | 0.4887 | 1.286 | 0.1642 | 0.2563 |
| s13 | 1.326 | 0.9750 | 0.1394 | 0.4650 | 0.5261 | 1.197 | 0.3476 | 0.3321 |
| s14 | 1.232 | 0.7201 | 0.1418 | 0.4277 | 0.5188 | 1.203 | 0.1077 | 0.2640 |
| s15 | 1.280 | 0.7304 | 0.0649 | 0.3915 | 0.5224 | 1.388 | 0.2487 | 0.2079 |
| s16 | 1.312 | 0.7454 | 0.1046 | 0.3171 | 0.4820 | 1.422 | 0.2159 | 0.2322 |
| s17 | 1.234 | 0.8455 | 0.1893 | 0.5073 | 0.6515 | 1.394 | 0.1459 | 0.3795 |
| s18 | 1.353 | 0.7491 | 0.1252 | 0.5764 | 0.4607 | 1.230 | 0.1463 | 0.2585 |
| s19 | 1.207 | 0.7049 | 0.0896 | 0.4040 | 0.5126 | 1.318 | 0.1673 | 0.3490 |
| s20 | 1.354 | 0.7607 | 0.1114 | 0.4225 | 0.5092 | 1.227 | 0.1499 | 0.2993 |
| s21 | 1.342 | 0.8689 | 0.1143 | 0.4154 | 0.5194 | 1.135 | 0.1790 | 0.3695 |
| s22 | 1.252 | 0.9211 | 0.0925 | 0.4747 | 0.4490 | 1.273 | 0.3166 | 0.3012 |
| s23 | 1.351 | 0.7629 | 0.0462 | 0.4471 | 0.5765 | 1.352 | 0.1417 | 0.3761 |
| s24 | 1.315 | 0.7042 | 0.1600 | 0.5681 | 0.5231 | 1.449 | 0.1397 | 0.3353 |
Leave-one-out nearest-neighbor probe
| Features | Accuracy |
|---|---|
| TS2Vec embedding (8 numbers) | 62.5% |
| Always the most common class | 50.0% |
- The embeddings are learned without labels: series whose patterns look alike end up close together, whatever their level and scale (each series is standardized first).
- Each step's representation sees about 30 neighboring steps on each side; a series' embedding is the maximum over its steps, so it records which patterns occur, not when.
The exact R script · R R version 4.5.1 (2025-06-13)
# TS2Vec series embeddings (contrastive time-series representation)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.ts_embed 1.0.0 · spec a0b2ac8234063cc1
# Dataset: seq_signals (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/seq_signals.parquet", col_select = c("x", "series", "step", "class")))
n_input <- nrow(df)
df[["series"]] <- factor(df[["series"]], levels = c("s01", "s02", "s03", "s04", "s05", "s06", "s07", "s08", "s09", "s10", "s11", "s12", "s13", "s14", "s15", "s16", "s17", "s18", "s19", "s20", "s21", "s22", "s23", "s24")) # stored level order
df[["class"]] <- factor(df[["class"]], levels = c("fast", "slow")) # stored level order
df <- df[stats::complete.cases(df[c("x", "series", "step", "class")]), , drop = FALSE] # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("x", "series", "step", "class")) # infinite values stop the run (registry/errors.yaml)
# %% Series
# TS2Vec (Yue et al. 2022): a dilated-convolution encoder trained with the hierarchical contrastive loss on random
# overlapping crops (contextual consistency); each series (or window of one) is embedded by max-pooling its steps.
VALUE <- "x"
SERIES <- "series"
TIME <- "step"
LABEL <- "class"
UNIT <- "series" # series | window
WINDOW <- NULL
STRIDE <- NULL
DIMS <- as.integer(8)
HIDDEN <- as.integer(8)
DEPTH <- as.integer(3)
EPOCHS <- as.integer(8)
LR <- as.numeric(0.001)
BATCH <- as.integer(8)
SEED <- 42
d <- df
if (!is.null(SERIES) && !is.null(TIME)) {
d <- d[order(as.integer(d[[SERIES]]), d[[TIME]], method = "radix"), , drop = FALSE]
} else if (!is.null(SERIES)) {
d <- d[order(as.integer(d[[SERIES]]), method = "radix"), , drop = FALSE]
} else if (!is.null(TIME)) {
d <- d[order(d[[TIME]], method = "radix"), , drop = FALSE]
}
rownames(d) <- NULL
x_all <- as.numeric(d[[VALUE]])
cs_check_rows(nrow(d), 16, "TS2Vec")
cs_check_not_constant(x_all, VALUE)
if (UNIT == "series") {
if (is.null(SERIES)) {
cs_error("CS_E_UNDEFINED", what = "Embedding whole series", reason = "it needs a Series column with at least 3 series (pick Windows to embed stretches of one series)")
}
cs_check_groups(as.character(d[[SERIES]]), SERIES, minimum = 3)
}
names_ <- if (!is.null(SERIES)) as.character(levels(d[[SERIES]])) else VALUE
ids <- if (!is.null(SERIES)) as.integer(d[[SERIES]]) else rep(1L, nrow(d))
signals <- lapply(seq_along(names_), function(i) x_all[ids == i])
lengths_ <- vapply(signals, length, integer(1))
if (min(lengths_) < 8) {
cs_error("CS_E_UNDEFINED", what = "TS2Vec",
reason = sprintf("series %s has %d values (at least 8 are needed)", names_[which.min(lengths_)], min(lengths_)))
}
labels_by_series <- NULL
if (!is.null(LABEL) && UNIT == "series") {
labels_by_series <- character(length(names_))
bad <- 0L
for (i in seq_along(names_)) {
lv <- unique(as.character(d[[LABEL]][ids == i]))
bad <- bad + as.integer(length(lv) > 1)
labels_by_series[i] <- lv[1]
}
if (bad > 0) cs_error("CS_E_INVALID_VALUES", column = LABEL, requirement = "the same within each series", count = bad)
}
if (max(lengths_) > 2 * min(lengths_)) {
warnings <- c(warnings, sprintf("Series lengths run from %d to %d values; training crops never exceed the shortest series in a batch.", min(lengths_), max(lengths_)))
}
# %% Train
# Training options, live progress and checkpoints (twin: codesplash.deep.trainer.configure).
cs_deep_trainer_configure(list(
optimizer = "default",
lr_schedule = "none",
warmup_epochs = 0,
grad_clip = 0,
ema_decay = 0,
swa_start = 0,
history_every_step = FALSE,
profile = "parity",
checkpoint_every = NULL
), out_dir = "target/academy-parity/run-24289/discover.ts_embed/signals-probe/out-r")
fit <- cs_ts2vec_fit(signals, hidden = HIDDEN, dims = DIMS, depth = DEPTH, epochs = EPOCHS, lr = LR, batch_size = BATCH, seed = SEED)
Z <- cs_ts2vec_standardize(signals)
if (UNIT == "series") {
inst_names <- names_
segments <- Z
} else {
W <- if (!is.null(WINDOW)) as.integer(WINDOW) else as.integer(min(64L, max(8L, min(lengths_) %/% 4L)))
if (W > min(lengths_)) {
cs_error("CS_E_INVALID_OPTION", option = "Window length", allowed = sprintf("at most %d (the shortest series)", min(lengths_)), value = as.character(W))
}
S <- if (!is.null(STRIDE)) as.integer(STRIDE) else W
inst_names <- character(0); segments <- list()
for (i in seq_along(Z)) {
z <- Z[[i]]
for (s in seq(0L, length(z) - W, by = S)) {
inst_names <- c(inst_names, if (!is.null(SERIES)) sprintf("%s:%d", names_[i], s + 1L) else as.character(s + 1L))
segments[[length(segments) + 1L]] <- z[(s + 1L):(s + W)]
}
}
if (length(segments) < 3) {
cs_error("CS_E_UNDEFINED", what = "Embedding windows", reason = sprintf("only %d window(s) fit (at least 3 are needed); shorten the window or the stride", length(segments)))
}
}
E <- cs_ts2vec_encode(fit, segments)
pc <- cs_ts2vec_pca2(E)
n <- nrow(E)
values <- list(
n_instances = n, n_series = length(signals), min_length = min(lengths_), dims = DIMS, depth = DEPTH,
receptive_field = cs_ts2vec_receptive_field(DEPTH), epochs_run = fit$epochs_run, final_loss = fit$final_loss,
n_params = fit$n_params, pc_share1 = pc$shares[1], pc_share2 = pc$shares[2],
embed_check = sum(t(outer(seq_len(n), seq_len(DIMS)) * E))
)
if (UNIT == "window") {
values$window <- W
values$stride <- S
}
# %% Probe
probe_rows <- list()
if (!is.null(labels_by_series)) {
classes <- sort(unique(labels_by_series), method = "radix")
if (length(signals) >= 4 && length(classes) >= 2) {
acc <- cs_scat_probe(E, labels_by_series)
chance <- max(vapply(classes, function(cl) sum(labels_by_series == cl), integer(1))) / length(labels_by_series)
values$probe_acc <- acc
values$probe_chance <- chance
probe_rows <- list(list(features = sprintf("TS2Vec embedding (%d numbers)", DIMS), accuracy = acc),
list(features = "Always the most common class", accuracy = chance))
} else {
warnings <- c(warnings, "The probe needs at least 4 series and 2 classes; it was skipped.")
}
}
# %% Artifacts
out <- cs_ml_out_dir("target/academy-parity/run-24289/discover.ts_embed/signals-probe/out-r")
mode <- if (UNIT == "series") SERIES else "window"
fdf <- data.frame(level = inst_names, stringsAsFactors = FALSE)
for (k in seq_len(DIMS)) fdf[[sprintf("factor_%d", k)]] <- E[, k]
path <- file.path(out, sprintf("factors_%s.parquet", mode))
nanoparquet::write_parquet(fdf, path)
hist <- data.frame(epoch = vapply(fit$history, function(h) as.numeric(h$epoch), numeric(1)),
loss = vapply(fit$history, function(h) h$loss, numeric(1)))
nanoparquet::write_parquet(hist, file.path(out, "history.parquet"))
artifacts <- list(list(key = sprintf("factors_%s", mode), path = path, format = "parquet"),
list(key = "history", path = file.path(out, "history.parquet"), format = "parquet"))
# %% Charts
charts <- list(cs_chart("map", "embedding-map", "Embeddings on their first two principal components", list(
x = cs_col("Component 1", pc$scores[, 1]), y = cs_col("Component 2", pc$scores[, 2]),
label = cs_col(if (UNIT == "series") SERIES else "window", inst_names, kind = "categorical"))))
charts[[length(charts) + 1]] <- cs_chart("training", "training-components", "Hierarchical contrastive loss by epoch", list(
x = cs_col("Epoch", hist$epoch, "numeric"),
value = cs_col("Loss", hist$loss, "numeric"),
component = cs_col("Part", rep("Contrastive", nrow(hist)), "categorical")))
# %% Tables
show <- min(DIMS, 8L)
emb_cols <- c(list(list(key = "level", label = if (UNIT == "series") SERIES else "Window (series:first step)", type = "string")),
lapply(seq_len(show), function(k) list(key = sprintf("e%d", k), label = sprintf("e%d", k), type = "number")))
tables <- list(list(key = "embeddings", title = sprintf("Embeddings (first %d of %d numbers)", show, DIMS), columns = emb_cols,
rows = lapply(seq_len(min(n, 500L)), function(i) {
row <- list(level = inst_names[i])
for (k in seq_len(show)) row[[sprintf("e%d", k)]] <- E[i, k]
row
})))
if (length(probe_rows)) {
tables[[length(tables) + 1]] <- list(key = "probe", title = "Leave-one-out nearest-neighbor probe",
columns = list(list(key = "features", label = "Features", type = "string"), list(key = "accuracy", label = "Accuracy", type = "percent")),
rows = probe_rows)
}
collapse <- DIMS > 1 && pc$shares[1] > 0.9
assumptions <- list(list(
key = "collapse",
label = "The embeddings use several directions",
status = if (collapse) "warn" else "pass",
detail = paste0(sprintf("The first principal direction holds %.0f%% of the embeddings' variance", 100 * pc$shares[1]),
if (collapse) " — nearly everything lies on one line (dimensional collapse)." else ".")
))
# %% Result
what <- if (UNIT == "series") sprintf("%d series", n) else sprintf("%d windows of %d steps", n, W)
summary <- sprintf("TS2Vec embedded %s of %s as %d numbers each, after %d epochs of contrastive training.", what, VALUE, DIMS, as.integer(fit$epochs_run))
if (!is.null(values$probe_acc)) {
summary <- paste(summary, sprintf("A nearest-neighbor probe on the embeddings recovers %s for %.0f%% of the series (most common class: %.0f%%).",
LABEL, 100 * values$probe_acc, 100 * values$probe_chance))
}
notes <- c("The embeddings are learned without labels: series whose patterns look alike end up close together, whatever their level and scale (each series is standardized first).",
sprintf("Each step's representation sees about %d neighboring steps on each side; a series' embedding is the maximum over its steps, so it records which patterns occur, not when.",
cs_ts2vec_receptive_field(DEPTH)))
cs_publish(list(
title = "TS2Vec series embeddings (contrastive time-series representation)",
engine = cs_engine_info("torch", "nanoparquet"),
n = n,
summary = summary,
statistics = list(list(key = "final_loss", label = "Final contrastive loss", value = values$final_loss)),
tables = tables,
charts = charts,
values = values,
assumptions = assumptions,
warnings = warnings,
notes = notes,
artifacts = artifacts
))
TS2Vec embedded 24 series of x as 8 numbers each, after 8 epochs of contrastive training. A nearest-neighbor probe on the embeddings recovers class for 62% of the series (most common class: 50%).
- Final contrastive loss
- 2.497
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- The embeddings use several directions — The first principal direction holds 37% of the embeddings' variance.
Embeddings (first 8 of 8 numbers)
| series | e1 | e2 | e3 | e4 | e5 | e6 | e7 | e8 |
|---|---|---|---|---|---|---|---|---|
| s01 | 1.355 | 0.8915 | 0.1968 | 0.5035 | 0.5307 | 1.189 | 0.1295 | 0.3136 |
| s02 | 1.391 | 0.8583 | 0.1205 | 0.4513 | 0.4779 | 1.141 | 0.3330 | 0.2215 |
| s03 | 1.322 | 0.7592 | 0.1330 | 0.5260 | 0.4712 | 1.278 | 0.1525 | 0.2157 |
| s04 | 1.424 | 0.7538 | 0.1272 | 0.5547 | 0.4465 | 1.154 | 0.1342 | 0.2434 |
| s05 | 1.260 | 0.7658 | 0.0659 | 0.3615 | 0.5803 | 1.380 | 0.2575 | 0.2331 |
| s06 | 1.381 | 0.9242 | 0.1204 | 0.3649 | 0.4911 | 1.158 | 0.1537 | 0.3165 |
| s07 | 1.369 | 0.7521 | 0.1375 | 0.4631 | 0.4042 | 1.202 | 0.1681 | 0.2179 |
| s08 | 1.002 | 0.6941 | 0.1851 | 0.4972 | 0.5066 | 1.291 | 0.2101 | 0.2694 |
| s09 | 1.352 | 0.7812 | 0.1710 | 0.5499 | 0.5701 | 1.316 | 0.1562 | 0.2677 |
| s10 | 1.208 | 0.7354 | 0.1280 | 0.3130 | 0.5225 | 1.432 | 0.2173 | 0.2453 |
| s11 | 1.320 | 0.8090 | 0.0728 | 0.4197 | 0.4919 | 1.210 | 0.1111 | 0.3891 |
| s12 | 1.342 | 0.7956 | 0.1589 | 0.4335 | 0.4887 | 1.286 | 0.1642 | 0.2563 |
| s13 | 1.326 | 0.9750 | 0.1394 | 0.4650 | 0.5261 | 1.197 | 0.3476 | 0.3321 |
| s14 | 1.232 | 0.7201 | 0.1418 | 0.4277 | 0.5188 | 1.203 | 0.1077 | 0.2640 |
| s15 | 1.280 | 0.7304 | 0.0649 | 0.3915 | 0.5224 | 1.388 | 0.2487 | 0.2079 |
| s16 | 1.312 | 0.7454 | 0.1046 | 0.3171 | 0.4820 | 1.422 | 0.2159 | 0.2322 |
| s17 | 1.234 | 0.8455 | 0.1893 | 0.5073 | 0.6515 | 1.394 | 0.1459 | 0.3795 |
| s18 | 1.353 | 0.7491 | 0.1252 | 0.5764 | 0.4607 | 1.230 | 0.1463 | 0.2585 |
| s19 | 1.207 | 0.7049 | 0.0896 | 0.4040 | 0.5126 | 1.318 | 0.1673 | 0.3490 |
| s20 | 1.354 | 0.7607 | 0.1114 | 0.4225 | 0.5092 | 1.227 | 0.1499 | 0.2993 |
| s21 | 1.342 | 0.8689 | 0.1143 | 0.4154 | 0.5194 | 1.135 | 0.1790 | 0.3695 |
| s22 | 1.252 | 0.9211 | 0.0925 | 0.4747 | 0.4490 | 1.273 | 0.3166 | 0.3012 |
| s23 | 1.351 | 0.7629 | 0.0462 | 0.4471 | 0.5765 | 1.352 | 0.1417 | 0.3761 |
| s24 | 1.315 | 0.7042 | 0.1600 | 0.5681 | 0.5231 | 1.449 | 0.1397 | 0.3353 |
Leave-one-out nearest-neighbor probe
| Features | Accuracy |
|---|---|
| TS2Vec embedding (8 numbers) | 62.5% |
| Always the most common class | 50.0% |
- The embeddings are learned without labels: series whose patterns look alike end up close together, whatever their level and scale (each series is standardized first).
- Each step's representation sees about 30 neighboring steps on each side; a series' embedding is the maximum over its steps, so it records which patterns occur, not when.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# TS2Vec series embeddings (contrastive time-series representation)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.ts_embed 1.0.0 · spec a0b2ac8234063cc1
# Dataset: seq_signals (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import math
import os
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash import ml as csml
from codesplash.errors import check_groups, check_not_constant
from codesplash.deep import ts2vec # twin of codesplashr::cs_ts2vec_* (torch, shared initial weights and crops)
from codesplash.ml import forecast as fc
from codesplash.stats import scattering as sc
# %% Data
df = pd.read_parquet("tests/parity/fixtures/seq_signals.parquet", columns=["x", "series", "step", "class"])
n_input = len(df)
df["series"] = pd.Categorical(df["series"], categories=["s01", "s02", "s03", "s04", "s05", "s06", "s07", "s08", "s09", "s10", "s11", "s12", "s13", "s14", "s15", "s16", "s17", "s18", "s19", "s20", "s21", "s22", "s23", "s24"]) # stored level order
df["class"] = pd.Categorical(df["class"], categories=["fast", "slow"]) # stored level order
df = df.dropna(subset=["x", "series", "step", "class"]) # listwise deletion over the analysis columns
df["series"] = df["series"].cat.remove_unused_categories()
df["class"] = df["class"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["x", "series", "step", "class"]) # infinite values stop the run (registry/errors.yaml)
# %% Series
# TS2Vec (Yue et al. 2022): a dilated-convolution encoder trained with the hierarchical contrastive loss on random
# overlapping crops (contextual consistency); each series (or window of one) is embedded by max-pooling its steps.
VALUE = "x"
SERIES = "series"
TIME = "step"
LABEL = "class"
UNIT = "series" # series | window
WINDOW = None
STRIDE = None
DIMS = int(8)
HIDDEN = int(8)
DEPTH = int(3)
EPOCHS = int(8)
LR = float(0.001)
BATCH = int(8)
SEED = 42
keys = ([SERIES] if SERIES else []) + ([TIME] if TIME else [])
d = df.sort_values(keys, kind="mergesort").reset_index(drop=True) if keys else df.reset_index(drop=True)
x_all = d[VALUE].to_numpy(dtype=float)
cs.check_rows(len(d), 16, "TS2Vec")
check_not_constant(x_all, VALUE)
if UNIT == "series":
if not SERIES:
cs.cs_error("CS_E_UNDEFINED", what="Embedding whole series", reason="it needs a Series column with at least 3 series (pick Windows to embed stretches of one series)")
check_groups(d[SERIES].astype(str), SERIES, minimum=3)
names = [str(v) for v in d[SERIES].cat.categories] if SERIES else [VALUE]
ids = d[SERIES].cat.codes.to_numpy() if SERIES else np.zeros(len(d), dtype=np.int64)
signals = [[float(v) for v in x_all[ids == i]] for i in range(len(names))]
lengths = [len(s) for s in signals]
if min(lengths) < 8:
short = names[int(np.argmin(lengths))]
cs.cs_error("CS_E_UNDEFINED", what="TS2Vec", reason=f"series {short} has {min(lengths)} values (at least 8 are needed)")
labels_by_series = None
if LABEL and UNIT == "series":
labels_by_series = []
bad = 0
for i in range(len(names)):
lv = d[LABEL][ids == i].astype(str).unique()
bad += int(len(lv) > 1)
labels_by_series.append(str(lv[0]))
if bad:
cs.cs_error("CS_E_INVALID_VALUES", column=LABEL, requirement="the same within each series", count=bad)
if max(lengths) > 2 * min(lengths):
warnings.append(f"Series lengths run from {min(lengths)} to {max(lengths)} values; training crops never exceed the shortest series in a batch.")
# %% Train
from codesplash.deep import trainer as deep_trainer # training options, live progress, checkpoints (twin: cs_deep_trainer_*)
deep_trainer.configure(
{
"optimizer": "default",
"lr_schedule": "none",
"warmup_epochs": 0,
"grad_clip": 0,
"ema_decay": 0,
"swa_start": 0,
"history_every_step": False,
"profile": "parity",
"checkpoint_every": None,
},
out_dir="target/academy-parity/run-24289/discover.ts_embed/signals-probe/out-python",
)
fit = ts2vec.fit(signals, hidden=HIDDEN, dims=DIMS, depth=DEPTH, epochs=EPOCHS, lr=LR, batch_size=BATCH, seed=SEED)
Z = ts2vec.standardize(signals)
if UNIT == "series":
inst_names = names
segments = Z
else:
W = int(WINDOW) if WINDOW else min(64, max(8, min(lengths) // 4))
if W > min(lengths):
cs.cs_error("CS_E_INVALID_OPTION", option="Window length", allowed=f"at most {min(lengths)} (the shortest series)", value=str(W))
S = int(STRIDE) if STRIDE else W
inst_names, segments = [], []
for i, z in enumerate(Z):
for s in range(0, len(z) - W + 1, S):
inst_names.append(f"{names[i]}:{s + 1}" if SERIES else str(s + 1))
segments.append(z[s : s + W])
if len(segments) < 3:
cs.cs_error("CS_E_UNDEFINED", what="Embedding windows", reason=f"only {len(segments)} window(s) fit (at least 3 are needed); shorten the window or the stride")
E = ts2vec.encode(fit, segments)
P2, shares = ts2vec.pca2(E)
n = E.shape[0]
values = {
"n_instances": n,
"n_series": len(signals),
"min_length": min(lengths),
"dims": DIMS,
"depth": DEPTH,
"receptive_field": ts2vec.receptive_field(DEPTH),
"epochs_run": fit["epochs_run"],
"final_loss": fit["final_loss"],
"n_params": fit["n_params"],
"pc_share1": shares[0],
"pc_share2": shares[1],
"embed_check": fc._sum([(i + 1) * (k + 1) * float(E[i, k]) for i in range(n) for k in range(DIMS)]),
}
if UNIT == "window":
values["window"] = W
values["stride"] = S
# %% Probe
probe_rows = []
if labels_by_series is not None:
classes = sorted(set(labels_by_series))
if len(signals) >= 4 and len(classes) >= 2:
acc = sc.probe(E, labels_by_series)
chance = max(labels_by_series.count(c) for c in classes) / len(labels_by_series)
values.update({"probe_acc": acc, "probe_chance": chance})
probe_rows = [{"features": f"TS2Vec embedding ({DIMS} numbers)", "accuracy": acc}, {"features": "Always the most common class", "accuracy": chance}]
else:
warnings.append("The probe needs at least 4 series and 2 classes; it was skipped.")
# %% Artifacts
out = csml.out_dir("target/academy-parity/run-24289/discover.ts_embed/signals-probe/out-python")
mode = SERIES if UNIT == "series" else "window"
fdf = pd.DataFrame({"level": inst_names})
for k in range(DIMS):
fdf[f"factor_{k + 1}"] = E[:, k]
path = os.path.join(out, f"factors_{mode}.parquet")
fdf.to_parquet(path, index=False)
history = pd.DataFrame({"epoch": [h["epoch"] for h in fit["history"]], "loss": [h["loss"] for h in fit["history"]]})
history.to_parquet(os.path.join(out, "history.parquet"), index=False)
artifacts = [{"key": f"factors_{mode}", "path": path, "format": "parquet"},
{"key": "history", "path": os.path.join(out, "history.parquet"), "format": "parquet"}]
# %% Charts
roles_map = {"x": cs.col("Component 1", P2[:, 0]), "y": cs.col("Component 2", P2[:, 1]),
"label": cs.col(SERIES if UNIT == "series" else "window", inst_names, kind="categorical")}
charts = [cs.chart("map", "embedding-map", "Embeddings on their first two principal components", roles_map)]
ep = [h["epoch"] for h in fit["history"]]
charts.append(cs.chart("training", "training-components", "Hierarchical contrastive loss by epoch", {
"x": cs.col("Epoch", ep, "numeric"),
"value": cs.col("Loss", [h["loss"] for h in fit["history"]], "numeric"),
"component": cs.col("Part", ["Contrastive"] * len(ep), "categorical"),
}))
# %% Tables
show = min(DIMS, 8)
tables = [{"key": "embeddings", "title": f"Embeddings (first {show} of {DIMS} numbers)",
"columns": [{"key": "level", "label": SERIES if UNIT == "series" else "Window (series:first step)", "type": "string"}]
+ [{"key": f"e{k + 1}", "label": f"e{k + 1}", "type": "number"} for k in range(show)],
"rows": [{"level": inst_names[i], **{f"e{k + 1}": float(E[i, k]) for k in range(show)}} for i in range(min(n, 500))]}]
if probe_rows:
tables.append({"key": "probe", "title": "Leave-one-out nearest-neighbor probe",
"columns": [{"key": "features", "label": "Features", "type": "string"}, {"key": "accuracy", "label": "Accuracy", "type": "percent"}],
"rows": probe_rows})
assumptions = [{
"key": "collapse",
"label": "The embeddings use several directions",
"status": "warn" if (DIMS > 1 and shares[0] > 0.9) else "pass",
"detail": f"The first principal direction holds {shares[0]:.0%} of the embeddings' variance"
+ (" — nearly everything lies on one line (dimensional collapse)." if DIMS > 1 and shares[0] > 0.9 else "."),
}]
# %% Result
what = f"{n} series" if UNIT == "series" else f"{n} windows of {W} steps"
summary = f"TS2Vec embedded {what} of {VALUE} as {DIMS} numbers each, after {fit['epochs_run']} epochs of contrastive training."
if "probe_acc" in values:
summary += f" A nearest-neighbor probe on the embeddings recovers {LABEL} for {values['probe_acc']:.0%} of the series (most common class: {values['probe_chance']:.0%})."
notes = ["The embeddings are learned without labels: series whose patterns look alike end up close together, whatever their level and scale (each series is standardized first).",
f"Each step's representation sees about {ts2vec.receptive_field(DEPTH)} neighboring steps on each side; a series' embedding is the maximum over its steps, so it records which patterns occur, not when."]
cs.publish({
"title": "TS2Vec series embeddings (contrastive time-series representation)",
"engine": cs.engine_info("torch", "numpy", "pandas"),
"n": n,
"summary": summary,
"statistics": [{"key": "final_loss", "label": "Final contrastive loss", "value": values["final_loss"]}],
"tables": tables,
"charts": charts,
"values": values,
"assumptions": assumptions,
"warnings": warnings,
"notes": notes,
"artifacts": artifacts,
})
Each of the 24 signals became 8 numbers. The encoder stacks dilated convolutions, so each step's representation sees about 30 neighboring steps on each side. A series' embedding is the maximum over its steps. It records which patterns occur, not when.
The probe hides each signal's class and guesses it from its nearest neighbor in embedding space. It scored 62.5%, against 50.0% for always guessing the most common class. The embeddings never saw the classes, so a gap like that means similar patterns really did end up close together.
How sure is the probe?
PredictPredict first
The probe reaches 75% on 8 series with two classes of 4 each. What does that tell you?
Reveal
Weak evidence. With 8 series each hit moves the accuracy by an eighth, and always guessing one class already scores half. Look for a larger gap or more series.
Windows of one long series
ReadTS2Vec embedded 5 windows of 20 steps of flow as 4 numbers each, after 10 epochs of contrastive training.
- Final contrastive loss
- 1.272
Plots
View data
| window | Component 1 | Component 2 |
|---|---|---|
| 1 | 1.169 | −0.0418 |
| 21 | 0.4631 | 0.0739 |
| 41 | −0.5937 | 0.3963 |
| 61 | −0.8672 | −0.2537 |
| 81 | −0.1716 | −0.1747 |
View data
| Part | Loss | Epoch |
|---|---|---|
| Contrastive | 0.9189 | 1 |
| Contrastive | 1.236 | 2 |
| Contrastive | 0.6810 | 3 |
| Contrastive | 1.151 | 4 |
| Contrastive | 0.7311 | 5 |
| Contrastive | 0.9721 | 6 |
| Contrastive | 1.257 | 7 |
| Contrastive | 1.394 | 8 |
| Contrastive | 1.305 | 9 |
| Contrastive | 1.272 | 10 |
Assumptions
- The embeddings use several directions — The first principal direction holds 91% of the embeddings' variance — nearly everything lies on one line (dimensional collapse).
Embeddings (first 4 of 4 numbers)
| Window (series:first step) | e1 | e2 | e3 | e4 |
|---|---|---|---|---|
| 1 | 2.148 | 1.162 | 0.2266 | 0.3192 |
| 21 | 1.522 | 0.9654 | 0.3864 | 0.6003 |
| 41 | 0.7934 | 0.4070 | 0.5774 | 1.198 |
| 61 | 0.3925 | 0.1891 | 0.3964 | 0.6899 |
| 81 | 1.003 | 0.5101 | 0.4105 | 0.5467 |
- The embeddings are learned without labels: series whose patterns look alike end up close together, whatever their level and scale (each series is standardized first).
- Each step's representation sees about 14 neighboring steps on each side; a series' embedding is the maximum over its steps, so it records which patterns occur, not when.
The exact R script · R R version 4.5.1 (2025-06-13)
# TS2Vec series embeddings (contrastive time-series representation)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.ts_embed 1.0.0 · spec 2287a144d0685dea
# Dataset: ml_nile (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_nile.parquet", col_select = c("flow", "year")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("flow", "year")]), , drop = FALSE] # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("flow", "year")) # infinite values stop the run (registry/errors.yaml)
# %% Series
# TS2Vec (Yue et al. 2022): a dilated-convolution encoder trained with the hierarchical contrastive loss on random
# overlapping crops (contextual consistency); each series (or window of one) is embedded by max-pooling its steps.
VALUE <- "flow"
SERIES <- NULL
TIME <- "year"
LABEL <- NULL
UNIT <- "window" # series | window
WINDOW <- 20
STRIDE <- NULL
DIMS <- as.integer(4)
HIDDEN <- as.integer(4)
DEPTH <- as.integer(2)
EPOCHS <- as.integer(10)
LR <- as.numeric(0.005)
BATCH <- as.integer(8)
SEED <- 42
d <- df
if (!is.null(SERIES) && !is.null(TIME)) {
d <- d[order(as.integer(d[[SERIES]]), d[[TIME]], method = "radix"), , drop = FALSE]
} else if (!is.null(SERIES)) {
d <- d[order(as.integer(d[[SERIES]]), method = "radix"), , drop = FALSE]
} else if (!is.null(TIME)) {
d <- d[order(d[[TIME]], method = "radix"), , drop = FALSE]
}
rownames(d) <- NULL
x_all <- as.numeric(d[[VALUE]])
cs_check_rows(nrow(d), 16, "TS2Vec")
cs_check_not_constant(x_all, VALUE)
if (UNIT == "series") {
if (is.null(SERIES)) {
cs_error("CS_E_UNDEFINED", what = "Embedding whole series", reason = "it needs a Series column with at least 3 series (pick Windows to embed stretches of one series)")
}
cs_check_groups(as.character(d[[SERIES]]), SERIES, minimum = 3)
}
names_ <- if (!is.null(SERIES)) as.character(levels(d[[SERIES]])) else VALUE
ids <- if (!is.null(SERIES)) as.integer(d[[SERIES]]) else rep(1L, nrow(d))
signals <- lapply(seq_along(names_), function(i) x_all[ids == i])
lengths_ <- vapply(signals, length, integer(1))
if (min(lengths_) < 8) {
cs_error("CS_E_UNDEFINED", what = "TS2Vec",
reason = sprintf("series %s has %d values (at least 8 are needed)", names_[which.min(lengths_)], min(lengths_)))
}
labels_by_series <- NULL
if (!is.null(LABEL) && UNIT == "series") {
labels_by_series <- character(length(names_))
bad <- 0L
for (i in seq_along(names_)) {
lv <- unique(as.character(d[[LABEL]][ids == i]))
bad <- bad + as.integer(length(lv) > 1)
labels_by_series[i] <- lv[1]
}
if (bad > 0) cs_error("CS_E_INVALID_VALUES", column = LABEL, requirement = "the same within each series", count = bad)
}
if (max(lengths_) > 2 * min(lengths_)) {
warnings <- c(warnings, sprintf("Series lengths run from %d to %d values; training crops never exceed the shortest series in a batch.", min(lengths_), max(lengths_)))
}
# %% Train
# Training options, live progress and checkpoints (twin: codesplash.deep.trainer.configure).
cs_deep_trainer_configure(list(
optimizer = "default",
lr_schedule = "none",
warmup_epochs = 0,
grad_clip = 0,
ema_decay = 0,
swa_start = 0,
history_every_step = FALSE,
profile = "parity",
checkpoint_every = NULL
), out_dir = "target/academy-parity/run-24289/discover.ts_embed/nile-one-series-windows/out-r")
fit <- cs_ts2vec_fit(signals, hidden = HIDDEN, dims = DIMS, depth = DEPTH, epochs = EPOCHS, lr = LR, batch_size = BATCH, seed = SEED)
Z <- cs_ts2vec_standardize(signals)
if (UNIT == "series") {
inst_names <- names_
segments <- Z
} else {
W <- if (!is.null(WINDOW)) as.integer(WINDOW) else as.integer(min(64L, max(8L, min(lengths_) %/% 4L)))
if (W > min(lengths_)) {
cs_error("CS_E_INVALID_OPTION", option = "Window length", allowed = sprintf("at most %d (the shortest series)", min(lengths_)), value = as.character(W))
}
S <- if (!is.null(STRIDE)) as.integer(STRIDE) else W
inst_names <- character(0); segments <- list()
for (i in seq_along(Z)) {
z <- Z[[i]]
for (s in seq(0L, length(z) - W, by = S)) {
inst_names <- c(inst_names, if (!is.null(SERIES)) sprintf("%s:%d", names_[i], s + 1L) else as.character(s + 1L))
segments[[length(segments) + 1L]] <- z[(s + 1L):(s + W)]
}
}
if (length(segments) < 3) {
cs_error("CS_E_UNDEFINED", what = "Embedding windows", reason = sprintf("only %d window(s) fit (at least 3 are needed); shorten the window or the stride", length(segments)))
}
}
E <- cs_ts2vec_encode(fit, segments)
pc <- cs_ts2vec_pca2(E)
n <- nrow(E)
values <- list(
n_instances = n, n_series = length(signals), min_length = min(lengths_), dims = DIMS, depth = DEPTH,
receptive_field = cs_ts2vec_receptive_field(DEPTH), epochs_run = fit$epochs_run, final_loss = fit$final_loss,
n_params = fit$n_params, pc_share1 = pc$shares[1], pc_share2 = pc$shares[2],
embed_check = sum(t(outer(seq_len(n), seq_len(DIMS)) * E))
)
if (UNIT == "window") {
values$window <- W
values$stride <- S
}
# %% Probe
probe_rows <- list()
if (!is.null(labels_by_series)) {
classes <- sort(unique(labels_by_series), method = "radix")
if (length(signals) >= 4 && length(classes) >= 2) {
acc <- cs_scat_probe(E, labels_by_series)
chance <- max(vapply(classes, function(cl) sum(labels_by_series == cl), integer(1))) / length(labels_by_series)
values$probe_acc <- acc
values$probe_chance <- chance
probe_rows <- list(list(features = sprintf("TS2Vec embedding (%d numbers)", DIMS), accuracy = acc),
list(features = "Always the most common class", accuracy = chance))
} else {
warnings <- c(warnings, "The probe needs at least 4 series and 2 classes; it was skipped.")
}
}
# %% Artifacts
out <- cs_ml_out_dir("target/academy-parity/run-24289/discover.ts_embed/nile-one-series-windows/out-r")
mode <- if (UNIT == "series") SERIES else "window"
fdf <- data.frame(level = inst_names, stringsAsFactors = FALSE)
for (k in seq_len(DIMS)) fdf[[sprintf("factor_%d", k)]] <- E[, k]
path <- file.path(out, sprintf("factors_%s.parquet", mode))
nanoparquet::write_parquet(fdf, path)
hist <- data.frame(epoch = vapply(fit$history, function(h) as.numeric(h$epoch), numeric(1)),
loss = vapply(fit$history, function(h) h$loss, numeric(1)))
nanoparquet::write_parquet(hist, file.path(out, "history.parquet"))
artifacts <- list(list(key = sprintf("factors_%s", mode), path = path, format = "parquet"),
list(key = "history", path = file.path(out, "history.parquet"), format = "parquet"))
# %% Charts
charts <- list(cs_chart("map", "embedding-map", "Embeddings on their first two principal components", list(
x = cs_col("Component 1", pc$scores[, 1]), y = cs_col("Component 2", pc$scores[, 2]),
label = cs_col(if (UNIT == "series") SERIES else "window", inst_names, kind = "categorical"))))
charts[[length(charts) + 1]] <- cs_chart("training", "training-components", "Hierarchical contrastive loss by epoch", list(
x = cs_col("Epoch", hist$epoch, "numeric"),
value = cs_col("Loss", hist$loss, "numeric"),
component = cs_col("Part", rep("Contrastive", nrow(hist)), "categorical")))
# %% Tables
show <- min(DIMS, 8L)
emb_cols <- c(list(list(key = "level", label = if (UNIT == "series") SERIES else "Window (series:first step)", type = "string")),
lapply(seq_len(show), function(k) list(key = sprintf("e%d", k), label = sprintf("e%d", k), type = "number")))
tables <- list(list(key = "embeddings", title = sprintf("Embeddings (first %d of %d numbers)", show, DIMS), columns = emb_cols,
rows = lapply(seq_len(min(n, 500L)), function(i) {
row <- list(level = inst_names[i])
for (k in seq_len(show)) row[[sprintf("e%d", k)]] <- E[i, k]
row
})))
if (length(probe_rows)) {
tables[[length(tables) + 1]] <- list(key = "probe", title = "Leave-one-out nearest-neighbor probe",
columns = list(list(key = "features", label = "Features", type = "string"), list(key = "accuracy", label = "Accuracy", type = "percent")),
rows = probe_rows)
}
collapse <- DIMS > 1 && pc$shares[1] > 0.9
assumptions <- list(list(
key = "collapse",
label = "The embeddings use several directions",
status = if (collapse) "warn" else "pass",
detail = paste0(sprintf("The first principal direction holds %.0f%% of the embeddings' variance", 100 * pc$shares[1]),
if (collapse) " — nearly everything lies on one line (dimensional collapse)." else ".")
))
# %% Result
what <- if (UNIT == "series") sprintf("%d series", n) else sprintf("%d windows of %d steps", n, W)
summary <- sprintf("TS2Vec embedded %s of %s as %d numbers each, after %d epochs of contrastive training.", what, VALUE, DIMS, as.integer(fit$epochs_run))
if (!is.null(values$probe_acc)) {
summary <- paste(summary, sprintf("A nearest-neighbor probe on the embeddings recovers %s for %.0f%% of the series (most common class: %.0f%%).",
LABEL, 100 * values$probe_acc, 100 * values$probe_chance))
}
notes <- c("The embeddings are learned without labels: series whose patterns look alike end up close together, whatever their level and scale (each series is standardized first).",
sprintf("Each step's representation sees about %d neighboring steps on each side; a series' embedding is the maximum over its steps, so it records which patterns occur, not when.",
cs_ts2vec_receptive_field(DEPTH)))
cs_publish(list(
title = "TS2Vec series embeddings (contrastive time-series representation)",
engine = cs_engine_info("torch", "nanoparquet"),
n = n,
summary = summary,
statistics = list(list(key = "final_loss", label = "Final contrastive loss", value = values$final_loss)),
tables = tables,
charts = charts,
values = values,
assumptions = assumptions,
warnings = warnings,
notes = notes,
artifacts = artifacts
))
TS2Vec embedded 5 windows of 20 steps of flow as 4 numbers each, after 10 epochs of contrastive training.
- Final contrastive loss
- 1.272
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- The embeddings use several directions — The first principal direction holds 91% of the embeddings' variance — nearly everything lies on one line (dimensional collapse).
Embeddings (first 4 of 4 numbers)
| Window (series:first step) | e1 | e2 | e3 | e4 |
|---|---|---|---|---|
| 1 | 2.148 | 1.162 | 0.2266 | 0.3192 |
| 21 | 1.522 | 0.9654 | 0.3864 | 0.6003 |
| 41 | 0.7934 | 0.4070 | 0.5774 | 1.198 |
| 61 | 0.3925 | 0.1891 | 0.3964 | 0.6899 |
| 81 | 1.003 | 0.5101 | 0.4105 | 0.5467 |
- The embeddings are learned without labels: series whose patterns look alike end up close together, whatever their level and scale (each series is standardized first).
- Each step's representation sees about 14 neighboring steps on each side; a series' embedding is the maximum over its steps, so it records which patterns occur, not when.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# TS2Vec series embeddings (contrastive time-series representation)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.ts_embed 1.0.0 · spec 2287a144d0685dea
# Dataset: ml_nile (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import math
import os
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash import ml as csml
from codesplash.errors import check_groups, check_not_constant
from codesplash.deep import ts2vec # twin of codesplashr::cs_ts2vec_* (torch, shared initial weights and crops)
from codesplash.ml import forecast as fc
from codesplash.stats import scattering as sc
# %% Data
df = pd.read_parquet("tests/parity/fixtures/ml_nile.parquet", columns=["flow", "year"])
n_input = len(df)
df = df.dropna(subset=["flow", "year"]) # listwise deletion over the analysis columns
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["flow", "year"]) # infinite values stop the run (registry/errors.yaml)
# %% Series
# TS2Vec (Yue et al. 2022): a dilated-convolution encoder trained with the hierarchical contrastive loss on random
# overlapping crops (contextual consistency); each series (or window of one) is embedded by max-pooling its steps.
VALUE = "flow"
SERIES = None
TIME = "year"
LABEL = None
UNIT = "window" # series | window
WINDOW = 20
STRIDE = None
DIMS = int(4)
HIDDEN = int(4)
DEPTH = int(2)
EPOCHS = int(10)
LR = float(0.005)
BATCH = int(8)
SEED = 42
keys = ([SERIES] if SERIES else []) + ([TIME] if TIME else [])
d = df.sort_values(keys, kind="mergesort").reset_index(drop=True) if keys else df.reset_index(drop=True)
x_all = d[VALUE].to_numpy(dtype=float)
cs.check_rows(len(d), 16, "TS2Vec")
check_not_constant(x_all, VALUE)
if UNIT == "series":
if not SERIES:
cs.cs_error("CS_E_UNDEFINED", what="Embedding whole series", reason="it needs a Series column with at least 3 series (pick Windows to embed stretches of one series)")
check_groups(d[SERIES].astype(str), SERIES, minimum=3)
names = [str(v) for v in d[SERIES].cat.categories] if SERIES else [VALUE]
ids = d[SERIES].cat.codes.to_numpy() if SERIES else np.zeros(len(d), dtype=np.int64)
signals = [[float(v) for v in x_all[ids == i]] for i in range(len(names))]
lengths = [len(s) for s in signals]
if min(lengths) < 8:
short = names[int(np.argmin(lengths))]
cs.cs_error("CS_E_UNDEFINED", what="TS2Vec", reason=f"series {short} has {min(lengths)} values (at least 8 are needed)")
labels_by_series = None
if LABEL and UNIT == "series":
labels_by_series = []
bad = 0
for i in range(len(names)):
lv = d[LABEL][ids == i].astype(str).unique()
bad += int(len(lv) > 1)
labels_by_series.append(str(lv[0]))
if bad:
cs.cs_error("CS_E_INVALID_VALUES", column=LABEL, requirement="the same within each series", count=bad)
if max(lengths) > 2 * min(lengths):
warnings.append(f"Series lengths run from {min(lengths)} to {max(lengths)} values; training crops never exceed the shortest series in a batch.")
# %% Train
from codesplash.deep import trainer as deep_trainer # training options, live progress, checkpoints (twin: cs_deep_trainer_*)
deep_trainer.configure(
{
"optimizer": "default",
"lr_schedule": "none",
"warmup_epochs": 0,
"grad_clip": 0,
"ema_decay": 0,
"swa_start": 0,
"history_every_step": False,
"profile": "parity",
"checkpoint_every": None,
},
out_dir="target/academy-parity/run-24289/discover.ts_embed/nile-one-series-windows/out-python",
)
fit = ts2vec.fit(signals, hidden=HIDDEN, dims=DIMS, depth=DEPTH, epochs=EPOCHS, lr=LR, batch_size=BATCH, seed=SEED)
Z = ts2vec.standardize(signals)
if UNIT == "series":
inst_names = names
segments = Z
else:
W = int(WINDOW) if WINDOW else min(64, max(8, min(lengths) // 4))
if W > min(lengths):
cs.cs_error("CS_E_INVALID_OPTION", option="Window length", allowed=f"at most {min(lengths)} (the shortest series)", value=str(W))
S = int(STRIDE) if STRIDE else W
inst_names, segments = [], []
for i, z in enumerate(Z):
for s in range(0, len(z) - W + 1, S):
inst_names.append(f"{names[i]}:{s + 1}" if SERIES else str(s + 1))
segments.append(z[s : s + W])
if len(segments) < 3:
cs.cs_error("CS_E_UNDEFINED", what="Embedding windows", reason=f"only {len(segments)} window(s) fit (at least 3 are needed); shorten the window or the stride")
E = ts2vec.encode(fit, segments)
P2, shares = ts2vec.pca2(E)
n = E.shape[0]
values = {
"n_instances": n,
"n_series": len(signals),
"min_length": min(lengths),
"dims": DIMS,
"depth": DEPTH,
"receptive_field": ts2vec.receptive_field(DEPTH),
"epochs_run": fit["epochs_run"],
"final_loss": fit["final_loss"],
"n_params": fit["n_params"],
"pc_share1": shares[0],
"pc_share2": shares[1],
"embed_check": fc._sum([(i + 1) * (k + 1) * float(E[i, k]) for i in range(n) for k in range(DIMS)]),
}
if UNIT == "window":
values["window"] = W
values["stride"] = S
# %% Probe
probe_rows = []
if labels_by_series is not None:
classes = sorted(set(labels_by_series))
if len(signals) >= 4 and len(classes) >= 2:
acc = sc.probe(E, labels_by_series)
chance = max(labels_by_series.count(c) for c in classes) / len(labels_by_series)
values.update({"probe_acc": acc, "probe_chance": chance})
probe_rows = [{"features": f"TS2Vec embedding ({DIMS} numbers)", "accuracy": acc}, {"features": "Always the most common class", "accuracy": chance}]
else:
warnings.append("The probe needs at least 4 series and 2 classes; it was skipped.")
# %% Artifacts
out = csml.out_dir("target/academy-parity/run-24289/discover.ts_embed/nile-one-series-windows/out-python")
mode = SERIES if UNIT == "series" else "window"
fdf = pd.DataFrame({"level": inst_names})
for k in range(DIMS):
fdf[f"factor_{k + 1}"] = E[:, k]
path = os.path.join(out, f"factors_{mode}.parquet")
fdf.to_parquet(path, index=False)
history = pd.DataFrame({"epoch": [h["epoch"] for h in fit["history"]], "loss": [h["loss"] for h in fit["history"]]})
history.to_parquet(os.path.join(out, "history.parquet"), index=False)
artifacts = [{"key": f"factors_{mode}", "path": path, "format": "parquet"},
{"key": "history", "path": os.path.join(out, "history.parquet"), "format": "parquet"}]
# %% Charts
roles_map = {"x": cs.col("Component 1", P2[:, 0]), "y": cs.col("Component 2", P2[:, 1]),
"label": cs.col(SERIES if UNIT == "series" else "window", inst_names, kind="categorical")}
charts = [cs.chart("map", "embedding-map", "Embeddings on their first two principal components", roles_map)]
ep = [h["epoch"] for h in fit["history"]]
charts.append(cs.chart("training", "training-components", "Hierarchical contrastive loss by epoch", {
"x": cs.col("Epoch", ep, "numeric"),
"value": cs.col("Loss", [h["loss"] for h in fit["history"]], "numeric"),
"component": cs.col("Part", ["Contrastive"] * len(ep), "categorical"),
}))
# %% Tables
show = min(DIMS, 8)
tables = [{"key": "embeddings", "title": f"Embeddings (first {show} of {DIMS} numbers)",
"columns": [{"key": "level", "label": SERIES if UNIT == "series" else "Window (series:first step)", "type": "string"}]
+ [{"key": f"e{k + 1}", "label": f"e{k + 1}", "type": "number"} for k in range(show)],
"rows": [{"level": inst_names[i], **{f"e{k + 1}": float(E[i, k]) for k in range(show)}} for i in range(min(n, 500))]}]
if probe_rows:
tables.append({"key": "probe", "title": "Leave-one-out nearest-neighbor probe",
"columns": [{"key": "features", "label": "Features", "type": "string"}, {"key": "accuracy", "label": "Accuracy", "type": "percent"}],
"rows": probe_rows})
assumptions = [{
"key": "collapse",
"label": "The embeddings use several directions",
"status": "warn" if (DIMS > 1 and shares[0] > 0.9) else "pass",
"detail": f"The first principal direction holds {shares[0]:.0%} of the embeddings' variance"
+ (" — nearly everything lies on one line (dimensional collapse)." if DIMS > 1 and shares[0] > 0.9 else "."),
}]
# %% Result
what = f"{n} series" if UNIT == "series" else f"{n} windows of {W} steps"
summary = f"TS2Vec embedded {what} of {VALUE} as {DIMS} numbers each, after {fit['epochs_run']} epochs of contrastive training."
if "probe_acc" in values:
summary += f" A nearest-neighbor probe on the embeddings recovers {LABEL} for {values['probe_acc']:.0%} of the series (most common class: {values['probe_chance']:.0%})."
notes = ["The embeddings are learned without labels: series whose patterns look alike end up close together, whatever their level and scale (each series is standardized first).",
f"Each step's representation sees about {ts2vec.receptive_field(DEPTH)} neighboring steps on each side; a series' embedding is the maximum over its steps, so it records which patterns occur, not when."]
cs.publish({
"title": "TS2Vec series embeddings (contrastive time-series representation)",
"engine": cs.engine_info("torch", "numpy", "pandas"),
"n": n,
"summary": summary,
"statistics": [{"key": "final_loss", "label": "Final contrastive loss", "value": values["final_loss"]}],
"tables": tables,
"charts": charts,
"values": values,
"assumptions": assumptions,
"warnings": warnings,
"notes": notes,
"artifacts": artifacts,
})
With Embed: Windows, every stretch of a series gets its own embedding, so even one long series works. Here the Nile's yearly flow was cut into 5 windows of 20 years. Windows close together on the map behaved alike. Save the embeddings as a dataset and cluster them, or look for windows far from the rest.
Reading the map, and collapse
ReadThe map shows the embeddings on their first two principal directions. If the first direction holds nearly all the variance, the encoder has squeezed everything onto a line (dimensional collapseDimensional collapseA learned representation that uses only one or a few directions, so most of its coordinates repeat the same information.); the result then warns and suggests wavelet scattering. Each series is standardized first, so a series and the same series doubled get the same embedding: TS2Vec compares shapes, not levels.
Check: TS2Vec
CheckpointCheck yourself
What does TS2Vec need to learn its embeddings?
Show the answer
Answer: a
TS2Vec is self-supervised: the crops of each series supply the training signal. The class column is only used afterwards, by the probe.
Check yourself
You have one long sensor recording and want to find stretches that behaved alike. Which setting fits?
Show the answer
Answer: a
Whole-series embeddings need several series; windows give one embedding per stretch of a single series.
Check yourself
Two machines produce the same vibration pattern, but one reads ten times higher. How close are their embeddings?
Show the answer
Answer: a
Standardizing each series removes level and scale, so TS2Vec compares the patterns themselves.
Concepts in this lesson