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.
A real result
Example “Signals probe”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
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
View data
| series | Component 1 | Component 2 |
|---|---|---|
| s01 | −0.1372 | −0.0399 |
| s02 | −0.1724 | 0.1036 |
| s03 | −0.0077 | −0.0849 |
| s04 | −0.1550 | −0.1376 |
| s05 | 0.1363 | 0.1072 |
| s06 | −0.1693 | 0.0737 |
| s07 | −0.0848 | −0.0578 |
| s08 | 0.1947 | −0.0148 |
| s09 | 0.0041 | −0.0909 |
| s10 | 0.2092 | 0.0930 |
| s11 | −0.0639 | −0.0200 |
| s12 | −0.0128 | −0.0145 |
| s13 | −0.1507 | 0.1723 |
| s14 | 0.0214 | −0.0626 |
| s15 | 0.1346 | 0.0622 |
| s16 | 0.1399 | 0.0781 |
| s17 | 0.1059 | −0.0193 |
| s18 | −0.0652 | −0.1288 |
| s19 | 0.1213 | −0.0035 |
| s20 | −0.0419 | −0.0299 |
| s21 | −0.1495 | 0.0424 |
| s22 | −0.0466 | 0.1408 |
| s23 | 0.0527 | −0.0302 |
| s24 | 0.1369 | −0.1386 |
View data
| Part | Loss | Epoch |
|---|---|---|
| Contrastive | 2.746 | 1 |
| Contrastive | 2.478 | 2 |
| Contrastive | 2.829 | 3 |
| Contrastive | 2.661 | 4 |
| Contrastive | 2.390 | 5 |
| Contrastive | 2.351 | 6 |
| Contrastive | 2.635 | 7 |
| Contrastive | 2.497 | 8 |
Assumptions
- The embeddings use several directions — The first principal direction holds 37% of the embeddings' variance.
Embeddings (first 8 of 8 numbers)
| series | e1 | e2 | e3 | e4 | e5 | e6 | e7 | e8 |
|---|---|---|---|---|---|---|---|---|
| s01 | 1.355 | 0.8915 | 0.1968 | 0.5035 | 0.5307 | 1.189 | 0.1295 | 0.3136 |
| s02 | 1.391 | 0.8583 | 0.1205 | 0.4513 | 0.4779 | 1.141 | 0.3330 | 0.2215 |
| s03 | 1.322 | 0.7592 | 0.1330 | 0.5260 | 0.4712 | 1.278 | 0.1525 | 0.2157 |
| s04 | 1.424 | 0.7538 | 0.1272 | 0.5547 | 0.4465 | 1.154 | 0.1342 | 0.2434 |
| s05 | 1.260 | 0.7658 | 0.0659 | 0.3615 | 0.5803 | 1.380 | 0.2575 | 0.2331 |
| s06 | 1.381 | 0.9242 | 0.1204 | 0.3649 | 0.4911 | 1.158 | 0.1537 | 0.3165 |
| s07 | 1.369 | 0.7521 | 0.1375 | 0.4631 | 0.4042 | 1.202 | 0.1681 | 0.2179 |
| s08 | 1.002 | 0.6941 | 0.1851 | 0.4972 | 0.5066 | 1.291 | 0.2101 | 0.2694 |
| s09 | 1.352 | 0.7812 | 0.1710 | 0.5499 | 0.5701 | 1.316 | 0.1562 | 0.2677 |
| s10 | 1.208 | 0.7354 | 0.1280 | 0.3130 | 0.5225 | 1.432 | 0.2173 | 0.2453 |
| s11 | 1.320 | 0.8090 | 0.0728 | 0.4197 | 0.4919 | 1.210 | 0.1111 | 0.3891 |
| s12 | 1.342 | 0.7956 | 0.1589 | 0.4335 | 0.4887 | 1.286 | 0.1642 | 0.2563 |
| s13 | 1.326 | 0.9750 | 0.1394 | 0.4650 | 0.5261 | 1.197 | 0.3476 | 0.3321 |
| s14 | 1.232 | 0.7201 | 0.1418 | 0.4277 | 0.5188 | 1.203 | 0.1077 | 0.2640 |
| s15 | 1.280 | 0.7304 | 0.0649 | 0.3915 | 0.5224 | 1.388 | 0.2487 | 0.2079 |
| s16 | 1.312 | 0.7454 | 0.1046 | 0.3171 | 0.4820 | 1.422 | 0.2159 | 0.2322 |
| s17 | 1.234 | 0.8455 | 0.1893 | 0.5073 | 0.6515 | 1.394 | 0.1459 | 0.3795 |
| s18 | 1.353 | 0.7491 | 0.1252 | 0.5764 | 0.4607 | 1.230 | 0.1463 | 0.2585 |
| s19 | 1.207 | 0.7049 | 0.0896 | 0.4040 | 0.5126 | 1.318 | 0.1673 | 0.3490 |
| s20 | 1.354 | 0.7607 | 0.1114 | 0.4225 | 0.5092 | 1.227 | 0.1499 | 0.2993 |
| s21 | 1.342 | 0.8689 | 0.1143 | 0.4154 | 0.5194 | 1.135 | 0.1790 | 0.3695 |
| s22 | 1.252 | 0.9211 | 0.0925 | 0.4747 | 0.4490 | 1.273 | 0.3166 | 0.3012 |
| s23 | 1.351 | 0.7629 | 0.0462 | 0.4471 | 0.5765 | 1.352 | 0.1417 | 0.3761 |
| s24 | 1.315 | 0.7042 | 0.1600 | 0.5681 | 0.5231 | 1.449 | 0.1397 | 0.3353 |
Leave-one-out nearest-neighbor probe
| Features | Accuracy |
|---|---|
| TS2Vec embedding (8 numbers) | 62.5% |
| Always the most common class | 50.0% |
- The embeddings are learned without labels: series whose patterns look alike end up close together, whatever their level and scale (each series is standardized first).
- Each step's representation sees about 30 neighboring steps on each side; a series' embedding is the maximum over its steps, so it records which patterns occur, not when.
TS2Vec embedded 24 series of x as 8 numbers each, after 8 epochs of contrastive training. A nearest-neighbor probe on the embeddings recovers class for 62% of the series (most common class: 50%).
- Final contrastive loss
- 2.497
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- The embeddings use several directions — The first principal direction holds 37% of the embeddings' variance.
Embeddings (first 8 of 8 numbers)
| series | e1 | e2 | e3 | e4 | e5 | e6 | e7 | e8 |
|---|---|---|---|---|---|---|---|---|
| s01 | 1.355 | 0.8915 | 0.1968 | 0.5035 | 0.5307 | 1.189 | 0.1295 | 0.3136 |
| s02 | 1.391 | 0.8583 | 0.1205 | 0.4513 | 0.4779 | 1.141 | 0.3330 | 0.2215 |
| s03 | 1.322 | 0.7592 | 0.1330 | 0.5260 | 0.4712 | 1.278 | 0.1525 | 0.2157 |
| s04 | 1.424 | 0.7538 | 0.1272 | 0.5547 | 0.4465 | 1.154 | 0.1342 | 0.2434 |
| s05 | 1.260 | 0.7658 | 0.0659 | 0.3615 | 0.5803 | 1.380 | 0.2575 | 0.2331 |
| s06 | 1.381 | 0.9242 | 0.1204 | 0.3649 | 0.4911 | 1.158 | 0.1537 | 0.3165 |
| s07 | 1.369 | 0.7521 | 0.1375 | 0.4631 | 0.4042 | 1.202 | 0.1681 | 0.2179 |
| s08 | 1.002 | 0.6941 | 0.1851 | 0.4972 | 0.5066 | 1.291 | 0.2101 | 0.2694 |
| s09 | 1.352 | 0.7812 | 0.1710 | 0.5499 | 0.5701 | 1.316 | 0.1562 | 0.2677 |
| s10 | 1.208 | 0.7354 | 0.1280 | 0.3130 | 0.5225 | 1.432 | 0.2173 | 0.2453 |
| s11 | 1.320 | 0.8090 | 0.0728 | 0.4197 | 0.4919 | 1.210 | 0.1111 | 0.3891 |
| s12 | 1.342 | 0.7956 | 0.1589 | 0.4335 | 0.4887 | 1.286 | 0.1642 | 0.2563 |
| s13 | 1.326 | 0.9750 | 0.1394 | 0.4650 | 0.5261 | 1.197 | 0.3476 | 0.3321 |
| s14 | 1.232 | 0.7201 | 0.1418 | 0.4277 | 0.5188 | 1.203 | 0.1077 | 0.2640 |
| s15 | 1.280 | 0.7304 | 0.0649 | 0.3915 | 0.5224 | 1.388 | 0.2487 | 0.2079 |
| s16 | 1.312 | 0.7454 | 0.1046 | 0.3171 | 0.4820 | 1.422 | 0.2159 | 0.2322 |
| s17 | 1.234 | 0.8455 | 0.1893 | 0.5073 | 0.6515 | 1.394 | 0.1459 | 0.3795 |
| s18 | 1.353 | 0.7491 | 0.1252 | 0.5764 | 0.4607 | 1.230 | 0.1463 | 0.2585 |
| s19 | 1.207 | 0.7049 | 0.0896 | 0.4040 | 0.5126 | 1.318 | 0.1673 | 0.3490 |
| s20 | 1.354 | 0.7607 | 0.1114 | 0.4225 | 0.5092 | 1.227 | 0.1499 | 0.2993 |
| s21 | 1.342 | 0.8689 | 0.1143 | 0.4154 | 0.5194 | 1.135 | 0.1790 | 0.3695 |
| s22 | 1.252 | 0.9211 | 0.0925 | 0.4747 | 0.4490 | 1.273 | 0.3166 | 0.3012 |
| s23 | 1.351 | 0.7629 | 0.0462 | 0.4471 | 0.5765 | 1.352 | 0.1417 | 0.3761 |
| s24 | 1.315 | 0.7042 | 0.1600 | 0.5681 | 0.5231 | 1.449 | 0.1397 | 0.3353 |
Leave-one-out nearest-neighbor probe
| Features | Accuracy |
|---|---|
| TS2Vec embedding (8 numbers) | 62.5% |
| Always the most common class | 50.0% |
- The embeddings are learned without labels: series whose patterns look alike end up close together, whatever their level and scale (each series is standardized first).
- Each step's representation sees about 30 neighboring steps on each side; a series' embedding is the maximum over its steps, so it records which patterns occur, not when.
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.
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,
})
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.