The architecture of STraTS is illustrated in Figure 3. Unlike most of the existing approaches which
take a time-series matrix as input, STraTS defines its input as a set of observation triplets. Each
observation triplet in the input is embedded using the Initial Triplet Embedding module. The
initial triplet embeddings are then passed through a Contextual Triplet Embedding module which
utilizes the Transfomer architecture to encode the context for each triplet. The Fusion Self-attention
module then combines these contextual embeddings via self-attention mechanism to generate an
embedding for the input time-series which is concatenated with demographics embedding and
passed through a feed-forward network to make the final prediction. The notations used in the
paper are summarized in Table 1.
3.2.1 Initial Triplet Embedding. Given an input time-series T = {(𝑡𝑖
, 𝑓𝑖
, 𝑣𝑖)}𝑛
𝑖=1
, the initial embedding
for the 𝑖
𝑡ℎ triplet ei ∈ R
𝑑
is computed by summing the following component embeddings: (i) Feature
embedding e
f
i
∈ R
𝑑
, (ii) Value embedding e
v
i
∈ R
𝑑
, and (iii) Time embedding e
t
i
∈ R
𝑑
. In other words,
ei = e
f
i
e
v
i
e
t
i
∈ R
𝑑
. Feature embeddings e
f
(·) are obtained from a simple lookup table similar to
word embeddings. Since feature values and times are continuous unlike feature names which are
categorical objects, we cannot use a lookup table to embed these continuous values unless they
are categorized. Some researchers [30, 32] have used sinusoidal encodings to embed continuous
ACM Trans. Knowl. Discov. Data., Vol. 1, No. 1, Article . Publication date: February 2022.
Self-Supervised Transformer for Sparse and Irregularly Sampled Multivariate Clinical Time-Series 7
Table 1. Notations used in this paper.
Notation Definition
𝑁 # Time-series for target task
𝑁
′
Time-series for forecasting task
d ∈ R
𝐷 Demographics vector
F Set of clinical variables
𝑡𝑖 ∈ R≥0 Time of 𝑖
𝑡ℎ observation
𝑓𝑖 ∈ F Variable of 𝑖
𝑡ℎ observation
𝑣𝑖 ∈ R Value of 𝑖
𝑡ℎ observation
(𝑡, 𝑓 , 𝑣) Observation triplet
T = {(𝑡𝑖
, 𝑓𝑖
, 𝑣𝑖)}𝑛
𝑖=1 Multivariate time-series
𝑦,𝑦˜ ∈ {0, 1} True and predicted outputs for target task
z, z˜ ∈ R
|F | True and predicted outputs for forecasting task
m ∈ {0, 1}
|F | Forecast mask
e
𝑡
𝑖
, e
𝑣
𝑖
∈ R
𝑑 CVE for time and value
e
𝑓
𝑖
∈ R
𝑑 Variable embedding
e𝑖 ∈ R
𝑑
Initial triplet embedding
e
𝑇 ∈ R
𝑑 Time-series embedding
e
𝑑 ∈ R
𝑑 Demographics embedding
values. We propose a novel continuous value embedding (CVE) technique using a one-to-many
Feed-Forward Network (FFN) with learnable parameters i.e., e
v
i
= 𝐹 𝐹𝑁𝑣
(𝑣𝑖), and e
t
i
= 𝐹 𝐹𝑁𝑡
(𝑡𝑖).
Both FFNs have one input neuron and 𝑑 output neurons and a single hidden layer with ⌊
√
𝑑⌋
neurons and 𝑡𝑎𝑛ℎ(·) activation. They are of the form 𝐹 𝐹𝑁 (𝑥) = 𝑈 𝑡𝑎𝑛ℎ(𝑊 𝑥 + 𝑏) where the
dimensions of weights {𝑊 , 𝑏,𝑈 } can be inferred from the size of hidden and output layers of the
FFN. Unlike sinusoidal encodings with fixed frequencies, this technique offers more flexibility
by allowing end-to-end learning of continuous value and time embeddings without the need to
categorize them.
3.2.2 Contextual Triplet Embedding. The initial triplet embeddings {e1, ..., e𝑛} are then passed
through a Transformer architecture [30] with 𝑀 blocks, each containing a Multi-Head Attention
(MHA) layer with ℎ attention heads and a FFN with one hidden layer. Each block takes 𝑛 input
embeddings E ∈ R
𝑛×𝑑
and outputs the corresponding 𝑛 output embeddings C ∈ R
𝑛×𝑑
that capture
the contextual information. MHA layers use multiple attention heads to attend to information
contained in different embedding projections in parallel. The computations of the MHA layer are
given by
H𝑗 = 𝑠𝑜 𝑓 𝑡𝑚𝑎𝑥
(EW𝑞
𝑗
) (EW𝑘
𝑗
)
𝑇
√︁
𝑑/ℎ
Assistant
(EW𝑣
𝑗
) 𝑗 = 1, ..., ℎ (1)
𝑀𝐻𝐴(E) = (H1 ◦ ... ◦ Hℎ) W𝑐 (2)
Each head projects the input embeddings into query, key, and value subspaces using matrices
{W
𝑞
𝑗
, W𝑘
𝑗
, W𝑣
𝑗
} ⊂ R
𝑑×𝑑ℎ . The queries and keys are then used to compute the attention weights
which are used to compute weighted averages of value (different from value in observation triplet)
vectors. Finally, the outputs of all heads are concatenated and projected to original dimension with
ACM Trans. Knowl. Discov. Data., Vol. 1, No. 1, Article . Publication date: February 2022.
8 Sindhu Tipirneni and Chandan K Reddy
Fig. 3. The overall architecture of the proposed STraTS model. The Input Triplet Embedding module embeds
each observation triplet, the Contextual Triplet Embedding module encodes contextual information for the
triplets, the Fusion Self-Attention module computes time-series embedding which is concatenated with
demographics embedding and passed through a dense layer to generate predictions for target and self supervision (forecasting) tasks.
W𝑐 ∈ R
ℎ𝑑ℎ×𝑑
. The FFN layer takes the form
F(X) = 𝑅𝑒𝐿𝑈 (XW𝑓
1
b
𝑓
1
) W
𝑓
2
b
𝑓
2
(3)
with weights Wf
1
∈ R
𝑑×2𝑑
, b
f
1
∈ R
2𝑑
, Wf
2
∈ R
2𝑑×𝑑
, b
f
2
∈ R
𝑑
. Dropout, residual connections, and
layer normalization are added for every MHA and FFN layer. Also, attention dropout randomly
masks out some positions in the attention matrix before the softmax computation during training.
The output of each block is fed as input to the succeeding one, and the output of the last block
gives the contextual triplet embeddings {c1, ..., c𝑛}.
3.2.3 Fusion Self-attention. After computing contextual embeddings using a Transformer, we
fuse them using a self-attention layer to compute time-series embedding e
𝑇 ∈ R
𝑑
. This layer first
computes attention weights {𝛼1, ..., 𝛼𝑛} by passing each contextual embedding through a FFN and
computing a softmax over all the FFN outputs.
𝑎𝑖 = u
𝑇
𝑎
𝑡𝑎𝑛ℎ(W𝑎c𝑖 + b𝑎) (4)
𝛼𝑖 =
𝑒𝑥𝑝(𝑎𝑖)
Í𝑛
𝑗=1
𝑒𝑥𝑝(𝑎𝑗)
∀𝑖 = 1, ..., 𝑛 (5)
W𝑎 ∈ R
𝑑𝑎×𝑑
, b𝑎 ∈ R
𝑑𝑎
, ua ∈ R
𝑑𝑎 are the weights of this attention network which has 𝑑𝑎 neurons in
the hidden layer. The time-series embedding is then computed as
e
𝑇 =
∑︁𝑛
𝑖=1
𝛼𝑖ci
(6)
ACM Trans. Knowl. Discov. Data., Vol. 1, No. 1, Article . Publication date: February 2022.
Self-Supervised Transformer for Sparse and Irregularly Sampled Multivariate Clinical Time-Series 9
3.2.4 Demographics Embedding. We realize that demographics can be encoded as triplets with
a default value for time. However, we found that the prediction models performed better in our
experiments when demographics are processed separately by passing d through a FFN as shown
below. The demographics embedding is thus obtained as
e
𝑑 = 𝑡𝑎𝑛ℎ(W𝑑
2
𝑡𝑎𝑛ℎ(W𝑑
1
d + b
𝑑
1
) + b
𝑑
2
) ∈ R
𝑑
(7)
where the hidden layer has a dimension of 2𝑑.
3.2.5 Prediction Head. The final prediction for target task is obtained by passing the concatenation
of demographics and time-series embeddings through a dense layer with weights w𝑇
𝑜 ∈ R
𝑑
, 𝑏𝑜 ∈ R
and sigmoid activation.
𝑦˜ = 𝑠𝑖𝑔𝑚𝑜𝑖𝑑 (w
𝑇
𝑜
[e
𝑑
◦ e
𝑇
] + 𝑏𝑜 ) (8)
The model is trained on the target task using cross-entropy loss.
3.2.6 Self-supervision. We experimented with both masking and forecasting as pretext tasks for
providing self-supervision and found that forecasting improved the results on target tasks. The
forecasting task uses the same architecture as the target task except for the prediction layer i.e.,
z˜ = W𝑠 [e
𝑑
◦ e
𝑇
] + b𝑠 ∈ R
|F | (9)
A masked MSE loss is used for training on the forecasting task to account for missing values in the
forecast outputs. Thus, the loss for self-supervision is given by
L𝑠𝑠 =
1
|𝑁 ′
|
𝑁
∑︁′
𝑘=1
∑︁
|F |
𝑗=1
𝑚
𝑘
𝑗
(z˜
𝑘
𝑗 − z
𝑘
𝑗
)
2
(10)
where m𝑘
𝑗
= 1 (or m𝑘
𝑗
= 0) if the ground truth forecast z
𝑘
𝑗
is available (or unavailable) for 𝑗
𝑡ℎ variable
in 𝑘
𝑡ℎ sample. The model is first pretrained on the self-supervision task and is then fine-tuned on
the target task.
from argparse import Namespace
from models import TimeSeriesModel
import torch.nn as nn
from transformers import BertModel, BertConfig
import torch
import torch.nn.functional as F
import numpy as np
x = torch.unsqueeze(x, -1)
x = torch.matmul(x,self.W1) + self.b1[None,None,:] # bsz,max_len,int_dim
x = self.activation(x)
x = torch.matmul(x,self.W2) #bsz,max_len,hid_dim
return x
att = torch.matmul(x,self.W) + self.b[None,None,:] # bsz,max_len,int_dim
att = self.activation(att)
att = torch.matmul(att,self.u)[:,:,0] # bsz,max_len
att = att + (1-mask)torch.finfo(att.dtype).min
att = torch.softmax(att,dim=-1) # bsz,max_len
return att
if self.pretrain:
return self.forecast_final(ts_demo_emb, forecast_values, forecast_mask)
logits = self.binary_head(self.forecast_head(ts_demo_emb))[:,0] if self.finetune else self.binary_head(ts_demo_emb)[:,0]
return self.binary_cls_final(logits, labels)
understand and explain what is going on to me. keep your formatting to a minimum, there are some rendering issues going on.
The code you've provided implements the STraTS model described in the paper. The model processes sparse and irregularly sampled multivariate clinical time-series data by representing each observation as a triplet: (time, feature, value). Here's an explanation of what each part of the code is doing:
CVE Class (Continuous Value Embedding):
The CVE class creates embeddings for continuous values like time and feature values.
It uses a feed-forward neural network (FFN) that maps a single scalar input to a high-dimensional embedding vector.
During initialization, it sets up two weight matrices (W1, W2) and a bias vector (b1).
The hidden layer size is the square root of the embedding dimension (e.g., if the embedding dimension is 256, the hidden layer size would be 16).
In the forward method:
It takes the scalar input x (either time or value) and unsqueezes it to add an extra dimension.
It performs a linear transformation using W1 and b1, applies a tanh activation function, and then another linear transformation using W2 to produce the embedding vector.
FusionAtt Class (Fusion Self-Attention):
The FusionAtt class computes attention weights to combine the contextual embeddings into a single time-series embedding.
It uses an attention mechanism where it first applies a linear transformation and a tanh activation to the input embeddings.
It then projects the result to a scalar attention score using the vector u.
The forward method:
Calculates unnormalized attention scores for each time step.
Applies a softmax function to obtain normalized attention weights.
Uses these weights to compute a weighted sum of the embeddings.
Transformer Class (Contextual Triplet Embedding):
The Transformer class implements the Transformer blocks that encode contextual information among the triplets.
It has multiple layers (self.N), each consisting of multi-head attention and feed-forward sublayers.
In the forward method:
For each layer:
Computes queries (q), keys (k), and values (v) by projecting the input embeddings.
Calculates the attention scores using scaled dot-product attention.
Applies attention dropout during training.
Computes the context vectors by weighting the values with the attention scores.
Applies a feed-forward network to the context vectors.
Includes residual connections and optionally layer normalization.
Handles masking to ignore padded positions in the sequence.
Strats Class (STraTS Model):
This is the main class that brings together all components to form the STraTS model.
In __init__:
Initializes the continuous value embedding modules for time and value.
Sets up the variable embedding lookup table for categorical features.
Initializes the Transformer for contextual embedding.
Sets up the fusion attention module.
In the forward method:
Training Mode:
Randomly masks out some variables (features) to simulate missing data during training.
Triplet Embeddings:
Computes embeddings for time (time_emb), value (value_emb), and variables (vari_emb).
Sums these embeddings to get the initial triplet embedding (triplet_emb).
Contextual Embedding:
Passes the triplet embeddings through the Transformer to get contextual embeddings (contextual_emb).
Fusion Attention:
Computes attention weights over the contextual embeddings using the FusionAtt module.
Applies these weights to obtain the aggregated time-series embedding (ts_emb).
Demographics Embedding:
Processes demographic data separately and obtains a demographics embedding (demo_emb).
Final Prediction:
Concatenates the time-series embedding and demographics embedding.
Depending on the mode:
If in pretraining mode, performs a forecasting task using a separate head (forecast_head).
If in fine-tuning or evaluation mode, computes the prediction using the target task head (binary_head).
Loss Computation:
Calculates the loss based on the task (e.g., cross-entropy loss for classification).
Additional Details:
Variable Masking:
During training, the model randomly drops out entire variables (features) across the batch to improve robustness to missing data.
This is controlled by the dropout rate (self.dropout).
Handling Missing Data:
The model uses masks to handle sequences of different lengths and to ignore padded positions.
Attention masks ensure that the model doesn't attend to padding tokens.
Demographic Data:
Although demographics could be included as triplets with a default time, the model processes them separately for better performance.
Uses a feed-forward network to obtain the demographics embedding.
Self-Supervised Learning:
The model supports a self-supervised pretraining phase where it learns to forecast missing values.
This helps the model learn better representations before fine-tuning on the target task.
Overall Workflow:
Input Preparation:
The inputs are sequences of observation triplets: times (times), values (values), and variable indices (varis).
Observation masks (obs_mask) indicate which positions have valid observations.
Demographics data (demo) is also provided.
Embedding Layer:
Each type of input (time, value, variable) is embedded into a high-dimensional space.
Transformer Encoding:
The embeddings are passed through the Transformer to capture temporal and contextual relationships among observations.
Aggregation:
The contextual embeddings are combined into a single time-series embedding using fusion self-attention.
Prediction:
The time-series embedding is concatenated with the demographics embedding.
The combined embedding is passed through a prediction head to produce the final output.
Loss and Optimization:
The model computes the appropriate loss based on the task and updates the weights during training.
This implementation follows the architecture described in the paper, ensuring that continuous values are appropriately embedded, contextual relationships are captured, and the model is robust to missing and irregularly sampled data. The use of self-supervised pretraining enhances the model's ability to learn meaningful representations from the data before fine-tuning on specific target tasks.