Self-attention with Functional Time Representation Learning

11/28/2019 ∙ by Da Xu, et al. ∙ WALMART LABS 0

Sequential modelling with self-attention has achieved cutting edge performances in natural language processing. With advantages in model flexibility, computation complexity and interpretability, self-attention is gradually becoming a key component in event sequence models. However, like most other sequence models, self-attention does not account for the time span between events and thus captures sequential signals rather than temporal patterns. Without relying on recurrent network structures, self-attention recognizes event orderings via positional encoding. To bridge the gap between modelling time-independent and time-dependent event sequence, we introduce a functional feature map that embeds time span into high-dimensional spaces. By constructing the associated translation-invariant time kernel function, we reveal the functional forms of the feature map under classic functional function analysis results, namely Bochner's Theorem and Mercer's Theorem. We propose several models to learn the functional time representation and the interactions with event representation. These methods are evaluated on real-world datasets under various continuous-time event sequence prediction tasks. The experiments reveal that the proposed methods compare favorably to baseline models while also capturing useful time-event interactions.



There are no comments yet.


page 17

page 18

This week in AI

Get the week's most popular data science and artificial intelligence research sent straight to your inbox every Saturday.

1 Introduction

Attention mechanism, which assumes that the output of an event sequence is relevant to only part of the sequential input, is fast becoming an essential instrument for various machine learning tasks such as neural translation

(Bahdanau et al., 2014), image caption generation Xu et al. (2015) and speech recognition Chorowski et al. (2015)

. It works by capturing the importance weights of the sequential inputs successively and is often used as an add-on component to base models such as recurrent neural networks (RNNs) and convolutional neural networks (CNNs)

Chen et al. (2017). Recently, a seq-to-seq model that relies only on an attention module called ’self-attention’ achieved state-of-the-art performance in neural translation Vaswani et al. (2017). It detects attention weights from input event sequence and returns the sequence representation. Without relying on recurrent network structures, self-attention offers appealing computational advantage since sequence processing can be fully parallelized. Key to the original self-attention module is positional encoding, which maps discrete position index

to a vector in

and can be either fixed or jointly optimized as free parameters. Positional encoding allows self-attention to recognize ordering information. However, it also restricts the model to time-independent or discrete-time event sequence modelling where the difference in ordered positions can measure distance between event occurrences.

In continuous-time event sequences, the time span between events often has significant implications on their relative importance for prediction. Since the events take place aperiodically, there are gaps between the sequential patterns and temporal patterns. For example, in user online behaviour analysis, the dwelling time often indicates the degree of interest on the web page while sequential information considers only the ordering of past browsing. Also, detecting interactions between temporal and event contexts is an increasingly important topic in user behavioural modelling Li et al. (2017). In online shopping, transactions usually indicate long-term interests, while views are often short-termed. Therefore future recommendations should depend on both event contexts and the timestamp of event occurrences.

To effectively encode the event contexts and feed them to self-attention models, the discrete events are often embedded into a continuous vector space

Bengio et al. (2013). After training, the inner product of their vector representations often reflect relationship such as similarity. In ordinary self-attention, the event embeddings are often added to positional encoding to form an event-position representation Vaswani et al. (2017). Therefore, it is natural and straightforward to think about replacing positional encoding with some functional mapping that embeds time into vector spaces.

However, unlike positional encoding where representations are needed for only a finite number of indices, time span is a continuous variable. The challenges of embedding time are three folds. Firstly, a suitable functional form that takes time span as input needs to be identified. Secondly, the functional form must be properly parameterized and can be jointly optimized as part of the model. Finally, the embedded time representation should respect the function properties of time itself. To be specific, relative time difference plays far more critical roles than absolute timestamps, for both interpolation or extrapolation purposes in sequence modelling. Therefore, the relative positions of two time representations in the embedding space should be able to reflect their temporal difference. The contributions of our paper are concluded below:

  • We propose the translation-invariant time kernel which motivates several functional forms of time feature mapping justified from classic functional analysis theories, namely Bochner’s Theorem Loomis (2013) and Mercer’s Theorem Mercer (1909)

    . Compared with the other heuristic-driven time to vector methods, our proposals come with solid theoretical justifications and guarantees.

  • We develop feasible time embeddings according to the time feature mappings such that they are properly parameterized and compatible with self-attention. We further discuss the interpretations of the proposed time embeddings and how to model their interactions with event representations under self-attention.

  • We evaluate the proposed methods qualitatively and quantitatively and compare them with several baseline methods in various event prediction tasks with several datasets (two are public). We specifically compare with RNNs and self-attention with positional encoding to demonstrate the superiority of the proposed approach for continuous-time event sequence modelling. Several case studies are provided to show the time-event interactions captured by our model.

2 Related Work

The original self-attention uses dot-product attention Vaswani et al. (2017), defined via:


