Skip to content

Tabular, time-series, scientific, and geometric deep learning · Time-series forecasting and representation · SPE019 · Architecture

PatchTST

PatchTST uses short temporal patches as transformer tokens and shares a backbone across univariate channels. Patching reduces token count and preserves local temporal structure;

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 forecast.patchtst. The reference's example ran here in one language.
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

PatchTST uses short temporal patches as transformer tokens and shares a backbone across univariate channels. Patching reduces token count and preserves local temporal structure; the family supports supervised forecasting and self-supervised pretraining.

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

Each channel is normalized and split into overlapping or nonoverlapping patches. Shared patch embeddings and transformer blocks encode channel histories, followed by forecasting heads; masked-patch reconstruction is an optional pretraining objective.

Assumptions

Channels are not assumed statistically independent merely because weights are shared. Cross-channel relationships may be missed without extensions. Temporal leakage from overlapping windows or normalization and changing sampling frequency are major failure modes.

Formula / computational definition

Pc,j=(xc,js,…,xc,js+p−1)P_{c,j}=(x_{c,js},\ldots,x_{c,js+p-1}), tc,j=WPc,j+b+ejt_{c,j}=WP_{c,j}+b+e_j. Patch length p and stride s determine token count. Forecasting minimizes a declared horizon loss; masked learning predicts missing patches.

Parameters and notation

Learned or estimated: Shared patch projection and transformer weights, positional parameters and forecast/reconstruction heads; channel-specific processing depends on the declared variant.

Hyperparameters and effects: Lookback, patch length/stride, horizon, normalization, heads/depth/width, dropout and masking. Larger patches reduce tokens but can obscure short events; channel independence limits direct cross-channel interactions.

Fitting, fine-tuning, and adaptation

Pretrain on permitted historical data if desired, then fit a forecast head. Transfer a frozen patch encoder first and unfreeze at lower rates after validation. Revisit patch duration when sampling frequency changes and adjust positional/head dimensions carefully. Check target-horizon calibration and source-series retention.

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. Use rolling-origin evaluation, horizon metrics, missingness and sampling-frequency shifts, and comparisons with linear/channel-mixing baselines. Report token counts and compute at matched lookback rather than only model parameters.

Example application

Forecast long multivariate sensor histories with a shared channelwise patch encoder. 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: Channel-independent temporal patch extraction and shared linear embedding. Use the shared setup. Dependencies: NumPy / base R. Validation: Python executed; R unexecuted.

Full-model route: Python: official PatchTST. R: native torch patch extraction/transformers or Python bridge. The example extracts channelwise patches and embeds them with shared weights, not a trained forecast network.

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 — Channel-independent temporal patch extraction and shared linear embedding. 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)
X=np.array([np.sin(np.arange(12.)/3),np.cos(np.arange(12.)/3)])
length,stride=4,2; starts=range(0,X.shape[1]-length+1,stride)
patches=np.stack([X[:,s:s+length] for s in starts],axis=1)
W=np.arange(12.).reshape(4,3)/12; tokens=patches@W
assert tokens.shape==(2,5,3)
print(tokens.shape,tokens[0,0])
R

Component demo, not a trained model — Channel-independent temporal patch extraction and shared linear embedding. 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) }))
}
X<-rbind(sin((0:11)/3),cos((0:11)/3)); length_patch<-4; stride<-2
starts<-seq(1,ncol(X)-length_patch+1,by=stride); W<-matrix(0:11,4,byrow=TRUE)/12
tokens<-array(0,c(2,length(starts),3))
for(ch in 1:2) for(j in seq_along(starts)) tokens[ch,j,]<-X[ch,starts[j]:(starts[j]+length_patch-1)]%*%W
stopifnot(identical(dim(tokens),c(2L,5L,3L))); print(tokens[1,1,])

Sources

From the CodeSplash reference, entry SPE019.