Skip to content

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.

Advanced ~12 min6 steps

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

Read first

01

Fixed features vs learned ones

Read

Wavelet 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.

02

Embedding whole series

Read
TS2Vec series embeddings (contrastive time-series representation)Recorded · Python and R agreeRecorded 2026-11-21 · 14 values compared
R

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

Plots

Embeddings on their first two principal componentsWhich levels of a categorical variable does the model treat as alike?
View data
seriesComponent 1Component 2
s01−0.1372−0.0399
s02−0.17240.1036
s03−0.0077−0.0849
s04−0.1550−0.1376
s050.13630.1072
s06−0.16930.0737
s07−0.0848−0.0578
s080.1947−0.0148
s090.0041−0.0909
s100.20920.0930
s11−0.0639−0.0200
s12−0.0128−0.0145
s13−0.15070.1723
s140.0214−0.0626
s150.13460.0622
s160.13990.0781
s170.1059−0.0193
s18−0.0652−0.1288
s190.1213−0.0035
s20−0.0419−0.0299
s21−0.14950.0424
s22−0.04660.1408
s230.0527−0.0302
s240.1369−0.1386
Hierarchical contrastive loss by epochIs the network still learning, and which part of its loss moves?
View data
PartLossEpoch
Contrastive2.7461
Contrastive2.4782
Contrastive2.8293
Contrastive2.6614
Contrastive2.3905
Contrastive2.3516
Contrastive2.6357
Contrastive2.4978

Assumptions

  • The embeddings use several directions — The first principal direction holds 37% of the embeddings' variance.

Embeddings (first 8 of 8 numbers)

seriese1e2e3e4e5e6e7e8
s011.3550.89150.19680.50350.53071.1890.12950.3136
s021.3910.85830.12050.45130.47791.1410.33300.2215
s031.3220.75920.13300.52600.47121.2780.15250.2157
s041.4240.75380.12720.55470.44651.1540.13420.2434
s051.2600.76580.06590.36150.58031.3800.25750.2331
s061.3810.92420.12040.36490.49111.1580.15370.3165
s071.3690.75210.13750.46310.40421.2020.16810.2179
s081.0020.69410.18510.49720.50661.2910.21010.2694
s091.3520.78120.17100.54990.57011.3160.15620.2677
s101.2080.73540.12800.31300.52251.4320.21730.2453
s111.3200.80900.07280.41970.49191.2100.11110.3891
s121.3420.79560.15890.43350.48871.2860.16420.2563
s131.3260.97500.13940.46500.52611.1970.34760.3321
s141.2320.72010.14180.42770.51881.2030.10770.2640
s151.2800.73040.06490.39150.52241.3880.24870.2079
s161.3120.74540.10460.31710.48201.4220.21590.2322
s171.2340.84550.18930.50730.65151.3940.14590.3795
s181.3530.74910.12520.57640.46071.2300.14630.2585
s191.2070.70490.08960.40400.51261.3180.16730.3490
s201.3540.76070.11140.42250.50921.2270.14990.2993
s211.3420.86890.11430.41540.51941.1350.17900.3695
s221.2520.92110.09250.47470.44901.2730.31660.3012
s231.3510.76290.04620.44710.57651.3520.14170.3761
s241.3150.70420.16000.56810.52311.4490.13970.3353

Leave-one-out nearest-neighbor probe

FeaturesAccuracy
TS2Vec embedding (8 numbers)62.5%
Always the most common class50.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
))
Python

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)

seriese1e2e3e4e5e6e7e8
s011.3550.89150.19680.50350.53071.1890.12950.3136
s021.3910.85830.12050.45130.47791.1410.33300.2215
s031.3220.75920.13300.52600.47121.2780.15250.2157
s041.4240.75380.12720.55470.44651.1540.13420.2434
s051.2600.76580.06590.36150.58031.3800.25750.2331
s061.3810.92420.12040.36490.49111.1580.15370.3165
s071.3690.75210.13750.46310.40421.2020.16810.2179
s081.0020.69410.18510.49720.50661.2910.21010.2694
s091.3520.78120.17100.54990.57011.3160.15620.2677
s101.2080.73540.12800.31300.52251.4320.21730.2453
s111.3200.80900.07280.41970.49191.2100.11110.3891
s121.3420.79560.15890.43350.48871.2860.16420.2563
s131.3260.97500.13940.46500.52611.1970.34760.3321
s141.2320.72010.14180.42770.51881.2030.10770.2640
s151.2800.73040.06490.39150.52241.3880.24870.2079
s161.3120.74540.10460.31710.48201.4220.21590.2322
s171.2340.84550.18930.50730.65151.3940.14590.3795
s181.3530.74910.12520.57640.46071.2300.14630.2585
s191.2070.70490.08960.40400.51261.3180.16730.3490
s201.3540.76070.11140.42250.50921.2270.14990.2993
s211.3420.86890.11430.41540.51941.1350.17900.3695
s221.2520.92110.09250.47470.44901.2730.31660.3012
s231.3510.76290.04620.44710.57651.3520.14170.3761
s241.3150.70420.16000.56810.52311.4490.13970.3353

Leave-one-out nearest-neighbor probe

FeaturesAccuracy
TS2Vec embedding (8 numbers)62.5%
Always the most common class50.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.

03

How sure is the probe?

Predict

Predict first

The probe reaches 75% on 8 series with two classes of 4 each. What does that tell you?

Good evidence the embeddings separate the classesWeak evidence: with few series the accuracy is noisy
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.

04

Windows of one long series

Read
TS2Vec series embeddings (contrastive time-series representation)Recorded · Python and R agreeRecorded 2026-11-21 · 14 values compared
R

TS2Vec embedded 5 windows of 20 steps of flow as 4 numbers each, after 10 epochs of contrastive training.

Final contrastive loss
1.272

Plots

Embeddings on their first two principal componentsWhich levels of a categorical variable does the model treat as alike?
View data
windowComponent 1Component 2
11.169−0.0418
210.46310.0739
41−0.59370.3963
61−0.8672−0.2537
81−0.1716−0.1747
Hierarchical contrastive loss by epochIs the network still learning, and which part of its loss moves?
View data
PartLossEpoch
Contrastive0.91891
Contrastive1.2362
Contrastive0.68103
Contrastive1.1514
Contrastive0.73115
Contrastive0.97216
Contrastive1.2577
Contrastive1.3948
Contrastive1.3059
Contrastive1.27210

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)e1e2e3e4
12.1481.1620.22660.3192
211.5220.96540.38640.6003
410.79340.40700.57741.198
610.39250.18910.39640.6899
811.0030.51010.41050.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
))
Python

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)e1e2e3e4
12.1481.1620.22660.3192
211.5220.96540.38640.6003
410.79340.40700.57741.198
610.39250.18910.39640.6899
811.0030.51010.41050.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.

05

Reading the map, and collapse

Read

The 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.

06

Check: TS2Vec

Checkpoint

Check 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