where denotes the queries, denotes the keys and denotes the values (representations) of events in the sequence. Self-attention mechanism relies on the positional encoding to recognize and capture sequential information, where the vector representation for each position, which is shared across all sequences, is added or concatenated to the corresponding event embeddings. The above , and matrices are often linear (or identity) projections of the combined event-position representations. Attention patterns are detected through the inner products of query-key pairs, and propagate to the output as the weights for combining event values. Several variants of self-attention have been developed under different use cases including online recommendation Kang and McAuley (2018), where sequence representations are often given by the attention-weighted sum of event embeddings.

To deal with continuous time input in RNNs, a time-LSTM model was proposed with modified gate structures Zhu et al. (2017)

. Classic temporal point process also allows the usage of inter-event time interval as continuous random variable in modelling sequential observations

Zhao et al. (2015). Several methods are proposed to couple point process with RNNs to take account of temporal information Xiao et al. (2017b, a); Mei and Eisner (2017); Du et al. (2016). In these work, however, inter-event time intervals are directly appended to hidden event representations as inputs to RNNs. A recent work proposes a time-aware RNN with time encoding Li et al. (2017).

The functional time embeddings proposed in our work have sound theoretical justifications and interpretations. Also, by replacing positional encoding with time embedding we inherit the advantages of self-attention such as computation efficiency and model interpretability. Although in this paper we do not discuss how to adapt the function time representation to other settings, the proposed approach can be viewed as a general time embedding technique.

3 Preliminaries

Embedding time from an interval (suppose starting from origin) to is equivalent to finding a mapping . Time embeddings can be added or concatenated to event embedding , where gives the vector representation of event , for a total of events. The intuition is that upon concatenation of the event and time representations, the dot product between two time-dependent events and becomes . Since represents relationship between events, we expect that captures temporal patterns, specially those related with the temporal difference as we discussed before. This suggests formulating temporal patterns with a translation-invariant kernel with as the feature map associated with .

Let the kernel be where and for some . Here the feature map captures how kernel function embeds the original data into a higher dimensional space, so the idea of introducing the time kernel function is in accordance with our original goal. Notice that the kernel function is positive semidefinite (PSD) since we have expressed it with a Gram matrix. Without loss of generality we assume that is continuous, which indicates that is translation-invariant, PSD and also continuous.

So the task of learning temporal patterns is converted to a kernel learning problem with as feature map. Also, the interactions between event embedding and time can now be recognized with some other mappings as , which we will discuss in Section 6. By relating time embedding to kernel function learning, we hope to identify

with some functional forms which are compatible with current deep learning frameworks, such that computation via bask-propagation is still feasible. Classic functional analysis theories provides key insights for identifying candidate functional forms of

. We first state Bochner’s Theorem and Mercer’s Theorem and briefly discuss their implications.

Theorem 1 (Bochner’s Theorem).

A continuous, translation-invariant kernel on is positive definite if and only if there exists a non-negative measure on such that

is the Fourier transform of the measure.

The implication of Bochner’s Theorem is that when scaled properly we can express with:


where . Since the kernel

and the probability measure

are real, we extract the real part of (2) and obtain:


With this alternate expression of kernel function , the expectation term can be approximated by Monte Carlo integral Rahimi and Recht (2008). Suppose we have samples drawn from

, an estimate of our kernel

can be constructed by . As a consequence, Bochner’s Theorem motivates the finite dimensional feature map to via:

such that .

So far we have obtained a specific functional form for , which is essentially a random projection onto the high-dimensional vector space of i.i.d random variables with density given by , where each coordinate is then transformed by trigonometric functions. However, it is not clear how to sample from the unknown distribution of . Otherwise we would already have according to the Fourier transformation in (2). Mercer’s Theorem, on the other hand, motivates a deterministic approach.

Theorem 2 (Mercer’s Theorem).

Consider the function class where is compact. Suppose that the kernel function is continuous with positive semidefinite and satisfy the condition

, then there exist a sequence of eigenfunctions

that form an orthonormal basis of

, and an associated set of non-negative eigenvalues

such that


where the convergence of the infinite series holds absolutely and uniformly.

Mercer’s Theorem provides intuition on how to embed instances from our functional domain into the infinite sequence space . To be specific, the mapping can be defined via , and Mercer’s Theorem guarantees the convergence of .

The two theorems have provided critical insight behind the functional forms of feature map . However, they are still not applicable. For the feature map motivated by Bochner’s Theorem, let alone the infeasibility of sampling from unknown , the use of Monte Carlo estimation brings other uncertainties, i,e how many samples are needed for a decent approximation. As for the feature map from Mercer’s Theorem, first of all, it is infinite dimensional. Secondly, it does not possess specific functional forms without making additional assumptions. The solutions to the above challenges are discussed in the next two sections.

