Skip to content

CDiscover · discover.ts_embed

TS2Vec series embeddings (contrastive time-series representation)

Which series (or stretches of a series) follow similar patterns, judged by a representation learned without labels?

TS2Vec learns a representation of time series without labels: a dilated-convolution encoder reads two overlapping random crops of each series and is trained so the overlap gets the same representation in both (contextual consistency), contrasting each series with the others and each time step with the other steps, at several time scales (the hierarchical contrastive loss). Each series, or each window of a long series, is then embedded as a short vector by max-pooling its steps: similar patterns end up close together whatever their level and scale. With a class column, a leave-one-out nearest-neighbor probe shows how much class information the embeddings carry. Embeddings can be saved as a dataset. Both engines train the same network on torch from the same initial weights and crops. Experimental.

Experimental Python and R agree to 6 decimals Also called TS2Vec, time series embedding, time series representation learning…

A real result

Example “Signals probe”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

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

Do it in CodeSplash Run it on your own data. It's in the Experimental lane in the app.

Worked examples in the app

  • Signals probeseq_signals · label: class · series: series · time: step · value: x
  • Signals windows overlapseq_signals · series: series · time: step · value: x
  • Nile one series windowsml_nile · time: year · value: flow
  • Degenerate constantseq_signals · series: series · time: step · value: x
  • Degenerate n3seq_signals · series: series · time: step · value: x
  • Degenerate infseq_signals · series: series · time: step · value: x
  • Degenerate huge cardinalityseq_signals · series: series · time: step · value: x
  • Degenerate single levelseq_signals · series: series · time: step · value: x

In the guides

Where it sits in the decision guides

  • Dimensionality reduction (PCA, ICA, NMF) · DS & ML Decision Guide · Discover — find structure without labels
  • Sequences, curves and signals (hidden Markov models, functional PCA, scattering) · DS & ML Decision Guide · Discover — find structure without labels
  • Deep learning (CNN, RNN, Transformer) · DS & ML Decision Guide · Predict — forecast or classify outcomes

What you need

Valuenumeric · 1 column
The measured values, one per step.
Series (optional)categorical · 0–1 column
Which series each row belongs to (one per machine, store or trial). Needed to embed whole series.
Time (optional)temporal / numeric · 0–1 column
Orders the steps within each series; omit to use the row order. Steps are taken as evenly spaced.
Class (optional)categorical · 0–1 column
A known class per series (constant within each series); turns on the nearest-neighbor probe.

Choices you make

model

Embeddefault series

What gets one embedding each.

  • Whole series(default) — One embedding per series (needs at least 3 series); compare or cluster the series.
  • Windows — One embedding per window of each series; find stretches that look alike or unusual, even in one long series.
Window lengthdefault —

Windows only: steps in each window.

Window stridedefault —

Windows only: steps between window starts; smaller than the window length makes them overlap.

Embedding sizedefault 16

Numbers in each embedding.

Hidden channelsdefault 16

Width of the convolution layers.

Dilated blocksdefault 4

Residual blocks before the output block; each doubles the dilation, so more blocks see longer patterns.

Epochsdefault 100

Training passes over all series.

Learning ratedefault 0.001

Adam's step size.

Batch sizedefault 8

Series per gradient step; the instance-wise contrast compares the series within a batch.

Advanced

Optimizerdefault default

