Towards Out-of-Distribution Sequential Event Prediction: A Causal Treatment
Abstract
The goal of sequential event prediction is to estimate the next event based on a sequence of historical events, with applications to sequential recommendation, user behavior analysis and clinical treatment.
In practice, the next-event prediction models are trained with sequential data collected at one time and need to generalize to newly arrived sequences in remote future, which requires models to handle temporal distribution shift from training to testing.
In this paper, we first take a data-generating perspective to reveal a negative result that existing approaches with maximum likelihood estimation would fail for distribution shift due to the latent context confounder, i.e., the common cause for the historical events and the next event.
Then we devise a new learning objective based on backdoor adjustment and further harness variational inference to make it tractable for sequence learning problems.
On top of that, we propose a framework with hierarchical branching structures for learning context-specific representations.
Comprehensive experiments on diverse tasks (e.g., sequential recommendation) demonstrate the effectiveness, applicability and scalability of our method with various off-the-shelf models as backbones.
Introduction
Real-world problem scenarios are flooded with sequential event data consisting of chronologically arrived events which reflect certain behaviors, activities or responses.
A typical example is user activity prediction [55, 12, 61, 20, 45, 63] that aims to harness user’s recent activities to estimate future ones, which could help downstream target advertisement in online platforms (e.g., e-commerce or social networks).
Predicting future events also plays a central role in some real situations such as epidemic control [43] and clinical treatment [3] for promoting social welfare.
A common nature of (sequential) event prediction lies in the different time intervals within which training and testing data are generated.
Namely, models trained with data collected at one time are supposed to predict events in the future [58, 36, 41] where the underlying data-generating distributions may have gone through variation due to environmental changes.
However, most existing approaches [20, 14, 37, 24, 45, 39, 19, 18] overlook this issue in both problem formulation and empirical evaluation, which may leave the real problems under-resolved with model mis-specification, and result in over-estimation for model performance on real data.
As a concrete example in sequential recommenders [11], the data-generating distribution for user clicking behaviors over items is highly dependent on user preferences that are normally correlated
Winter ... ...
Past Events
Future Event
Spurious Correlation ... ...
Past Events
Prediction
Spurious Correlation ... ...
Past Events
Future Event
Causality ... ...
Past Events
Prediction
Causality
Time Line
Train (Offline) Test (Online)
T i m e
G a p
Summer
T i m e
G a p
P r i o r
A r t s
O u r s v .
s .
Prior art would spuriously correlate non-causal items and produce undesired results under a new environment in the future.
Our approach endeavors to alleviate the issue via counteracting the effects of contexts (seasons).
with some external factors, like the dynamic fashion trends in different years [13] or seasonal influences on item popularity [44].
These highly time-sensitive external factors would induce distinct user preferences leading to different behavioral data as time goes by.
This issue could also partially explain the common phenomenon of model performance drop after adaptation from offline to online environments [41, 36, 22].
Nevertheless, handling distribution shift in sequential event data poses several non-trivial challenges.
First , the temporal shift requires models’ capability for out-of-distribution (OoD) generalization [30], i.e., extrapolating from training environments to new unseen environments in remote future.
Prior art that focus on model learning and evaluation over in-distribution data may yield sub-optimal results on OoD testing instances.
Second , as mentioned before, there exist external factors that impact the generation of events.
These external factors, which we term as contexts , are unobserved in practice.
To eliminate their effects, one may also need the latent distributions that characterize how the contexts affect events generation.
Unfortunately, such information is often inaccessible due to constrained data collection and privacy issues, which requires the models to learn from pure observed sequences.
1.1 Our Contributions
To resolve these difficulties, in this paper, we adopt a generative perspective to investigate the temporal distribution shift problem and propose a new variational context adjustment approach with instantiations to solve the issue for sequential event prediction.
A generative perspective on temporal distribution shift.
We use proof-of-concept Structural
Causal Models (SCMs) to characterize the dependency among contexts, historical sequences and labels (i.e., next event type) in terms of both data generation and model prediction.
We show that contexts essentially act as a confounder, which leads the model to leverage spurious correlations and fail to generalize to data from new distributions.
See Fig.
1 for a toy example to illustrate the issue.
Variational context adjustment.
We propose a variational context adjustment approach to resolve the issue.
The resulting new learning objective has two-fold effects: 1) helping to uncover the underlying relations between latent contexts and sequences in a data-driven way, and 2) canceling out the confounding effect of contexts to facilitate our model exploring the true causality of interest (as illustrated in Fig. 1).
We also propose a mixture of variational posteriors to approximate context prior via randomly simulating pseudo input sequences.
Instantiation by a flexible framework.
We propose a framework named as CaseQ to instantiate ingredients in the objective, which could combine with most off-the-shelf sequence backbone models.
To accommodate temporal patterns under different environments, we devise a novel hierarchical branching structure for learning context-specific representations of sequences.
It could dynamically evolves its architecture to adapt for variable contexts.
Empirical results.
We carry out comprehensive experiments on three sequential event prediction tasks with valuation protocols designed for testing model performance under temporal distribution shift.
Specifically, when we enlarge time gap between training and testing data, CaseQ can alleviate performance drop by 47 .
77% w.r.t.
Normalized Discounted Cumulative Gain (NDCG) and 35 .
73% w.r.t.
Hit Ratio (HR) for sequential recommendation, which shows its robustness against temporal distribution shift.
The implementation codes will be made publicly accessible upon publication.
1.2 Related Works
Sequential Event Prediction [25] aims to predict the next event given a historical event sequence with applications including item recommendation in online commercial platforms, user behavior prediction in social networks, and epidemic control in real situations.
Early works [39, 19, 18] rely on Markov chains and Bayesian networks to learn event associations.
Later, deep learning based methods are proposed to capture non-linear temporal dynamics using CNN [46], RNN [20, 27], self-attention [24, 51], etc.
These models are usually trained offline using event sequences collected during a certain period of time.
Due to temporal distribution shifts, they may not generalize well to online environments [41, 36, 22].
Our work develops a principled approach for enhancing sequential event prediction with better robustness w.r.t.
distribution shifts via pursing causality behind data.
Out-of-Distribution Generalization [30, 4, 31, 62] deals with distinct training and testing distributions.
It is a common yet challenging problem, and has received increasing attention due to its significance [26, 42, 52, 54].
For event prediction, distribution shift inherently exists because of different time intervals from which training and testing data are generated.
Most existing sequence learning models assume that data are independent and identically distributed [20, 14, 37].
Despite various approaches of OoD generalization designed for machine learning problems in other research areas (e.g., vision and texts), it still remains under-explored for sequential event prediction and user behavior modeling.
Causal Inference [33, 35] is a fundamental way to identity causal relations among variables, and pursuit stable and robust learning and inference.
It has received wide attention and been applied in various domains e.g., computer vision [56, 28], natural language processing [40, 32] and recommender systems [57, 1].
Some existing causal frameworks for user behavior modeling [38, 16, 59, 60, 17] aim to extract causal relations based on observed or predefined patterns, yet they often require domain knowledge or side information for guidance and also do not consider temporal distribution shift. [1, 2, 6, 49] adopt counterfactual learning to overcome the effect of an ad-doc bias in recommendation task (e.g., exposure bias, popularity bias) or mitigate clickbait issue, whereas they do not focus on modeling sequential events and are still based on MLE as learning objectives.
Problem and Model Formulation
We denote X
= { 1 , 2 , · · · , M } as the space of event types, and assume each event is assigned with an event type x i ∈ X .
Events occurred in chronological order consist of a sequence S
= { x 1 , x 2 , · · · , x |S| } .
As mentioned before, the data distribution is normally affected by time-dependent external factors, i.e., context c .
We use S , Y , ˆ Y and C to denote the random variables of historical event sequence S , ground-truth next event y , predicted next event ˆ y and context c , respectively.
The data distribution can be characterized as P ( S, Y | C ) =
P ( S | C ) P
( Y | S, C ) .
Problem Formulation. Given training data { ( S i , y i ) } Ni =1 generated from data distributions with ( S i , y i ) ∼ P ( S, Y | C =
c ( i ) tr ) , where c ( i ) tr denotes the specific context when the i -th training sample is generated, we are to learn a prediction model
ˆ y i =
f ( S i ; θ ) that can generalize to testing data { ( S j , y j ) } N ′ j =1 from new distributions with ( S j , y j ) ∼ P ( S, Y | C
= c ( j ) te ) , where c ( j ) te denotes the specific context when the j -th testing sample is generated.
The distribution shift stems from different contexts that change over time, which we call temporal distribution shift in this paper.
2.1 Understanding the Limitations of Maximum Likelihood Estimation
[Figure] Most of existing approaches target maximizing the likelihood P θ ( y |S ) as the objective for optimization.
Here we use P θ ( · ) to denote the distribution induced by prediction model f θ .
Based on the definitions, we can build two Structural Causal Models (SCMs) that interpret the causal relations among 1) C , S , Y (given by datagenerating process) and 2) C , S and ˆ Y (given by model learning), as shown in Fig. 2(a) and (b).
For Fig. 2(a), the three causal relations are given by the definitions for data generation, i.e., P ( S, Y | C ) =
P ( S | C ) P
( Y | S, C ) .
We next illustrate the rationales behind the other two causal relations S → ˆ Y and C → ˆ Y .
S → ˆ Y :
This relation is induced by the prediction model ˆ y = f
( S ; θ ) that takes a historical event sequence S as input and outputs the prediction for next event ˆ y .
The relation from S to ˆ y is deterministic given fixed model parameters θ .
C → ˆ Y :
This relation is implicitly embodied in the learning process that optimizes the model parameters with a given dataset collected at one time.
By our definition, the training dataset is generated from a latent distribution affected by context c tr and the MLE algorithm yields
[Equation]
where l ( · , · ) denotes a certain loss function, e.g., cross-entropy.
This indicates that the learned model parameters θ ∗ is dependent on the distribution of c tr .
Also, due to the fact ˆ y = f
( S ; θ ) , we conclude the proof for relation from C to ˆ Y .
In short, intuitive explanations for such a causal relation lie in two facts: 1) C affects the generation of data used for model training, and 2) ˆ Y is the output of the trained model given input sequence S .
Confounding Effect of C .
The key observation is that C acts as the confounder in both Fig. 2(a) and (b), which could play a crucial role leading to undesirable testing performance of MLE-based approaches once the distribution is shifted.
As implied by the causal relations in Fig.
2(a), there exists partial information in S that is predictive for Y yet highly sensitive to C , a usually fast-changing variable in real-world scenarios.
As a result, the correlation between S and Y in previous contexts may become spurious in future ones.
This also explains the failure of MLE-based models for generalizing to data from new distributions, according to the similar causal pattern in Fig. 2(b).
We can reuse the toy example in Fig.
1 as an intuitive interpretation for the failure.
The ‘summer’ season (a context) acts as a confounder that correlates buying ‘ice cream’ (a historical event) and buying ‘T-shirt’ (a label), between which exists no obvious causal relation.
However, the model would ‘memorize’ their correlation and tend to improperly recommend ‘T-shirt’ in the ‘winter’ season (new context).
Whereas in fact the user purchases ice cream in winter most possibly because he/she is a dessert lover, in which case recommending other desserts would be a better decision.
Intervention.
To address the confounding effect of C and endow the model with robustness to temporal distribution shift, we propose to target model learning with P θ ( Y | do ( S )) instead of the conventional P θ ( Y | S ) .
As shown in Fig. 5(c), the do -operator cuts off the arrow (i.e., causal relation) coming from C to S , which essentially simulates an ideal data-generating process where sequences are generated independently from contexts.
This operation blocks the backdoor path S ← C
→ ˆ Y that spuriously correlates S and Y , and enables the model to learn the desired causal relation S → Y which is invariant to environmental change.
2.2 Variational Context Adjustment
An ideal way to compute P θ ( Y | do ( S )) is to carry out randomized controlled trial (RCT)
[34] by recollecting data from a prohibitively large quantity of random samples under any possible context, which is infeasible since we could neither control the environment nor collect data in the future.
Fortunately, there exists a statistical estimation of P θ ( Y | do ( S )) by leveraging backdoor adjustment [34], wherein the confounder C is stratified into discrete pieces C
= { c i } |C| i =1 .
By using basic rules induced by the do -operator (see derivation in Appendix A), we have:
[Equation]
Intuitively, the backdoor adjustment approximates the ideal situation via enumerating c i according to the context prior P ( C ) independent from input sequences, which could counteract the effect of C on the generation of S .
Nevertheless, optimizing with Eq.
(2) is intractable since c i is unobserved and its prior distribution P ( C ) is unknown.
Furthermore, computing Eq.
(2) requires the relation between contexts and generated sequences, which is implicit in the data-generating process behind the data.
To address the difficulty for targeting Eq.
(2), we introduce a variational distribution Q ( C | S ) as the estimation for latent contexts given input sequences.
By treating C as a latent variable and using variational inference technique, we can obtain the following tractable evidence lower bound (ELBO) as learning objective (see derivation in Appendix B):
[Equation]
where the last step is given by Jensen’s Inequality and the equality holds if and only if Q ( C | S ) exactly fits the true posterior P ( C | S, Y ) , which suggests it successfully uncovers the latent context from observed data.
The first component in Eq.
(3) is the negative reconstruction error (i.e. prediction error).
The second component is the Kullback–Leibler (KL) divergence of the variational distribution and context prior distribution.
Like [29], we could re-write the second term as a summation of the entropy of Q ( C | S ) , i.e., H [ Q ( C | S = S )] and the cross-entropy between Q ( C | S ) and the prior distribution, i.e., H [ Q ( C ) , P ( C )] .
The former enforces high variance of contexts for each event sequence, and the latter aligns the aggregated posterior with the prior.
Learnable Prior via Mixture of Posteriors. The distribution P ( C ) characterizes the true context prior in real world.
It serves to regularize Q ( C | S ) through the KL term in Eq.
Choosing an appropriate P ( C ) is important yet challenging.
One straightforward solution is to adopt a pre-defined prior [8, 56], e.g., uniform distribution.
However, such a simplistic distribution may not reflect the true context prior, and potentially lead to over-regularization [5].
An alternative way is to estimate the prior by computing the average of the variational posterior [21], i.e., P
[Equation] ( C [Equation]
However, such a method is computational expensive [47] and would often result in biased estimation given a limited quantity of training data collected within a certain time interval.
Inspired by [47] using mixture of Gaussian as a flexible and learnable prior, we propose to use a mixture of pseudo variational posteriors as an estimation:
[Equation]
where S [-
-]′
j is a randomly generated pseudo event sequence and we set R ≪ N to reduce the computational cost.
Note that the variational distribution Q ( C | S ) is given by the prediction model (see details in Section 3).
Therefore, the prior estimation by Eq.
(4) is a general reflection of how the model recognizes each type of context given uninformative inputs.
Also, the estimated prior is learned with the model in fully data-driven manner.
Model Instantiations
We next parameterize the components in Eq.
(3), i.e., P θ ( Y | S, C ) and Q ( C | S ) , and propose a flexible framework named as CaseQ by taking ‘cas’ from ‘causal’ and ‘seq’ from ‘sequence’.
Event Embedding.
Given an event sequence S = { x 1 , x 2 , · · · , x t } as input, we use an embedding to represent each type of event.
We consider a global embedding matrix H x ∈ R M × d to map each type of event into a d -dimensional embedding space:
[Equation]
where M denotes the number of event types, OneHot ( · ) : Z + → { 0 , 1 } M transforms an event into a one-hot column vector, and h 1 m ∈ R d denotes the representation for an event x m in the sequence.
Inference Unit: Context-Specific Encoder. To encode input sequences and accommodate the effect of C on prediction, we consider an encoder Φ( · ) conditioned on a specific context.
It takes a sequence of event embeddings and estimated context representation c ( t ) at time step t (given by the branching unit detailed next) as input, and outputs a sequence of hidden states:
[Equation]
where h 2 m is the m -th hidden state for the event sequence.
Assume that there are K types of contexts, i.e., C = { c k } Kk =1 and c ( t ) ∈ C .
Each type of context c k is represented as a K -dimensional one-hot column vector c k ∈ { 0 , 1 } K whose k -th dimension is 1 .
Based on the SCM in Fig.
2, the context would change the underlying mechanism of how the next event is generated in real-world.
Therefore, we consider context-specific inference units { Φ k ( · ; θ k ) }
Kk =1 as sub-networks of the encoder Φ( · ) to learn context-aware sequence representations, where Θ = { θ k } Kk =1 .
Then, we have
[Equation]
where c ( t ) [ k ] returns the k -th entry of the vector c ( t ) .
The inference unit can be specified as arbitrary off-the-shelf sequence models such as recurrent neural network (RNN) or self-attention (SA) [48].
Branching Unit: Dynamic Model Selection.
We next introduce a branching unit Ψ( · ) to parameterize the variational posterior Q ( C | S ) that aims to obtain c ( t ) given the sequence.
At each time step, it takes the sequence representation as input and outputs a probability vector q t ∈ [0 , 1] K , whose k -th entry represents the probability of the corresponding context c k , i.e., q [Equation] = Ψ( h 1 t ; Ω) , where
[Equation]
We use a d ′ -dimensional context embedding w k ∈ R d ′ to accommodate the information of each context c k by an embedding matrix H c ∈ R K × d ′ , where w k = c k ⊤ H c and d ′ = d ( d + 1) .
Then, we split each context embedding into several fix-sized parameters W k ∈ R d × d , a k ∈ R d : [Equation] = [Equation]
[Equation]
d
[Equation]
] .reshape ( d, d ) ,
[Equation]
=
[Equation]
[ d
[Equation] : d ( d + 1)] . [Equation] The attribution score s tk that measures how likely a sequence up to time step t belongs to context c k can be calculated via
[Equation]
Namely, we first project the sequence representation into a new d -dimensional space and then use dot product to measure the similarity.
The variational distribution Q ( C | S = S ) can be specified as a probability vector q t that is computed by using Softmax function over s tk , i.e., q t =
Softmax ([ s tk ] Kk =1 ; τ ) , where τ controls the confidence level.
To implement the random sampling procedure c ∼ Q ( C | S ) in Eq.
(3), one can also apply the categorical reparameterization trick that uses differentiable samples from Gumbel-Softmax [23] distribution, i.e.,
[Equation]
Then, we can revise the right term of Eq.
(7) as (cid:80) Kk = 1 q t [ k ]Φ k ([ h 11 , h 12 , · · · , h
[Equation]
θ k ) . CaseQ: a Hierarchical Branching Structure.
The aforementioned single-layered architecture requires an independent inference unit for each type of context, i.e., |C| = K , which has several drawbacks: 1) It is impractical to accommodate a large amount of context types due to limited computational resources; 2) Real-world contexts are not entirely isolated, and assuming independent parameterization may lead to over-fitting and undesired generalizability given limited training data.
To address these limitations, we further devise a hierarchical branching structure for CaseQ framework.
Instead of using a one-hot vector, we denote a context as a 0-1 matrix, i.e.,
[Equation]
where D denotes the number of layers and K denotes the number of parallel inference units in each layer.
Each row in c k is a one-hot vector indicating a certain inference unit in a layer, and each type of context corresponds to a certain combination of inference units.
The entire network could then be represented as the stack of multiple parallel inference units and branching units:
[Equation]
where q lt = Ψ l ( h lt ) , and l ∈ { 1 , 2 , · · · , D } .
The final prediction result at each time step can be obtained by ranking the relevance scores of current hidden states and event embeddings:
[Equation]
The above computation acts as a realization of P θ ( Y | S = S , C = c ) and c ∼ Q ( C | S = S ) , required by the first term in Eq.
Besides, the KL term in Eq.
(3) also requires density estimation from
Q ( C | S = S ) .
To achieve this, we use the continued Kronecker product of the probability vector q lt in each layer to represent the final variational posterior:
[Equation]
where q lt ∈ R K and ⊗ denotes Kronecker product
The produced variational posterior is a K Ddimensional vector, where each entry is the probability of a certain path (i.e., a combination of inference units across layers) in the network.
This design has some merits.
First, we could accommodate |C| =
K D types of contexts that grow exponentially w.r.t.
model depth D .
This helps to endow the model with larger capacity for learning diversified contexts.
Second, different contexts may associate with each other by sharing the same inference unit in some layers, which could help to bridge their connection and plays as an effective inductive bias that guides the model to generalize to new environments (see more details and justifications in Appendix C.
According to Eq.
(3), the final loss function can be written as
[Equation]
where α is a weight parameter for balance, q ( S ′ j ) denotes the produced variational posterior distribution with a pseudo sequence S [-
-]′ j as input, and l ( · , · ) can be arbitrary loss functions (e.g., cross-entropy) depending on specific tasks.
Experiments
The goal of our experiments is to test whether CaseQ can effectively handle temporal event prediction under distribution shift.
We thus consider several temporal prediction tasks with particular evaluation protocols for the purpose.
Datasets. We evaluate the effectiveness of CaseQ with different applications for event prediction, including sequential recommendation, ATM maintenance and user awarded badges prediction.
We use four datasets with variable length and number of event types: Movielens , Yelp , Stack Overflow and ATM .
The detailed description of datasets and their statistics are given in Appendix E.
Evaluation Protocol.
The commonly adopted leave-one-out evaluation for sequential event prediction [24, 45, 46] uses the latest event for testing, the event right before the last for validation, and the rest for training.
To test the effectiveness of CaseQ for handling temporal distribution shift, we generalize such evaluation protocol by enlarging the time gap between training and testing data.
We use the last G + 1 events for testing, the first |S| − G − 2 events for training, and the ( |S| − G − 1) -th event for validation.
We call G maximal gap size and g ∈ [0 , G ] gap size that means the number of events between the validation event and a specific testing event.
When G = 0 and g = 0 , it degrades to leave-one-out evaluation.
By increasing g in our case, we could enlarge the time gap between training and testing data, so as to simulate temporal shift in real-world scenarios where data collection and online serving are during different periods of time.
More details are in Appendix G.
Evaluation Metrics. For recommendation datasets, i.e., Movielens and Yelp, we adopt two widely used evaluation metrics:
Hit Ratio at K (HR@ K ), and Normalized Discounted Cumulative Gain at K (NDCG@ K ).
For other two low-dimensional datasets with fewer number of event types, i.e., Stack
Overflow and ATM, we use Accuracy (i.e., Precision) as the metric.
4.1 Sequential Recommendation
We adopt three sequence models as backbones for sequential recommendation: 1) GRU4Rec [20] that uses RNNs to model users’ sequential behaviors and predict the next clicked item; 2) SASRec [24] [Table] [Figure] [Table]
[Figure] [Table] [Figure] [Table]
[Figure]
[Table]
[Figure]
[Table]
[Figure]
[Table]
[Figure]
[Table]
[Figure]
that adopts Self-Attention (SA) in Transformer’s encoder for sequential recommendation; 3) SSEPT [50] that further considers user’s personalized embedding which incorporates user information into the input sequence.
We use MLE for training these models.
For fairness, our model uses the same number of layers as the baselines.
We set gap size g as 0 , 30 for Movielens and 0 , 20 for Yelp (as the average sequence length of Movielens is greater than Yelp’s).
As shown in Table 1, our approach consistently outperforms the counterparts with different backbones throughout all the cases.
While the performance degrades when we increase the gap size, CaseQ is significantly more robust to temporal distribution shift than the models trained with MLE.
The percentage of the performance drop for CaseQ is nearly half of that for the counterpart models.
Also, CaseQ is agnostic to the sequential prediction backbones and is promising for combining with other advanced architectures.
4.2 Event Prediction
We further study the performance of CaseQ in Stack Overflow and ATM datasets, which have distinct statistical features compared to sequential recommendation datasets.
We consider three commonly adopted models for predicting discrete sequential events, i.e., GRU, LSTM and Transformer [48].
We also consider two ensemble frameworks that has the same model size with ours and are built on parallel structures: 1) Ensemble [7] adopts mean pooling over the hidden states of different inference units; 2) DMoE [10] combines the hidden states by learning a gating network in each layer.
Also, we use multiple heads for Transformer to equip it with the same model size as CaseQ.
For
Stack Overflow, the gap size varies from 0 to 50 .
For ATM, it varies from 0 to 20 .
As shown in
Fig. 3, CaseQ achieves the best results throughout all the cases in both datasets.
As the gap size increases, the overall accuracy of baseline models exhibit a sharp downward trend in general, which shows the severe negative impact of temporal distribution shift.
Despite with larger model size, both ensemble-based baselines show little improvement over the single models and also suffer a serious performance drop with larger gap sizes.
In comparison, when the gap size goes large, the performance improvement of CaseQ over other competitors becomes more significant.
This suggests that our approach is indeed effective for improving the robustness of sequence models w.r.t.
temporal shift.
[Figure]
4.3 Case Study
Visualization of Temporal Shift. To further investigate temporal distribution shift, in Fig.
4 we visualize the probabilities for each type of context at different time steps of a sequence.
We set
K = 4 , D = 2 .
The two sub-figures show the results with different base models (LSTM and
Transformer).
The probability value reflects the intensity of a certain context at one time.
As shown in the figure, while some contexts dominate at the beginning, they exhibit clear variation over time.
The results imply that there indeed exists temporal distribution shift behind the data collected at different time intervals.
Therefore, prior art use the past sequential data for training may not successfully transfer to new environments in the future.
By contrast, our approach could first identifies latent contexts behind data and then alleviate its impact on learning a stable prediction model.
Learning of Context Embeddings. Context embeddings are latent representations for each type of context and dynamically affect the branching unit for selecting the proper inference unit.
Conceptually, each type of context is expected to represent an environment in physical world, so each context embedding is supposed to be informative and distinctive.
To verify whether our model could learn meaningful context representations without collapse or over-regularization, we visualize the context embeddings ( K = 3 , D = 2 ) through the training process in Fig.
5 by using dimensional reduction.
Each color corresponds to the embedding of a certain context.
While the context embeddings have the same initialized positions, they gradually separate and move towards different directions as the epochs increase.
This indicates that the model manages to learn informative context representations.
4.4 Scalability Test
We further test the scalability of CaseQ w.r.t.
the number of context types.
Fig.
6 shows the training time and inference time per mini-batch of data.
We use a single layer when the number of context types is within [1 , 6] and two layers when it further increases.
As we can see in the range of [1 , 6] , the training and inference time exhibit linear increase with a single-layer architecture.
The increasing trend goes down when we increase the model depth.
The results suggest CaseQ’s decent scalability.
4.5 Hyper-Parameter Analysis
An appropriate number of context types are important for guaranteeing the performance and generalizability of our model.
Recall that there are in total K D types of contexts, given a model whose depth (i.e. number of layers) is D and width (i.e. number of parallel inference units in a layer) is K .
Fig.shows the performance of CaseQ w.r.t.
different K and D in sequential recommendation task.
The results show that increasing K and D in a certain range is effective for improving the performance [Figure] [Figure]
[Figure] Notably, the improvements are more significant with larger gap size [Figure] which again verifies that CaseQ is helpful for addressing temporal shift.
Still, out-of-range K and D would harm the performance, which is presumably due to over-fitting.  Limitations and Conclusion
Limitations and Potential Impacts.
One of the main limitations of our variational context adjustment framework is that it stratifies discrete contexts (which may be infinitely many) into a fixed context set, in order to make the objective tractable.
However, this remains a common issue for all works that are dealing with infinitely many discrete confounders, and our framework has already made a progress in this direction increasing the size of context set to K D .
We expect to see more works to be done in this direction. Also, due to the nature of the problem setting where the context is defined as a latent and abstract factor (which is a major challenge we aim to tackle and serves as our contribution), it would be hard or even impossible to identify its meaning in the real-world. Finally, we do not foresee any direct negative societal impacts. Conclusion.
In this paper, we endeavor to deal with temporal distribution shift in sequential event prediction.
Namely, the training and testing data are generated from distinct distributions with different contexts.
We first show that existing approaches with maximum likelihood estimation would leverage spurious correlation and produce undesirable prediction.
Then we propose a new learning objective with backdoor adjustment and variation inference techniques.
Based on this, we devise a novel model framework for learning context-specific representations.
Extensive experiments demonstrate the practical efficacy of proposed method.
We hope our work could enlighten new research focus for subsequent works and inspire more frontier research in sequential event prediction against distribution shift. Acknowledgement
This work was partly supported by National Key Research and Development Program of China (2020AAA0107600), National Natural Science Foundation of China (61972250, 72061127003), and
Shanghai Municipal Science and Technology (Major) Project (2021SHZDZX0102, 22511105100).
A Derivation of Backdoor Adjustment
We show the derivation of backdoor adjustment for the proposed causal graph in Fig.
2 based on the rules with do -calculus [33].
Consider a directed acyclic graph G with three nodes: X , Y and Z .
We denote G X as the intervened causal graph by cutting off all arrows coming into X , and G X as the graph by cutting off all arrows going out from X .
For any interventional distribution compatible with
G , we have the following two rules:
Rule 1.
Action/observation exchange:
[Equation]
Rule 2.
Insertion/deletion of actions:
[Equation]
We could derive the interventional distribution via:
[Equation]
where the first step follows the law of total probability, the second step applies Rule 2, and the last step applies Rule 1.
B Derivation of Variational Context Adjustment
We derive the variational context adjustment in Eq.
We re-write the logarithm of interventional distribution P θ ( Y | do ( S = S ))
as log E c ∼ P ( C ) [ P θ ( Y | S = S , C = c )] .
We introduce a variational distribution Q ( C | S = S ) as an approximation of the true posterior
P ( C | S = S , Y = y ) .
By using variational inference, we derive a tractable lower bound as objective:
[Equation]
where the third step is given by Jensen Inequality
[Equation]
C More Discussions
We gather the continued Kronecker product of the probability vector q lt in each layer to compute the final variational posterior q t :
[Equation]
[Figure]
Kronecker product is a generalization of the outer product from vectors to matrices.
The entries of q t denotes the probability for every possible combination of inference units (termed as path ) at time step t .
For example, consider D = 3 , K = 3 .
We have q lt ∈ R 3 , q 1 t ⊗ q 2 t ⊗ q 3 t ∈ R 3 × R 3 × R 3 , and q t ∈ R 27 .
The i -th element in q t denotes the probability of a certain path in the network, representing the probability of a type of context Q ( C
= c i | S = S ) .
Suppose i =
( xyz ) 3 is a ternary number, the path corresponds to the combination of z / y / x -th inference unit at the first/second/third layer.
How CaseQ generalizes to novel context?
As mentioned before, one advantage of such a design is that it could associate different types of contexts through shared inference units in some layers.
By this way, we build links between majority (seen) contexts and minority (unseen) contexts.
It can guide the model to generalize to future environments when the minority context may become the major one or unseen context occurs.
We provide an example in Fig.
8 for further illustration.
In training stage, the latent contexts gradually change over time (and so as the corresponding path in the network).
During this time, c 2 and c 3 are majority contexts, c 4 is the minority context, and c 1 is a unseen one.
Despite the imbalanced contexts, each inference unit as a module is relatively equally trained.
Therefore, in testing stage, when c 1 and c 4 become majority contexts, our model can still generalize well by using well-trained inference units as modules.
D Comparison with Existing Causal Models
We compare CaseQ with existing causal models for sequence learning and user behavior modeling.
Some existing methods [38, 16, 59, 60, 17] aim to extract causal relations based on observed or predefined patterns, yet they often require domain knowledge or side information for guidance and also do not consider temporal distribution shift.
[1, 2, 6, 49] adopt counterfactual learning to overcome the effect of an ad-doc bias in recommendation task (e.g., exposure bias, popularity bias) or mitigate clickbait issue.
Differently, they do not focus on modeling sequential events and are still based on maximum likelihood estimation as learning objectives.
There are also few recent works that attempt to adopt causal inference to de-noise input sequences in sequential user behaviors[57].
Yet, they overlook the distribution shift and have distinct research focus compared with this paper.
E Dataset Descriptions
Movielens Movielens [15] is a widely used benchmark dataset for sequential recommendation evaluation.
It contains one million ratings of 3900 movies made by 6040 users.
We use each user’s rating records as implicit feedbacks and construct a sequence of rated movies for each user in the order of timestamps, where each rating for a movie is treated as an event.
[Table]
Yelp Yelp is a dataset for business recommendation, provided by the Yelp Dataset Challenge 2 .
After pre-processing and filtering, it contains 648 , 687 reviews for businesses by 23 , 057 users.
We treat all user reviews as events and sort them chronically into sequences.
Stack Overflow This dataset is collected from a question answering website Stack Overflow [9].
It includes 480 , 000 records of awarded badges of 6 , 000 users during two years between 2012 and 2014 .
Each awarded badge is treated as an event.
The task is to predict the next awarded badge of users.
ATM This dataset is collected from 1554 ATMs owned by an anonymous global bank headquartered in North America [53], which includes 7 types of events including 6 error types.
It has a total number of 552 , 215 events.
The task is to predict future events for better maintenance support services.
The statistics of these datasets are summarized in Table 2.
F Implementation Details
We implement CaseQ with PyTorch.
All parameters are initialized with Xavier initialization method.
We train the model by Adam optimizer.
{+All the models are trained from scratch without any pre-training on GTX 
+}
GPU with 11G memory.
For comparative methods, we refer to the hyper-parameter settings in their papers and also finetune them on different datasets.
For sequences whose length is greater than 100 , we only consider the most recent 100 events to speed up training.
We run all experiments 5 times and take the average value.
G Evaluation Protocol and Problem Setting
Given a dataset consists of N event sequences, i.e., D = {S i } Ni =1 , where S i = { x i, 1 , x i, 2 , · · · , x i, |S i | } .
We use S i
[: t ] to denote the first t events in the sequence and S i [ − t :] to denote the last t events.
The training, validation and test sets are:
[Equation]
where G is the maximal gap size.
When the sequence length is less than or equal to G + 3 , we use the whole sequence for training.
Given a specific gap size g ∈ [0 , G ] , we evaluate the model performance on a test subset:
[Equation]
By increasing g , we could enlarge the time gap between training and testing data, so as to simulate temporal distribution shift in real-world scenario where data collection and online serving are during different periods of time, and evaluate model’s effectiveness against distribution shift.
We are interested in the model performance drop as a metric to evaluate the robustness to distribution shift.
Note that evaluations with different g are conducted simultaneously using the same model to control variates.
When G = 0 and g = 0 , this evaluation method exactly degrades to widely used leave-one-out evaluation protocol that is widely used in recommendation tasks [24, 45, 46].