4 Bochner Time Embedding

Feature maps specified by Origin Parameters Interpretations of
Bochner’s : location-scale parameters specified for the reparametrization trick. : converts the sample (drawn from auxiliary distribution) to target distribution under location-scale parameter .
Bochner’s : parameters for the inverse CDF . : the sample drawn from the auxiliary distribution.
Bochner’s : transformed samples under non-parametric inverse CDF transformation. : the sample of the underlying distribution in Bochner’s Theorem.
Mercer’s : the Fourier coefficients of corresponding , for . : the frequency for kernel function (can be parameters).
Table 1: The proposed functional forms of the feature map motivated from Bochner’s and Mercer’s Theorem, with explanations of free parameters and interpretation of .

A practical solution to effectively learn the feature map suggested by Bochner’s Theorem is to use the ’reparameterization trickKingma and Welling (2013). Reparameterization trick provides ideas on sampling from distributions by using auxiliary variable which has known independent marginal distribution .

For ’location-scale’ family distribution such as Gaussian distribution, suppose

, then with the auxiliary random variable , can be reparametrized as . Now samples of are transformed from samples of , and the free distribution parameters and can be optimized as part of the whole learning model. With Gaussian distribution, the feature map suggested by Bochner’s Theorem can be effectively parameterized by and , which are also the inputs to the functions that transforms the sample from the auxiliary distribution to a sample of target distribution (Table 1). A potential concern here is that the ’location-scale’ family may not be rich enough to capture the complexity of temporal patterns under Fourier transformation. Indeed, the Fourier transform of a Gaussian function in the form of

is another Gaussian function. An alternate approach is to use inverse cumulative distribution function CDF transformation.


be the inverse CDF of some probability distribution (if exists), then for

sampled from uniform distribution, we can always use

to generate samples of the desired distribution. This suggests parameterizing the inverse CDF function as with some functional approximators such as neural networks or flow-based CDF estimation methods including normalizing flow Rezende and Mohamed (2015) and RealNVP Dinh et al. (2016) (see the Appendix for more discussions). As a matter of fact, if the samples are first drawn (following either transformation method) and held fixed during training, we can consider using non-parametric transformations. For sampled from auxiliary distribution, let , for some non-parametric inverse CDF . Since are fixed, learning amounts to directly optimize the transformed samples as free parameters.

In short, the Bochner’s time feature maps can be realized with reparametrization trick or parametric/nonparametric inverse CDF transformation. We refer to them as Bochner time encoding. In Table 1, we conclude the functional forms for Bochner time encoding and provides explanations of the free parameters as well as the meanings of . A sketched visual illustration is provided in the left panel of Table 2. Finally, we provide the theoretical justification that with samples drawn from the corresponding distribution , the Monte Carlo approximation converges uniformly to the kernel function with high probability. The upper bound stated in Claim 1 provides some guidelines for the number of samples needed to achieve a good approximation.

Claim 1.

Let be the corresponding probability measure stated in Bochner’s Theorem for kernel function . Suppose the feature map is constructed as described above using samples , we have


where is the second momentum with respect to .

The proof is provided in supplement material.

Therefore, we can use samples (at the order of hundreds if ) from to have with any probability.

5 Mercer Time Embedding

Mercer’s Theorem solves the challenge of embedding time span onto a sequence space, however, the functional form of is unknown and the space is infinite-dimensional. To deal with the first problem, we need to make an assumption on the periodic properties of to meet the condition in Proposition 1, which states a fairly straightforward formulation of the functional mapping .

Proposition 1.

For kernel function that is continuous, PSD and translation-invariant with , suppose is a even periodic function with frequency , i.e and for all and integers , the eigenfunctions of are given by the Fourier basis.

The proof of Proposition 1 is provided in supplement material.

Notice that in our setting the kernel is not necessarily periodic. Nonetheless we may assume that the temporal patterns can be detected from a finite set of periodic kernels , where each is a continuous, translation-invariant and PSD kernel further endowed with some frequency . In other words, we project the unknown kernel function onto a set of periodic kernels who have the same properties as .

According to Proposition 1 we immediately see that for each periodic kernel the eigenfunctions stated in Mercer’s Theorem are given by: , , with giving the corresponding Fourier coefficients. Therefore we have the infinite dimensional Mercer’s feature map for each :

where we omit the dependency of all on for notation simplicity.

One significant advantage of expressing by Fourier series is that they often have nice truncation properties, which allows us to use the truncated feature map without loosing too much information. It has been shown that under mild conditions the Fourier coefficients decays exponentially to zero Widom (1964), and classic approximation theory guarantees a uniform convergence bound for truncated Fourier series Jackson (1930) (see Appendix for discussions). As a consequence, we propose to use the truncated feature map , and thus the complete Mercer’s time embedding is given by:


