Skip to content

Tabular, time-series, scientific, and geometric deep learning · Time-series forecasting and representation · SPE020 · Training method

TS2Vec

TS2Vec learns contextual representations at individual timestamps and larger temporal scales through hierarchical contrastive learning.

Runs in CodeSplash (Experimental) Component demo, not a trained model CodeSplash's run and the reference's record

In CodeSplash

A CodeSplash method runs this entry in Python and R. Set it up from the method's page. The methods that run it are Experimental.

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

Availability
Runs in CodeSplash (Experimental)
Code example
Component demo, not a trained model
Who ran it
CodeSplash's run and the reference's record
CodeSplash's run
Verified in Python and R through discover.ts_embed. The reference's example ran in Python and R here, and they agree.
The reference's record
Python: Ran in the reference's review. The report doesn't record which version of the code ran. R: Reviewed but not run: R wasn't available to the reference's authors.

Purpose

TS2Vec learns contextual representations at individual timestamps and larger temporal scales through hierarchical contrastive learning. Representations can support classification, forecasting and anomaly-detection pipelines with separate downstream evaluation.

Question / hypotheses

The operative question is whether the specified representation, symmetry, likelihood or physical constraint improves held-out behavior for this data domain. This is a learning framework, not a null-hypothesis test; losses, attention weights and predictive confidence are not statistical p-values.

Architecture / computational structure

A dilated convolutional encoder processes augmented context views. Timestamp-level instance and temporal contrastive losses are combined across increasingly pooled temporal resolutions; aggregation can produce subsequence or whole-series embeddings.

Assumptions

Positive alignment must survive augmentations; time warps or misaligned crops can silently corrupt supervision. Noncausal context embeddings may leak future information in forecasting unless inference is made causal. Negatives may share meaningful patterns.

Formula / computational definition

L=∑l[λLinstance(Zl,Zl′)+(1−λ)Ltemporal(Zl,Zl′)]L=\sum_l[\lambda L_{instance}(Z_l,Z_l^\prime)+(1-\lambda)L_{temporal}(Z_l,Z_l^\prime)], with Zl+1=MaxPool⁡(Zl)Z_{l+1}=\operatorname{MaxPool}(Z_l) schematically. Positive pairs correspond to matching timestamps in overlapping augmented contexts.

Parameters and notation

Learned or estimated: Encoder and any projection parameters; contrastive objectives train representations without downstream task labels. A later forecast/classification head has separate fitted parameters.

Hyperparameters and effects: Crop/mask policy, embedding width, dilation/depth, hierarchy levels, loss weighting, context length and optimizer. Coarse levels emphasize long structure while fine levels preserve local distinctions.

Fitting, fine-tuning, and adaptation

Pretrain on training-period or otherwise permitted series. Fit a frozen-representation downstream model first; optionally fine-tune encoder plus head with smaller encoder rates and time-respecting validation. Keep causal/noncausal inference conventions explicit, and monitor source transfer and embedding variance after adaptation.

How to use and calibrate

Define the independent evaluation unit before preprocessing: row/entity, whole set/object, molecule/trajectory, input function or chronological forecasting origin. Keep target construction and normalization within permitted training data. Evaluate downstream tasks on independent entities/time periods, representation stability, missingness, horizon behavior and compute. A low contrastive loss does not validate anomaly thresholds or forecast intervals; calibrate those separately.

Example application

Learn reusable timestamp and subsequence features from unlabeled sensor streams. This is a proposed use case, not a claim of validated performance on supplied real data.

Interpretation / pitfalls

Watch out

Assess model error against domain baselines and the stated assumptions. Component-level mathematical correctness does not establish paper reproduction or scientific validity. Use an independent validation design for model selection and a final held-out evaluation for claims; uncertainty and calibration require separate assessment.

Python and R code examples

Scope: TS2Vec-aligned temporal contrastive scoring and one coarse max-pooling level. Use the shared setup. Dependencies: NumPy / base R. Validation: Python executed; R unexecuted.

Full-model route: Python: authors’ TS2Vec implementation. R: custom native torch contrastive hierarchy or Python bridge. The example demonstrates aligned temporal contrastive scoring and coarse pooling, not full TS2Vec training.

Python and R

The reference's own programs, shown as written. A component demo shows one central piece of the method; it doesn't train a full model.

Python

Component demo, not a trained model — TS2Vec-aligned temporal contrastive scoring and one coarse max-pooling level. Use the shared setup.

Shared setup for this chapter
import numpy as np
def sm(x):
    x=np.asarray(x); e=np.exp(x-x.max(axis=-1,keepdims=True)); return e/e.sum(axis=-1,keepdims=True)
Z=np.array([[1.,0.],[.7,.3],[.2,.8],[0.,1.]])
other=Z+np.array([[.05,-.02],[-.02,.05],[.01,-.03],[-.03,.01]])
prob=sm(Z@other.T/.2); aligned_loss=-np.log(np.diag(prob)).mean()
coarse=np.stack([Z[:2].max(0),Z[2:].max(0)])
print(aligned_loss,coarse) # instance contrast and full hierarchy omitted
R

Component demo, not a trained model — TS2Vec-aligned temporal contrastive scoring and one coarse max-pooling level. Use the shared setup.

Shared setup for this chapter
sm <- function(x) {
  if(is.null(dim(x))) { e<-exp(x-max(x)); return(e/sum(e)) }
  t(apply(x,1,function(v) { e<-exp(v-max(v)); e/sum(e) }))
}
Z<-matrix(c(1,0,.7,.3,.2,.8,0,1),4,byrow=TRUE)
other<-Z+matrix(c(.05,-.02,-.02,.05,.01,-.03,-.03,.01),4,byrow=TRUE)
prob<-sm(Z%*%t(other)/.2); aligned_loss<--mean(log(diag(prob)))
coarse<-rbind(apply(Z[1:2,],2,max),apply(Z[3:4,],2,max))
print(list(loss=aligned_loss,coarse=coarse))

Sources

From the CodeSplash reference, entry SPE020.