Learning series representations: TS2Vec
TS2Vec learns a vector for every time step without labels, by matching the same moment in two cropped views at several time scales. Score an aligned contrastive loss by hand and see what the vectors are good for.
What runs in CodeSplash
- SPE020TS2Vec Runs in CodeSplash (Experimental)
- TS2Vec series embeddings (contrastive time-series representation) Experimental
You will be able to
- Explain TS2Vec's positive pairs and its two contrastive losses
- Compute an aligned temporal contrastive loss and one coarse pooling level
- Say how overlapping windows and non-causal encoders can leak into later evaluation
- Evaluate embeddings with a separate downstream task
Labels are scarce, series are not
ReadMachines, sensors and patients produce long series, and labels for them are rare. TS2VecTS2VecA convolutional encoder trained without labels so overlapping crops of a series get the same representation. learns a vector for every time step from the series alone, by contrastive learningContrastive learningLearning representations without labels by pulling two views of the same row together and pushing other rows' views away.. Those vectors can then feed clustering, anomaly scores, a small classifier or a forecaster, each evaluated on its own task.
Its encoder is a stack of dilated convolutionsDilated convolution encoderStacked convolutions whose spacing doubles each block, so each step's representation sees exponentially more neighbors., so each time step's vector sees a window of neighbors whose width doubles with depth.
Reference · SPE020 · Runs in CodeSplashTS2VecTS2Vec learns contextual representations at individual timestamps and larger temporal scales through hierarchical contrastive learning.Two views, same moment
ReadTS2Vec takes two overlapping random crops of a series and encodes both. The same timestamp in the two crops is a positive pair: its two vectors should match. The hierarchical contrastive lossHierarchical contrastive lossContrasts each series with the others and each time step with the other steps, then repeats after halving the time resolution. pushes them together against two kinds of negatives:
- temporal: other timestamps of the same series;
- instance: the same timestamp in other series of the batch.
Then it max-pools the vectors over time and repeats, so the loss also acts at coarser scales:
The contrastive loss on a toy: views of the same item pull together.
DExplorable · InfoNCE: temperature, negatives, collapse
How does contrastive learning learn useful embeddings without labels, and what keeps it from collapsing?
After training with this objective, where do the embeddings end up?
Batch size
Each item's negatives are the rest of the batch.
Objective
Without labels, a batch can't tell them apart. Off: they're masked out.
Multiplied by min(τ, 0.15)², so low temperatures take smaller steps.
Commit your prediction above to see the result
Make your prediction to see the result.
The temporal loss by hand
ExploreThe reference embeds four timestamps in 2-D, perturbs them for a second view, and scores each timestamp against all four in the other view at temperature . The aligned temporal loss is 0.750. One max-pooling step turns the four vectors into two: (1.0, 0.3) and (0.2, 1.0).
import numpy as np
def sm(a): e = np.exp(a - a.max(axis=-1, keepdims=True)); return e / e.sum(axis=-1, keepdims=True)
Z = np.array([[1., 0.], [.7, .3], [.2, .8], [0., 1.]])
other = Z + np.array([[.05, -.02], [-.02, .05], [.01, -.03], [-.03, .01]]) # second view
loss = -np.log(np.diag(sm(Z @ other.T / .2))).mean() # match each step to itself
print(loss, np.stack([Z[:2].max(0), Z[2:].max(0)])) # one coarser levelsm <- function(a) { e <- exp(a - apply(a, 1, max)); e / rowSums(e) }
Z <- rbind(c(1, 0), c(.7, .3), c(.2, .8), c(0, 1))
other <- Z + rbind(c(.05, -.02), c(-.02, .05), c(.01, -.03), c(-.03, .01)) # second view
loss <- -mean(log(diag(sm(Z %*% t(other) / .2)))) # match each step to itself
print(list(loss = loss, coarse = rbind(apply(Z[1:2, ], 2, max), apply(Z[3:4, ], 2, max))))The instance part and deeper levels are left out here.
Embedding overlapping windows
ExploreTS2Vec embedded 168 windows of 32 steps of x as 6 numbers each, after 5 epochs of contrastive training.
- Final contrastive loss
- 2.003
Plots
View data
| window | Component 1 | Component 2 |
|---|---|---|
| s01:1 | −0.0946 | −0.0123 |
| s01:17 | 0.0552 | 0.0953 |
| s01:33 | 0.0750 | 0.1277 |
| s01:49 | −0.0965 | 0.0261 |
| s01:65 | −0.1170 | 0.0383 |
| s01:81 | 0.1388 | 0.0578 |
| s01:97 | 0.1454 | 0.0939 |
| s02:1 | 0.2143 | −0.2031 |
| s02:17 | 0.2187 | 0.0584 |
| s02:33 | −0.0826 | −0.0073 |
| s02:49 | 0.0404 | 0.1127 |
| s02:65 | 0.1279 | 0.0672 |
| s02:81 | −0.1868 | −0.1637 |
| s02:97 | 0.1987 | −0.0065 |
| s03:1 | −0.2383 | 0.0634 |
| s03:17 | −0.0785 | 0.1861 |
| s03:33 | −0.1443 | 0.0188 |
| s03:49 | 0.0019 | 0.1154 |
| s03:65 | −0.1259 | −0.0055 |
| s03:81 | −0.2873 | −0.1028 |
| s03:97 | 0.0890 | −0.0519 |
| s04:1 | −0.1110 | −0.0299 |
| s04:17 | −0.0627 | −0.1153 |
| s04:33 | −0.2257 | −0.1955 |
| s04:49 | −0.0057 | −0.0993 |
| s04:65 | −0.0473 | −0.0313 |
| s04:81 | 0.1795 | 0.1030 |
| s04:97 | 0.1884 | 0.0839 |
| s05:1 | 0.0468 | −0.0652 |
| s05:17 | 0.1112 | 0.0799 |
| s05:33 | −0.0091 | −0.0774 |
| s05:49 | 0.0022 | 0.2624 |
| s05:65 | 0.0272 | 0.1566 |
| s05:81 | 0.3483 | 0.2047 |
| s05:97 | 0.1962 | 0.0392 |
| s06:1 | −0.3706 | −0.1646 |
| s06:17 | −0.3220 | −0.1575 |
| s06:33 | 0.1833 | 0.0482 |
| s06:49 | 0.3700 | −0.1090 |
| s06:65 | 0.4945 | −0.1872 |
| s06:81 | 0.4012 | −0.1508 |
| s06:97 | −0.0147 | −0.0440 |
| s07:1 | 0.0216 | −0.1184 |
| s07:17 | 0.0115 | −0.1166 |
| s07:33 | 0.0384 | −0.0685 |
| s07:49 | 0.0278 | −0.0760 |
| s07:65 | −0.1032 | −0.0425 |
| s07:81 | −0.1050 | −0.0417 |
| s07:97 | 0.2203 | −0.1348 |
| s08:1 | −0.2577 | −0.0084 |
| s08:17 | −0.2209 | −0.1445 |
| s08:33 | −0.1731 | −0.0378 |
| s08:49 | −0.1328 | 0.0078 |
| s08:65 | −0.3877 | −0.0431 |
| s08:81 | −0.4442 | −0.1053 |
| s08:97 | −0.4278 | −0.0335 |
| s09:1 | −0.2771 | 0.0561 |
| s09:17 | 0.0408 | 0.1169 |
| s09:33 | 0.0191 | 0.1410 |
| s09:49 | 0.0786 | −0.0385 |
First 60 of 168 rows.
View data
| Part | Loss | Epoch |
|---|---|---|
| Contrastive | 2.130 | 1 |
| Contrastive | 2.152 | 2 |
| Contrastive | 2.359 | 3 |
| Contrastive | 2.219 | 4 |
| Contrastive | 2.003 | 5 |
Assumptions
- The embeddings use several directions — The first principal direction holds 59% of the embeddings' variance.
Embeddings (first 6 of 6 numbers)
| Window (series:first step) | e1 | e2 | e3 | e4 | e5 | e6 |
|---|---|---|---|---|---|---|
| s01:1 | 1.251 | 0.6858 | 0.0372 | 0.5348 | 0.3187 | 1.349 |
| s01:17 | 1.408 | 0.7806 | −0.0056 | 0.4731 | 0.2584 | 1.403 |
| s01:33 | 1.465 | 0.7564 | −0.0101 | 0.4904 | 0.2463 | 1.421 |
| s01:49 | 1.268 | 0.6917 | −0.0095 | 0.5082 | 0.2585 | 1.411 |
| s01:65 | 1.257 | 0.6889 | 0.1243 | 0.5271 | 0.3223 | 1.406 |
| s01:81 | 1.429 | 0.8431 | −0.0253 | 0.4742 | 0.2226 | 1.328 |
| s01:97 | 1.478 | 0.8150 | −0.0268 | 0.4961 | 0.2126 | 1.355 |
| s02:1 | 1.421 | 0.7301 | 0.0096 | 0.3370 | 0.2421 | 1.089 |
| s02:17 | 1.480 | 0.8891 | 0.0048 | 0.4428 | 0.2682 | 1.283 |
| s02:33 | 1.230 | 0.7359 | 0.1402 | 0.3944 | 0.3541 | 1.379 |
| s02:49 | 1.415 | 0.7614 | 0.0385 | 0.4227 | 0.3211 | 1.429 |
| s02:65 | 1.483 | 0.7553 | 0.0240 | 0.4697 | 0.2598 | 1.339 |
| s02:81 | 1.127 | 0.5858 | 0.0929 | 0.3988 | 0.4075 | 1.284 |
| s02:97 | 1.473 | 0.8119 | 0.1047 | 0.4183 | 0.2703 | 1.240 |
| s03:1 | 1.145 | 0.6899 | −0.0122 | 0.5396 | 0.2953 | 1.502 |
| s03:17 | 1.309 | 0.8072 | 0.1579 | 0.5675 | 0.3368 | 1.500 |
| s03:33 | 1.196 | 0.7167 | −0.0317 | 0.5135 | 0.2650 | 1.425 |
| s03:49 | 1.317 | 0.8525 | 0.0403 | 0.5404 | 0.2714 | 1.417 |
| s03:65 | 1.227 | 0.6776 | −0.0074 | 0.4996 | 0.2603 | 1.399 |
| s03:81 | 1.026 | 0.6380 | 0.0121 | 0.5036 | 0.2623 | 1.392 |
| s03:97 | 1.335 | 0.8049 | −0.0121 | 0.4594 | 0.1742 | 1.268 |
| s04:1 | 1.242 | 0.6571 | 0.0024 | 0.4737 | 0.2335 | 1.384 |
| s04:17 | 1.240 | 0.6545 | 0.0156 | 0.4101 | 0.2287 | 1.300 |
| s04:33 | 1.042 | 0.6232 | 0.0326 | 0.4147 | 0.2783 | 1.298 |
| s04:49 | 1.282 | 0.6942 | 0.0274 | 0.3972 | 0.2799 | 1.275 |
| s04:65 | 1.281 | 0.6948 | 0.0121 | 0.4445 | 0.2529 | 1.352 |
| s04:81 | 1.498 | 0.8451 | 0.0174 | 0.4443 | 0.2519 | 1.351 |
| s04:97 | 1.495 | 0.8464 | −0.0184 | 0.4788 | 0.1978 | 1.330 |
| s05:1 | 1.319 | 0.7481 | −0.0029 | 0.3462 | 0.3477 | 1.280 |
| s05:17 | 1.371 | 0.9037 | 0.0108 | 0.4036 | 0.3282 | 1.358 |
| s05:33 | 1.262 | 0.7368 | 0.0173 | 0.3809 | 0.3394 | 1.288 |
| s05:49 | 1.423 | 0.8274 | 0.0335 | 0.4947 | 0.3755 | 1.550 |
| s05:65 | 1.390 | 0.8169 | 0.0352 | 0.4293 | 0.3761 | 1.460 |
| s05:81 | 1.590 | 1.059 | 0.0618 | 0.4238 | 0.3297 | 1.333 |
| s05:97 | 1.452 | 0.8772 | 0.0003 | 0.4258 | 0.3483 | 1.265 |
| s06:1 | 0.9605 | 0.5501 | 0.1031 | 0.4473 | 0.3633 | 1.375 |
| s06:17 | 1.037 | 0.5171 | 0.0374 | 0.4019 | 0.2957 | 1.391 |
| s06:33 | 1.424 | 0.9062 | −0.0279 | 0.3652 | 0.3118 | 1.309 |
| s06:49 | 1.522 | 0.9038 | −0.0167 | 0.2917 | 0.2765 | 1.094 |
| s06:65 | 1.612 | 0.8891 | −0.0175 | 0.2407 | 0.2527 | 0.9786 |
First 40 of 168 rows.
- 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 8c1486a0bc5318e3
# 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")))
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 <- df[stats::complete.cases(df[c("x", "series", "step")]), , 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")) # 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 <- NULL
UNIT <- "window" # series | window
WINDOW <- 32
STRIDE <- 16
DIMS <- as.integer(6)
HIDDEN <- as.integer(6)
DEPTH <- as.integer(2)
EPOCHS <- as.integer(5)
LR <- as.numeric(0.001)
BATCH <- as.integer(4)
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-windows-overlap/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-windows-overlap/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 168 windows of 32 steps of x as 6 numbers each, after 5 epochs of contrastive training.
- Final contrastive loss
- 2.003
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 59% of the embeddings' variance.
Embeddings (first 6 of 6 numbers)
| Window (series:first step) | e1 | e2 | e3 | e4 | e5 | e6 |
|---|---|---|---|---|---|---|
| s01:1 | 1.251 | 0.6858 | 0.0372 | 0.5348 | 0.3187 | 1.349 |
| s01:17 | 1.408 | 0.7806 | −0.0056 | 0.4731 | 0.2584 | 1.403 |
| s01:33 | 1.465 | 0.7564 | −0.0101 | 0.4904 | 0.2463 | 1.421 |
| s01:49 | 1.268 | 0.6917 | −0.0095 | 0.5082 | 0.2585 | 1.411 |
| s01:65 | 1.257 | 0.6889 | 0.1243 | 0.5271 | 0.3223 | 1.406 |
| s01:81 | 1.429 | 0.8431 | −0.0253 | 0.4742 | 0.2226 | 1.328 |
| s01:97 | 1.478 | 0.8150 | −0.0268 | 0.4961 | 0.2126 | 1.355 |
| s02:1 | 1.421 | 0.7301 | 0.0096 | 0.3370 | 0.2421 | 1.089 |
| s02:17 | 1.480 | 0.8891 | 0.0048 | 0.4428 | 0.2682 | 1.283 |
| s02:33 | 1.230 | 0.7359 | 0.1402 | 0.3944 | 0.3541 | 1.379 |
| s02:49 | 1.415 | 0.7614 | 0.0385 | 0.4227 | 0.3211 | 1.429 |
| s02:65 | 1.483 | 0.7553 | 0.0240 | 0.4697 | 0.2598 | 1.339 |
| s02:81 | 1.127 | 0.5858 | 0.0929 | 0.3988 | 0.4075 | 1.284 |
| s02:97 | 1.473 | 0.8119 | 0.1047 | 0.4183 | 0.2703 | 1.240 |
| s03:1 | 1.145 | 0.6899 | −0.0122 | 0.5396 | 0.2953 | 1.502 |
| s03:17 | 1.309 | 0.8072 | 0.1579 | 0.5675 | 0.3368 | 1.500 |
| s03:33 | 1.196 | 0.7167 | −0.0317 | 0.5135 | 0.2650 | 1.425 |
| s03:49 | 1.317 | 0.8525 | 0.0403 | 0.5404 | 0.2714 | 1.417 |
| s03:65 | 1.227 | 0.6776 | −0.0074 | 0.4996 | 0.2603 | 1.399 |
| s03:81 | 1.026 | 0.6380 | 0.0121 | 0.5036 | 0.2623 | 1.392 |
| s03:97 | 1.335 | 0.8049 | −0.0121 | 0.4594 | 0.1742 | 1.268 |
| s04:1 | 1.242 | 0.6571 | 0.0024 | 0.4737 | 0.2335 | 1.384 |
| s04:17 | 1.240 | 0.6545 | 0.0156 | 0.4101 | 0.2287 | 1.300 |
| s04:33 | 1.042 | 0.6232 | 0.0326 | 0.4147 | 0.2783 | 1.298 |
| s04:49 | 1.282 | 0.6942 | 0.0274 | 0.3972 | 0.2799 | 1.275 |
| s04:65 | 1.281 | 0.6948 | 0.0121 | 0.4445 | 0.2529 | 1.352 |
| s04:81 | 1.498 | 0.8451 | 0.0174 | 0.4443 | 0.2519 | 1.351 |
| s04:97 | 1.495 | 0.8464 | −0.0184 | 0.4788 | 0.1978 | 1.330 |
| s05:1 | 1.319 | 0.7481 | −0.0029 | 0.3462 | 0.3477 | 1.280 |
| s05:17 | 1.371 | 0.9037 | 0.0108 | 0.4036 | 0.3282 | 1.358 |
| s05:33 | 1.262 | 0.7368 | 0.0173 | 0.3809 | 0.3394 | 1.288 |
| s05:49 | 1.423 | 0.8274 | 0.0335 | 0.4947 | 0.3755 | 1.550 |
| s05:65 | 1.390 | 0.8169 | 0.0352 | 0.4293 | 0.3761 | 1.460 |
| s05:81 | 1.590 | 1.059 | 0.0618 | 0.4238 | 0.3297 | 1.333 |
| s05:97 | 1.452 | 0.8772 | 0.0003 | 0.4258 | 0.3483 | 1.265 |
| s06:1 | 0.9605 | 0.5501 | 0.1031 | 0.4473 | 0.3633 | 1.375 |
| s06:17 | 1.037 | 0.5171 | 0.0374 | 0.4019 | 0.2957 | 1.391 |
| s06:33 | 1.424 | 0.9062 | −0.0279 | 0.3652 | 0.3118 | 1.309 |
| s06:49 | 1.522 | 0.9038 | −0.0167 | 0.2917 | 0.2765 | 1.094 |
| s06:65 | 1.612 | 0.8891 | −0.0175 | 0.2407 | 0.2527 | 0.9786 |
First 40 of 168 rows.
- 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 8c1486a0bc5318e3
# 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"])
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 = df.dropna(subset=["x", "series", "step"]) # listwise deletion over the analysis columns
df["series"] = df["series"].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"]) # 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 = None
UNIT = "window" # series | window
WINDOW = 32
STRIDE = 16
DIMS = int(6)
HIDDEN = int(6)
DEPTH = int(2)
EPOCHS = int(5)
LR = float(0.001)
BATCH = int(4)
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-windows-overlap/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-windows-overlap/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,
})
Here TS2Vec embeds windows of 32 steps taken every 16 steps, giving 168 windows from 24 series. The first two principal components of the embeddings hold 58.9% and 24.9% of their variance.
Neighboring windows share half their steps. They are not independent examples: keep all windows of a series on one side of any later split.
Where embeddings leak
PredictPredict first
You compute TS2Vec embeddings over a whole series, then use the embedding at time to forecast time . Safe or a leak?
Reveal
It can leak. The encoder's window reaches both ways, so the vector at may already contain . For forecasting, compute each embedding from data up to only. Also check that augmentations keep positive pairs truly aligned; a misaligned crop teaches the wrong match.
What runs here
ReadCheck: TS2Vec
CheckpointCheck yourself
In TS2Vec, what is a positive pair?
Show the answer
Answer: b
Matching timestamps across augmented views are positives; other timestamps and other series supply negatives.
Check yourself
Why does TS2Vec repeat its loss after max-pooling over time?
Show the answer
Answer: a
Each pooling level applies the same contrastive loss to coarser vectors. Fine levels keep local detail; coarse levels capture longer patterns.
Check yourself
Windows of 32 steps are taken every 16 steps. How should you split them for a downstream classifier?
Show the answer
Answer: b
Overlapping windows share data. A random split would test on near-copies of training windows.
Check yourself
How do you show TS2Vec embeddings are useful?
Show the answer
Answer: b
Self-supervised loss doesn't measure usefulness. Evaluate the task you care about, with leakage-safe splits.
Recap
Recap- TS2Vec learns per-step vectors without labels by matching the same moment in two crops.
- Its loss contrasts against other times and other series, at several pooled scales.
- Overlapping windows and two-sided encoders can leak: split by series and keep forecasting causal.
- Judge embeddings on a downstream task. TS2Vec runs in CodeSplash as
discover.ts_embed.
Concepts in this lesson