Therefore Mercer’s feature map embeds the periodic kernel function into the high-dimensional space spanned by truncated Fourier basis under certain frequency. As for the unknown Fourier coefficients , it is obvious that learning the kernel functions is in form equivalent to learning their corresponding coefficients. To avoid unnecessary complications, we treat as free parameters.

Last but not least, we point out that the set of frequencies that specifies each periodic kernel function should be able to cover a broad range of bandwidths in order to capture various signals and achieve good approximation. They can be either fixed or jointly optimized as free parameters. In our experiments they lead to similar performances if properly initialized, such as using a geometrically sequence: to cover with a focus on high-frequency regions. The sketched visual illustration is provided in the right panel of Table 2.

Bochner time embedding Mercer time embedding
Table 2: Sketched visual illustration of the proposed Bochner and Mercer time embedding ( and ) for a specific with . In right panel the scale of sine and cosine waves decreases as their frequency gets larger, which is a common phenomenon for Fourier series.

6 Time-event Interaction

Learning time-event interaction is crucial for continuous-time event sequence prediction. After embedding time span into finite-dimensional vector spaces, we are able to directly model interactions using time and event embeddings. It is necessary to first project the time and event representations onto the same space. For an event sequence we concatenate the event and time representations into where , and project them into the query, key and value spaces. For instance, to consider only linear combinations of event and time representations in query space, we can simply use

. To capture non-linear relations hierarchically, we may consider using multilayer perceptrons (MLP) with activation functions, such as


is the rectified linear unit. Residual blocks can also be added to propagate useful lower-level information to final output. When predicting the next time-dependent event

, to take account of the time lag between each event in input sequence and target event we let and use as time representations. This does not change the relative time difference between input events, i.e. for , and now the attention weights and prediction becomes a function of next occurrence time.

7 Experiment and Result

We evaluate the performance of the proposed time embedding methods with self-attention on several real-world datasets from various domains. The experiemnts aim at quantitatively evaluating the performance of the four time embedding methods, and comparing them with baseline models.

7.1 Data Sets

  • Stack Overflow111 dataset records user’s history awarded badges in a question-answering website. The task is to predict the next badge the user receives, as a classification task.

  • MovieLens222 is a public dataset consists of movie rating for benchmarking recommendations algorithms Harper and Konstan (2015). The task is to predict the next movie that the user rates for recommendation.

  • dataset is obtained from Walmart’s online e-commerce platform in the U.S333 It contains the session-based search, view, add-to-cart and transaction information with timestamps for each action from selected users. The task is to predict the next-view item for recommendation. Details for all datasets are provided in supplemnetary meterial.

Data preparation - For fair comparisons with the baselines, on the MovieLens dataset we follow the same prepossessing steps mentioned in Kang and McAuley (2018). For users who rated at least three movies, we use their second last rating for validation and their last rated movie for testing. On the stack overflow dataset we use the same filtering procedures described in Li et al. (2017) and randomly split the dataset on users into training (80%), validation (10%) and test (10%). On the dataset we filter out users with less than ten activities and products that interacted with less than five users. The training, validation and test data are splited based on session starting time chronically.

7.2 Baselines and Model configurations

We compare the proposed approach with LSTM, the time-aware RNN model (TimeJoint) Li et al. (2017) and recurrent marked temporal point process model (RMTPP) Du et al. (2016) on the Stack Overflow dataset. We point out that the two later approaches also utilize time information. For the above three models, we reuse the optimal model configurations and metrics (classification accuracy) reported in Li et al. (2017) for the same Stack Overflow dataset.

For the recommendation tasks on MovieLens dataset, we choose the seminal session-based RNN recommendation model (GRU4Rec) Hidasi et al. (2015), convolutional sequence embedding method (Caser) Tang and Wang (2018) and translation-based recommendation model (TransRec) Kang and McAuley (2018) as baselines. These position-aware sequential models have been shown to achieve cutting-edge performances on the same MovieLens dataset Kang and McAuley (2018). We also reuse the metrics - top K hitting rate (Hit@K) and normalized discounted cumulative gain (NDCG@K), as well as the optimal model configurations reported in Kang and McAuley (2018).

On the dataset, other than GRU4Rec and TransRec, we compare with an attention-based RNN model RNN+attn. The hyper-parameters of the baselines are tuned for optimal performances according to the Hit@10 metric on the validation dataset. The outcomes are provided in Table 3.

As for the proposed time embedding methods, we experimented on the Bochner time embedding with the reparameterization trick