How the weights are updated. The method's own choice is the usual one.

  • Method's own(default) — Adam or AdamW, as the method describes; the usual choice.
  • Adam — Adam without decoupled weight decay (an AdamW method's weight decay is then not applied).
  • AdamW — Adam with decoupled weight decay; on an Adam method it adds decay 0.01 on weight matrices.
  • SGD with momentum — Plain gradient steps with momentum 0.9; often needs a larger learning rate and a schedule.
Learning-rate scheduledefault none

How the learning rate changes over training.

  • Constant(default) — The same learning rate every epoch (the method's default).
  • Cosine — Falls smoothly from the learning rate toward 0 over the epochs.
  • Step — Divides the learning rate by 10 after each third of the epochs.
  • One cycle — Rises from a 25th of the learning rate to the full rate over the first 30% of steps, then falls far below it.
  • Reduce on plateau — Divides the learning rate by 10 after 10 epochs without improvement in the validation loss.
Warm-up epochsdefault 0

Epochs at the start that ramp the learning rate up linearly; 0 = no warm-up.

Gradient clippingdefault 0

Largest gradient size (L2 norm over all weights) before a step; larger gradients are scaled down. 0 = off.

Weight average (EMA)default 0

Keeps a moving average of the weights (for example 0.99) and uses it for validation and the result. 0 = off.

Weight average from epoch (SWA)default 0

Averages the weights at the end of every epoch from this one on and returns the average. 0 = off; not with EMA.

Record every stepdefault off

Saves the loss, learning rate and gradient size after every batch in the training history, not only per epoch.

Compute profiledefault parity

Where and how precisely the network trains. Parity matches the other engine; the faster profiles can give slightly different numbers.

  • Parity(default) — Double precision on one CPU thread: the same numbers in Python and R, run after run (the default).
  • Faster CPU — Single precision on all performance cores; repeatable on this Mac, results differ slightly from Parity.
  • Apple GPU — Single precision on the Apple GPU (macOS 15 or later); results can differ slightly. Falls back to Faster CPU without a GPU.
Checkpoint every (epochs)default —

Saves the training state this often and when training ends, so a stopped run can resume where it was. Automatic saves about every 30 seconds; 0 = off. Each save holds the weights and the optimizer's state, so a large text encoder tuned on every layer can take 1–2 GB per fold.

Checks and remedies

CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.

  • The embeddings use several directions

    Warns when one principal direction holds over 90% of the embeddings' variance: the encoder has collapsed the series onto a line.

    • If violated → Wavelet scattering features — Scattering features are fixed (no training), so they cannot collapse, and they show how much the series differ in their frequency content. Changes the question: Fixed wavelet features of each series instead of a learned representation.

What it reports

n_instances
A convolutional encoder trained without labels so overlapping crops of a series get the same representation.
n_series
A convolutional encoder trained without labels so overlapping crops of a series get the same representation.
min_length
A convolutional encoder trained without labels so overlapping crops of a series get the same representation.
dims
A convolutional encoder trained without labels so overlapping crops of a series get the same representation.
depth
Stacked convolutions whose spacing doubles each block, so each step's representation sees exponentially more neighbors.
receptive_field
Stacked convolutions whose spacing doubles each block, so each step's representation sees exponentially more neighbors.
epochs_run
Contrasts each series with the others and each time step with the other steps, then repeats after halving the time resolution.
final_loss
Contrasts each series with the others and each time step with the other steps, then repeats after halving the time resolution.
n_params
A convolutional encoder trained without labels so overlapping crops of a series get the same representation.
pc_share1
The share of the embeddings' variance on their first (or second) principal direction; over 90% on one suggests collapse.
pc_share2
The share of the embeddings' variance on their first (or second) principal direction; over 90% on one suggests collapse.
embed_check
The share of the embeddings' variance on their first (or second) principal direction; over 90% on one suggests collapse.

Per group, level or term: window, stride, probe_acc, probe_chance

Python and R

Python and R agree to 6 decimals (relative tolerance 1e-6). Python uses torch, codesplash; R uses torch, codesplashr, nanoparquet.

Default traps between the two languages

  • The dilated convolutions (one matrix product over the input shifted by −δ, 0 and +δ steps), GELU (written with erf), the hierarchical contrastive loss and Adam are written out in both helpers and run on LibTorch in double precision on one thread, from the same initial weights; crop positions and timestamp masks come from the shared Wichmann–Hill stream. Python's torch and R's torch ship different LibTorch builds, so a kernel can differ by an ulp; embeddings agree to about 1e-15 relative on the fixtures.
  • The embedding map's principal components come from each engine's symmetric eigendecomposition, signed so each eigenvector's largest entry is positive.
Python

The exact script CodeSplash ran for example “Signals probe” · 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,
})
R

The exact script CodeSplash ran for example “Signals probe” · 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
))

Sources

  • Yue Z, Wang Y, Duan J, Yang T, Huang C, Tong Y, Xu B (2022). TS2Vec: towards universal representation of time series. Proceedings of the AAAI Conference on Artificial Intelligence 36(8):8980–8987.
  • van den Oord A, Li Y, Vinyals O (2018). Representation learning with contrastive predictive coding. arXiv:1807.03748.
  • Bai S, Kolter JZ, Koltun V (2018). An empirical evaluation of generic convolutional and recurrent networks for sequence modeling. arXiv:1803.01271.

From the CodeSplash method registry · discover.ts_embed v1.0.0.