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 this and explain how the triplet works. can feature and value take in embeddings from clinical longformer? whats the difference? explain.
Certainly! I'd be happy to help explain how the triplet works in the STraTS model and discuss whether feature and value embeddings can be taken from Clinical Longformer, along with the differences between the two approaches.
Understanding the Triplet in STraTS
STraTS Model Overview:
The STraTS (Self-supervised Transformer for Sparse and Irregular Time Series) model is designed to handle multivariate clinical time-series data, which is often sparse and irregularly sampled. It processes the data using a Transformer architecture tailored for this kind of data.
Observation Triplets:
In STraTS, the input time-series data is represented as a sequence of observation triplets, each consisting of:
( t_i ): The timestamp of the ( i^{th} ) observation.
( f_i ): The feature (variable) index of the ( i^{th} ) observation.
( v_i ): The value of the ( i^{th} ) observation.
For example, an observation triplet might represent that at time ( t_i = 12.5 ) hours, the patient's heart rate (( f_i )) was measured at ( v_i = 80 ) bpm.
Initial Triplet Embedding:
The model embeds each observation triplet into a vector representation by computing:
( \mathbf{e}_{t_i} ): The embedding of the timestamp ( t_i ).
( \mathbf{e}_{f_i} ): The embedding of the feature ( f_i ).
( \mathbf{e}_{v_i} ): The embedding of the value ( v_i ).
Here's how each component is embedded:
Feature Embedding (( \mathbf{e}_{f_i} )):
Since features are categorical variables (like lab test names or vital signs), they are embedded using an embedding layer (similar to word embeddings in NLP).
Implemented as a lookup table where each feature index maps to a learnable embedding vector.
Value Embedding (( \mathbf{e}_{v_i} )):
Values are continuous and vary widely (e.g., blood glucose levels).
STraTS uses a Continuous Value Embedding (CVE) technique:
A small feed-forward network (FFN) with learnable parameters maps the scalar value ( v_i ) to an embedding vector.
Computes a single time-series embedding ( \mathbf{e}_T ) by applying attention over the contextual embeddings.
Represents the entire time-series in a fixed-size vector.
Can Feature and Value Take Embeddings from Clinical Longformer?
Clinical Longformer Overview:
The Clinical Longformer is an adaptation of the Longformer model tailored for clinical text.
It is designed for processing long sequences of unstructured text data (e.g., clinical notes, electronic health records in text form).
It uses token embeddings, positional embeddings, and a sparse attention mechanism to handle long text sequences efficiently.
Differences in Data Types:
STraTS Data Type: Structured clinical time-series data, where observations are represented as triplets with specific numerical values and categorical features.
Clinical Longformer Data Type: Unstructured clinical text, where data is composed of tokens (words/subwords) in a sequence.
Embedding Mechanisms:
STraTS:
Feature Embedding: Embeds feature indices using an embedding layer.
Value Embedding: Embeds continuous numerical values using CVE (FFN).
Time Embedding: Embeds continuous timestamps using CVE (FFN).
Clinical Longformer:
Token Embedding: Embeds text tokens using an embedding layer (pre-trained on language modeling tasks).
Positional Embedding: Adds positional information to token embeddings.
Attention Mechanism: Handles long sequences using sparse attention patterns.
Can STraTS Use Embeddings from Clinical Longformer?
Feature Embeddings:
Possible Consideration:
If the feature names in STraTS (e.g., lab test names like "blood glucose") can be mapped to text tokens, we could, in theory, obtain embeddings from Clinical Longformer.
Challenges:
Clinical Longformer embeddings are designed for tokens in a language model context.
Features in STraTS are categorical variables representing specific measurements, not text sequences.
Using text-based embeddings may not capture the necessary domain-specific relationships between features.
Value Embeddings:
Unlikely to be Suitable:
Values in STraTS are continuous numerical measurements.
Clinical Longformer does not provide a mechanism to embed numerical values directly.
Even if numerical values are converted to text (e.g., "80"), the embeddings may not appropriately capture the quantitative relationships.
Time Embeddings:
Similar Issues:
Times are continuous and specific to the temporal dimension in time-series data.
Clinical Longformer does not have a built-in way to embed timestamps as in STraTS.
Differences Between STraTS Embeddings and Clinical Longformer Embeddings
1. Data Modality:
STraTS:
Designed for structured numerical data (time-series with numerical values and categorical features).
Clinical Longformer:
Designed for unstructured textual data (clinical notes, reports).
2. Embedding Types:
STraTS:
Feature Embedding: Categorical embedding for features.
Value Embedding: CVE for continuous numerical values.
Time Embedding: CVE for continuous timestamps.
Clinical Longformer:
Token Embedding: Word-piece embeddings trained on language modeling.
Positional Embedding: To encode the position of tokens in the sequence.
No mechanism to embed continuous numerical values directly.
3. Contextual Understanding:
STraTS:
Contextualizes observations within the time-series data, focusing on temporal patterns and relationships among measurements.
Clinical Longformer:
Contextualizes words in a text, capturing semantic and syntactic relationships.
4. Suitability for the Task:
STraTS Embeddings:
Specifically designed to capture the nuances of clinical time-series data.
The CVE allows the model to handle continuous values effectively.
Clinical Longformer Embeddings:
Optimized for natural language understanding, not numerical time-series data.
Conclusion and Recommendations
Can We Use Clinical Longformer Embeddings in STraTS?
Not Directly:
The embeddings from Clinical Longformer are not directly compatible with the requirements of STraTS.
Embedding numerical values and timestamps require specialized techniques like CVE, which are not provided by Clinical Longformer.
Possible Indirect Approaches:
Feature Names as Text:
One could attempt to use Clinical Longformer's token embeddings for feature names if they are textual (e.g., "heart rate").
This would involve mapping feature indices to text tokens and extracting embeddings.
However, this approach might not capture the domain-specific relationships needed for clinical time-series analysis.
Augmenting STraTS:
If additional unstructured text data is available (e.g., clinical notes corresponding to observations), Clinical Longformer embeddings could be integrated into the model.
This would essentially create a multimodal model combining time-series data and text.
Differences Between the Approaches:
Embedding Mechanism:
STraTS uses specialized embeddings tailored for numerical and categorical data in time-series.
Clinical Longformer embeddings are optimized for textual data.
Model Focus:
STraTS focuses on capturing temporal dynamics and handling irregularities in clinical measurements.
Clinical Longformer focuses on understanding long sequences of text with linguistic structures.
Recommendation:
Stick with STraTS Embeddings:
For clinical time-series data, it is advisable to use the embeddings designed for that purpose.
The CVE approach in STraTS effectively handles continuous numerical values and times.
Potential for Pretraining:
If concerned about embedding quality, consider pretraining the STraTS model on a large dataset to improve the embeddings within the model's architecture.
Summary
Triplet Embeddings in STraTS:
Combines time, feature, and value embeddings to represent each observation.
Uses CVE for continuous values and embeddings for categorical features.
Clinical Longformer Embeddings:
Designed for text data; unsuitable for embedding numerical values and timestamps directly.
Feature embeddings from Clinical Longformer may not capture the necessary domain relationships for time-series data.
Differences and Suitability:
The two models operate on different data types and are optimized for different tasks.
Directly using embeddings from Clinical Longformer in STraTS is not recommended due to modality mismatches.
I hope this explanation clarifies how the triplet embeddings work in STraTS and why using embeddings from Clinical Longformer may not be suitable for the feature and value embeddings in this context. Let me know if you have any further questions or need additional details!