using normal distribution (

Bochner Normal), the parametric inverse CDF transformation (Bochner Inv CDF) with MLP, MLP + residual block, masked autoregressive flow (MAF) Papamakarios et al. (2017) and non-volume preserving transformations (NVP) Dinh et al. (2016), the non-parametric inverse CDF transformation (Bochner Non-para), as well as the Mercer time embedding. For the purpose of ablation study, we compare with the original positional encoding self-attention (PosEnc) for all tasks (Table 3). We use for both Bochner and Mercer time embedding, with the sensitivity analysis on time embedding dimensions provided in appendix. We treat the dimension of Fourier basis for Mercer time embedding as hyper-parameter, and select from according to the validation Hit@10 as well. When reporting the results in Table 3, we mark the model configuration that leads to the optimal validation performance for each of our time embedding methods. Other configurations and training details are provided in appendix.

7.3 Experimental results

Stack Overflow
Method LSTM TimeJoint RMTPP PosEnc Bochner Normal Bochner Inv CDF Bochner Non-para Mercer
Accuracy 46.03(.21) 46.30(.23) 46.23(.24) 44.03(.33) 44.89(.46) 44.67(.38) 46.27(0.29) 46.83(0.20)
config NVP
Method GRU4Rec Caser TransRec - - - - -
Hit@10 75.01(.25) 78.86(.22) 64.15(.27) 82.45(.31) 81.60(.69) 82.52(.36) 82.86(.22) 82.92 (.17)
NDCG@10 55.13(.14) 55.38(.15) 39.72(.16) 59.05(.14) 59.47(.56) 60.80(.47) 60.83(.15) 61.67 (.11)
config MAF data
Method GRU4Rec RNN+attn TransRec - - - - -
Hit@5 4.12(.19) 5.90(.17) 7.03(.15) 8.63(.16) 4.27(.91) 9.04(.31) 9.25(.15) 10.92(.13)
NDCG@5 4.03(.20) 4.66(.17) 5.62(.17) 6.92(.14) 4.06(.94) 7.27(.26) 7.34(.12) 8.90(.11)
Hit@10 6.71(.50) 9.03(.44) 10.38(.41) 12.49(.38) 7.66(.92) 12.77(.65) 13.16(.41) 14.94(.31)
NDCG@10 4.97(.31) 7.36(.26) 8.72(.26) 10.84(.26) 6.02(.99) 10.95(.74) 11.36(.27) 12.81(.22)
config MAF
Table 3:

Performance metrics for the proposed apporach and baseline models. All results are converted to percentage by multiplying by 100, and the standard deviations computed over ten runs are given in the parenthesis. The proposed methods and the best outcomes are highlighted in bold font. The

config rows give the optimal model configuration for Bochner Inv CDF (among using MLP, MLP + redisual block, MAF and NVP as CDF learning method) and Mercer (among ).

We observe in Table 3 that the proposed time embedding with self-attention compares favorably to baseline models on all three datasets. For the Stack Overflow and dataset, Mercer time embedding achieves best performances, and on MovieLens dataset the Bochner Non-para outperforms the remaining methods. The results suggest the effectiveness of the functional time representation, and the comparison with positional encoding suggests that time embedding are more suitable for continuous-time event sequence modelling. On the other hand, it appears that Bochner Normal and Bochner Inv CDF

has higher variances, which might be caused by their need for sampling steps during the training process. Otherwise,

Bochner Inv CDF has comparable performances to Bochner Non-para across all three datasets. In general, we observe better performances from Bochner Non-para time embedding and Mercer time embedding. Specifically, with the tuned Fourier basis degree , Mercer’s method consistently outperforms others across all tasks. While , the dimension of time embedding, controls how well the bandwidth of [] is covered,

controls the degree of freedom for the Fourier basis under each frequency. When

is fixed, larger may lead to overfitting issue for the time kernels under certain frequencies, which is confirmed by the sensitivity analysis on provided in Figure 1b.

Figure 1: (a). We show the results of Bochner Inv CDF on the Movielens and dataset with different distributional learning methods. (b). The sensitivity analysis on Mercer time encoding on the Movielens dataset by varying the degree of Fourier basis under different dimension .
(a) The temporal patterns in average attention weight decay on the last interacted product after different user actions, as time elapsed.
(b) The temporal patterns in average attention weight decay on the last viewed product from different departments, as time elapsed.
(c) The prediction of future attention weight on the last interacted product as a function of time and different user actions.
Figure 2: Temporal patterns and time-event interactions captured by time and event representations on the dataset.

In Figure 2, we visualize the average attention weights across the whole population as functions of time and user action or product department on the dataset, to demonstrate some of the useful temporal patterns captured by the Mercer time embedding. For instance, Figure 1(a) shows that when recommending the next product, the model learns to put higher attention weights on the last searched products over time. Similarly, the patterns in Figure 1(b) indicate that the model captures the signal that customers often have prolonged or recurrent attentions on baby products when compared with electronics and accessories. Interestingly, when predicting the attention weights by using future time points as input (Figure 1(c)), we see our model predicts that the users almost completely lose attention on their most recent purchased products (which is reasonable), and after a more extended period none of the previously interacted products matters anymore.

Discussion. By employing state-of-the-art CDF learning methods, Bochner Inv CDF achieves better performances than positional encoding and other baselines on Movlielens and dataset (Figure 1a). This suggests the importance of having higher model complexity for learning the in Bochner’s Thm, and also explains why Bochner Normal fails since normal distribution has limited capacity in capturing complicated distributional signals. On the other hand, Bochner Non-para is actually the special case of Mercer’s method with and no intercept. While Bochner’s methods originate from random feature sampling, Mercer’s method grounds in functional basis expansion. In practice, we may expect Mercer’s method to give more stable performances since it does not rely on distributional learning and sampling. However, with advancements in Bayesian deep learning and probabilistic computation, we may also expect Bochner Inv CDF to work appropriately with suitable distribution learning models, which we leave to future work.

8 Conlusion

We propose a set of time embedding methods for functional time representation learning, and demonstrate their effectiveness when using with self-attention in continuous-time event sequence prediction. The proposed methods come with sound theoretical justifications, and not only do they reveal temporal patterns, but they also capture time-event interactions. The proposed time embedding methods are thoroughly examined by experiments using real-world datasets, and we find Mercer time embedding and Bochner time embedding with non-parametric inverse CDF transformation giving superior performances. We point out that the proposed methods extend to general time representation learning, and we will explore adapting our proposed techniques to other settings such as temporal graph representation learning and reinforcement learning in the our future work.


Appendix A Appendix

a.1 Proof of Claim 1


Define the score . The goal is to derive a uniform upper bound for . By assumption

is an unbiased estimator for

, i.e. . Due to the translation-invariant property of and , we let , where for all . Also we define . Therefore , and we use as the shorthand notation. The LHS in (1) now becomes .

Note that with for . So is a finite cover of . Define , then for any , we have


where (since is differentiable) with the maximum achieved at . So we may bound the two events separately.

For we simply notice that trigeometric functions are bounded between , and therefore . The Hoeffding’s inequality for bounded random variables immediately gives us:

So applying the Hoeffding-type union bound to the finite cover gives


For the other event we first apply Markov inequality and obtain:


Also, since , we have


where is the second momentum with respect to .

Combining (8), (9) and (8) gives us:


It is straightforward to examine that the RHS of (11) is a convex function of and is minimized by . Plug back to (11) and we obtain bound stated in Claim 1. ∎

a.2 Proof of Proposition 1


We first define the kernel linear operator on via , where is a non-negative measure over . For notation simplicity we do not explicitly index with its frequency. The more complete statement of Mercer’s Theorem is that under the conditions specified in Theorem 2,


which leads to the representation of the kernel as .

Therefore we only need to show the Fourier basis gives the eigenfunctions of the kernel linear operator . Without loss of generality we assume the frequency is , i.e. is a even periodic function on and extend to the real line by for . So now the kernel linear operator is expressed by:


Now we show that the eigenfunctions for the kernel linear operator are given by Fourier basis. Suppose for , we have


where in we use a change of variable and utilize the periodic property of and the cosine function. In we apply the sum formula of trigonometric functions, and in we simply use the fact that because is an even function. Similar arguments show that for are also the eigenfunctions for . Since the Fourier basis form a complete orthonormal basis of , according to the complete Mercer’s Theorem we see that the eigenfunctions of are exactly given by the Fourier basis. ∎

a.3 Fourier series under truncation

In this part we briefly discuss the exponential decay for the eigenvalues and the uniform bound on approximation error for truncated Fourier series mentioned in Section 5. Notice that Bochner’s Theorem also applies to the periodic kernels () stated in Mercer time embedding, such that

where is the scaling constant such that is a probability measure. It has been shown that if for some , then there is a constant such that the Fourier coefficients satisfy: as Widom [1964].

As for the approximation error of truncated Fourier series, first we use to denote the partial sum of the Fourier series for up to the order. According to the Corollary I in Jackson [1930], if is Lipschitz, then we have the uniform convergence bound

for all under some constant .

The above classical results suggest the exponential decay of the Fourier coefficients as well as the uniform convergence property of the truncated Fourier series and further validate the Mercer time embedding.

a.4 Flow-based distribution learning

Here we briefly introduce the idea of constructing and sampling from an arbitrarily complex distribution from a known auxiliary distribution by a sequence of invertible transformations. It is motivated by the basic change of variable theorem, which we state below.

Given an auxiliary random variable following some know distribution , suppose another random variable is constructed via a one-to-one mapping from : , then the density function of is given by:


We can parameterize the one-to-one function with free parameters and optimize them over the observed evidence such as by maximizing the log-likelihood. By stacking a sequence of one-to-one mappings, i.e. , we can construct complicated density functions. It is easy to show by chaining that is given by:


A sketched graphical illustration of the concept is shown in Figure 3.

Figure 3: Illustration of the distribution transformation flow.

Similarity, samples from the auxiliary distribution can be transformed to the unknown target distribution in the same manner, and the transformed samples are essentially parameterized by the transformation mappings, i.e. the in the second row of Table 1.

a.5 Dataset details

The Stach Overflow dataset contains 6,000 users and 480,000 events of awarding badges. Timestamps are provided when a user is awarded a badge. There are 22 unique badges after filtering, and the prediction of the next badge is treated as a classification task. Event sequences are generated with the same procedures described in Li et al. [2017].

The MovieLens dataset, which is a benchmark for evaluating collaborative filtering algorithms, consists of 60,40 users and 3,416 movies with a total of one million ratings. The implicit feedback of rating actions characterizes user-movie interactions. Therefore the event sequence for each user is not a complete observation for their watching records. To construct event sequences from observations, we follow the same steps as described in Kang and McAuley [2018], where for each user, the final rating is used for testing, the second to last rating is used for validations, and the remaining sequence is used as the input sequence.

In the dataset, there are about 72,000 users and about 1.7 million items with user-item interactions characterized by search, view, add-to-cart and transaction (purchase). The product catalog information is also available, which provides the name, brand and categories for each product. User activity records are aggregated in term of online shopping sessions. So for each user session, we construct event sequences using the same steps as the MovieLens dataset, in a sequence-to-sequence fashion.

a.6 Training and model configuration

We select the number of blocks among {1,2,3} and the number of attention heads among {1,2,3,4} for each dataset according to their validation performances. We do not experiment on using dropout or regularizations unless otherwise specified. We use the default settings for MAF and NVP

provided by TensorFlow Probability

444 555 when learning the distribution for Bochner Inv CDF. Notice that we have not carefully tuned the MAF and NVP for Bochner Inv CDF, since our major focus is to show the validity of these approaches.

Stack Overflow - For all the models that we implement, following the baseline settings reported in Li et al. [2017], the hidden dimension for event representations is set to 32. The dimensions of time embeddings are also set to be 32. In each self-attention block, we concatenate time embeddings to event embeddings and project them to key, query and value spaces through linear projections, i.e.

where and are the entity and time embeddings, , ,

are the projection matrices. We find that using a larger hidden dimension with to many attention blocks quickly leads to over-fit in this dataset, and using the single-head self-attention gives best performances. Therefore we end up using only one self-attention block. The maximum length of the event sequence is set to be 100. For the classification problem, we feed the output sequence embeddings into a fully connected layer to predict the logits for each class and use the softmax function to compute cross-entropy loss.

MovieLens - We adopt the self-attention model architecture used by the baseline models Kang and McAuley [2018] for fair comparisons by replacing the positional encoding with our time embedding. To be specific, the dimension for event representation is set to 50, the number of attention blocks is two and only one head is used in each attention block. To be consistent with the positional encoding self-attention baseline reported in Kang and McAuley [2018], we set the dropout rate to 0.2 and the l2 regularization to 0. The maximum length of the sequence is 200, and the batch size is 128. We also adopt the shared embeddings idea for event representations Kang and McAuley [2018]

, where we use the same set of parameters for the event embeddings layers and the final softmax layers. Finally, the cross-entropy loss with negative sampling is used to speed up the training process. dataset - Given the massive number of items in the dataset, we first train a shallow embeddings model to learn coarse item representations according to their context features and use those embeddings as initialization for the product representations in our model Xu et al. [2019]. The dimension of item embedding and time embedding are set to 100. Each user action (search, view, add-to-cart, transaction) is treated as a token and has a 50-dimensional vector representation that is jointly optimized as part of the model. The action embedding is concatenated to the time-event representations and together they give the time-event-action embedding. To capture time-event and time-action interactions, we first project the joint embeddings onto query, key and value spaces also with linear projections as we did on the Stack Overflow dataset. We find that using two attention blocks and a single head give the best results. Since the task is to predict the next-view item in the same session, we also use the cross-entropy loss with negative sampling.

During training, we apply the early stopping

where we terminate the model training if the validation performance has not increased for 10 epochs. When training models for predicting the next events, we refer to the

masked self-attention training procedure proposed in Vaswani et al. [2017] to prevent information leak while maintaining a fast training speed.

a.6.1 Initialization for time embedding methods

For the Bochner Normal method, we use the standard normal distribution as initial distribution in all experiments. The parametric inverse CDF function for the Bochner Inv CDF is carried out by a three-layer MLP under uniform initialization. For the Bochner Non-para method, since each or , they have a period of . Since we would like to capture underlying temporal signals, the scale of the potential periodicity in the experimented dataset should be taken into consideration. For instance, on the Stack Overflow dataset, it can take days or weeks before the next event happens. Therefore, if the temporal signals were to have underlying periods, it should be on the scale from several days to several weeks. For the dataset, the next activities are often operated within minutes. Therefore the periods should range from seconds to hours.

Therefore, in our experiments, we set the frequencies to cover a suitable range of period where . With out loss of generality, the and are based on the minimum and maximum time span between consecutive events observed in data. We find that using geometric sequences that cover as initialization gives better results than random sampling and equal spacing sampling. To be specific, we use the set of frequencies such that their corresponding periods are given by

Since the above argument also applies to Mercer time embedding method, we use the same initialization approach as well.

a.6.2 Training efficiency

The Adam optimizer is used for all models. We set the learning rate to 0.001 and set the exponential decay rate for second moment statistics to 0.98. The training is stopped if the validation metric stops increasing in 10 consecutive epochs. We use NDCG@10 for the proprietary dataset and MovieLens dataset, and accuracy for Stack Overflow data as the monitoring metric. The final metrics are computed on the hold-out test data using model checkpoints saved during training that has the best validation performances. All models are trained in TensorFlow(1.13) on a single Nvidia V100 GPU.

The training efficiency evaluations are provided in Figure 4. While it takes 9.2 seconds to train each epoch for the convolutional model Caser and up to 17.7 seconds for RNN-based model, it takes only 1.5 seconds for the proposed Bochner non-para method. Also, the test NDCG@10 reaches 0.55 within 100 seconds, while the convolutional model and RNN model reaches the same performance after 600 seconds. The training efficiency for Mercer time embedding is similar to the reported Bochner non-para.

Figure 4: Training efficiency of the proposed Bochner non-para, the convolutional sequence embedding method Caser and RNN-based method on the MovieLens dataset. On the y-axis is the NDCG@10 on testing data.

a.7 Sensitivity analysis

Figure 5: Sensitivity analysis for embedding dimensions on MovieLens data
Figure 6: Sensitivity analysis for embedding dimensions on data

We provide sensitivity analysis on time embedding dimensions for the experiments on MovieLens and the proprietary dataset. We focus on the Bochner non-para and Mercer time embedding, which we find to have the best performances. The results are plotted in Figure 5 and 6. For the recommendation outcomes on MovieLens dataset, we see that for both time embedding methods, the performances increase first and then stabilize as the dimension gets higher. On the proprietary dataset, the performance keeps increasing with larger time embedding dimensions. Firstly, the results suggest both time embedding methods have consistent performances on the two datasets. Secondly, we comment that the difference in data volumes might have caused the different trends on the two datasets. The dataset is much larger than the MovieLens dataset, and the temporal and time-event interaction patterns are more complicated than that of MovieLens. Therefore both time embedding methods keep learning with larger time embedding dimensions.

In a nutshell, the sensitivity analysis suggests that the proposed Bochner non-para and Mercer time embedding give stable and consistent performances on the two datasets.

a.8 Cases study for attention weights

In this section, we present two user-event interaction sequences sampled from the dataset and show how the attention weights progress with respect to the occurrence time of the next event (Figure 7 and 8). The sequence of user activities starts from the top to bottom. Each activity consists of the type of user behavior and the product.

Figure 7: Dynamics of attention weights on each event-action pair with respect to the next event’s occurrence time, for a real-world customer online shopping sequence in home furniture.
Figure 8: Dynamics of attention weights on each event-action pair with respect to the next event’s occurrence time, for a real-world user online shopping sequence in TV and related electronics.

In Figure 7, it is evident that right after the final event, actions such as view and search have high attention weights, as they reflect the most immediate interests. As for the transaction activity, the attention on transaction-sofa pair gradually rise from zero as time elapsed. The attention of view-coffee table pair increases over time as well. The patterns captured by our model are highly reasonable in e-commerce settings: 1. customers’ short-term behaviors are more relevant to what they recently searched and viewed; 2. the long-term behaviors are affected by the actual purchases, and the products that they searched/viewed but haven’t yet purchased. The attention weight dynamics reflected in Figure 8 also show similar patterns.

a.9 Visualization of time embeddings and time kernel functions

In Figure 9, we plot the time embeddings functions and the corresponding kernel function . Firstly, we observe that the kernel functions approximated by either Bochner time embedding or Mercer time embedding are PSD and translation-invariant (since the non-zero elements are distributed on fringes that are parallel to the diagonal in the lower panels of Figure 9). Secondly, the visualizations show that the time embedding functions do capture temporal patterns, because otherwise the values in the matrices would be randomly distributed, as opposed to the recognizable patterns in the upper panels of Figure 9.

Figure 9: Visualization of the learned Bochner non-para and Mercer time embedding functions (upper panel) and corresponding time kernel function (lower panel). For the Mercer time embeddings, we sample three periodic kernels and visualize them with their corresponding time embedding functions.

a.10 Reference implementation

The reference code for our implementations is provided in the supplementary material.