Temporal Graph Machine Learning
local graph
Chapter 11: Temporal Graph Machine Learning
Section titled “Chapter 11: Temporal Graph Machine Learning”Dynamic graphs — representing temporal graphs, embedding methods (factorization, random walk, kernel, temporal point process, deep learning), temporal matrix factorization, temporal random walks, TGNNs.
In the ever-evolving landscape of data science and machine learning, the study of temporal graphs has emerged as a crucial field with widespread applications. Temporal graphs provide a dynamic representation of relationships and interactions between entities over time, offering a more realistic and nuanced perspective than traditional static graphs.
This chapter explores the fundamental concepts of temporal graphs, delving into their definitions, properties, and common applications in various domains. We will explore the definition of dynamic graphs and why they are needed. We will see common problems that can be modeled in the framework of dynamic graphs and we will explore several machine learning algorithms that have been developed for solving such problems, including temporal graph neural networks.
The following topics will be covered in this chapter:
- The definition of dynamic graphs
- Common problems that can be modeled with temporal graphs
- Embedding dynamic graphs
- A general taxonomy to navigate among temporal graph machine learning algorithms
- Hands-on temporal graphs
What are dynamic graphs?
Section titled “What are dynamic graphs?”In the realm of graph theory, the conventional representation of relationships through static graphs has long been the cornerstone of various analytical approaches. As described in Chapter 1, Getting Started with Graphs, a static graph is denoted as , where is its set of vertices and is its set of edges. However, the limitations inherent in static graphs have become increasingly evident, prompting the necessity to delve into the temporal dimension of dynamic graphs. Static graphs, while indeed efficient for capturing instantaneous relationships, fall short in encapsulating the evolving nature of connections over time, which is crucial in many real-world phenomena. To address this limitation, dynamic graphs extend the concept of static graphs to incorporate the temporal dimension. This concept can be used to solve several problems, as we will see in the next section.
Common problems with temporal graphs
Section titled “Common problems with temporal graphs”The concept of temporal graphs is useful in all the real-world problems that can be represented as a graph, where the nodes and edges of the graph may change over time. For example, temporal graphs are extensively applied in modeling social networks. By capturing the evolving relationships between individuals, temporal graphs enable a more accurate representation of social dynamics. This is particularly useful for predicting changes in friendships, community structures, and the information diffusion over time.
Also, in transportation systems, such as road or airline networks, the dynamics of connection are time-dependent. Temporal graphs may help model the changing patterns of traffic, optimal routing, and impact of events such as rush hours or seasonal variations on the network’s structure.
Temporal graphs are also useful for representing and analyzing communication networks, where the time of interactions is crucial. By considering the temporal order of messages or calls, analysts can gain insights into communication patterns, identify anomalies, and enhance the efficiency of network protocols.
Those are only a few examples of how temporal graphs can provide a powerful framework for modeling and understanding relationships over time. Another example is biology, where temporal graphs are employed to study dynamic processes, such as protein-protein interactions, gene regulatory networks, and ecological systems. In finance and stock markets, temporal graphs constitute a valuable tool for modeling transactions and movements to help explain market trends, detect anomalies, and improve predicting processes.
In epidemiology, temporal graphs can help to explain the dynamics between individuals, regions, and populations, aiding in predicting the course of the epidemic and implementing effective healthcare strategies.
As we have seen in Chapter 6, Solving Common Graph-Based Machine Learning Problems, all these problems can be reduced (and thus solved) to a specific task, such as node classification (or regression), graph classification (or regression), and link prediction. Similar consideration should also be made for problems involving a temporal component since tasks on static graphs have a natural translation into the temporal domain:
- Node and graph classification over time: Let be a set of vertices of a graph . Node classification at time is the problem of classifying a vertex in into one (or more) predefined classes, usually based on past or future information. If we aim to classify the whole graph at time , the problem is called graph classification over time. A similar definition can be followed for the tasks of node regression and graph regression that we saw in Chapter 6, Solving Common Graph-Based Machine Learning Problems.
- Link prediction over time: This is the task of predicting when a new connection between two nodes will be created at a particular time point , possibly exploiting past or future information on the graph.
It is worth mentioning that an alternative way of seeing these problems is under the setting of time prediction. In this scenario, we want to predict when an event happened or when it will happen. In other words, we want to predict at which time step a new connection will be established, when a new node will appear in the graph, when a node will change its status, and so on.
But how can we formalize the concept of temporal graphs? Let’s see in the next section.
Representing dynamic graphs
Section titled “Representing dynamic graphs”A critical aspect when modeling dynamic graphs is to define the granularity of the temporal dimension. In particular, two different methods may be adopted:
- Discrete-time approaches: Time is considered to be discrete, thus the evolution of the dynamic graph is described as a sequence of static graphs (snapshots) at a fixed timestamp
- Continuous time: Here, time is considered to be continuous, and specific events are recorded in real time
Based on the above considerations, the transition from static to dynamic involves embracing a spectrum of definitions. Beginning with static graphs of the form , where is a set of nodes, is a set of edges, and is a set of features describing nodes, we progress to spatio-temporal graphs.
Spatio-temporal graphs are of the form , indicating that, while the topology remains the same, the features may change over time.
By further extending this concept, we encounter discrete-time dynamic graphs:
- Discrete-time dynamic graphs are of the form . Here, not only do the features change over time, but so does the topology of the graphs (connections appear and disappear, as well as nodes in the graph). In this scenario, time is considered to be discrete, meaning that we have snapshots of the changing graph over time at discrete time points.
Finally, the concept of discrete-time dynamic graphs can be further generalized to continuous-time dynamic graphs, where each event (change in the graph) is observed and recorded individually, together with its timestamp.
- Continuous-time dynamic graphs are represented as a pair, , where is the graph’s initial state at time 0 and is the set of events recorded for the graph through time. An event is a triple (event type, event, timestamp) where the event type can be any type of topology or feature update, including node addition/deletion, edge addition/deletion, feature update, and edge weight update. An example of an event is the tuple (node deletion, v4, 19-11-2023), meaning that on 19-11-2023 the node v4 was deleted.
In this section, we introduced temporal graphs and common ways of representing temporal graphs at different time granularities. In the next section, we will see how temporal graphs can be encoded to extract relevant features for downstream tasks!
Embedding dynamic graphs
Section titled “Embedding dynamic graphs”As we saw in Chapter 2, Graph Machine Learning, most of the state-of-the-art machine learning algorithms on graphs can be modeled into an encoder-decoder framework. The same applies to dynamic graphs. More specifically:
- The encoder takes as input a dynamic graph and returns as output its embedded representation
- The decoder takes as input an embedded representation of the dynamic graph and, depending on the task, outputs a prediction (it can be a new line, a class, or even a reconstructed graph)
In fields where dynamic graphs can be used to describe various phenomena, accurately modeling the graph’s evolution is often essential for precise predictions. Over time, various categories of machine learning models have been created to capture both the structure and evolution of dynamic graphs.
Notably, adaptations of graph neural networks (GNNs) tailored for dynamic graphs have recently demonstrated success in various domains, emerging as indispensable tools in the machine learning toolbox.
In this section, some of the most common methods for embedding dynamic graphs will be presented. However, for a thorough survey of representation learning methods for dynamic graphs, check out the scientific papers Representation learning for dynamic graphs: A survey by Kazemi et al. (2020), A survey on embedding dynamic graphs by Barros et al. (2021), and Dynamic Graph Representation Learning With Neural Networks: A Survey by Yang et al. (2024). For a more specialized exploration of GNN-based approaches to dynamic graphs, refer to the paper Foundations and modelling of dynamic networks using dynamic graph neural networks: A survey by Skarding et al. (2021).
Let’s first introduce a mathematical formulation to define the problem of dynamic graph embedding. The task involves mapping a dynamic graph with evolving nodes and edges into a d-dimensional vector space over time. This mapping captures both the network’s topological structure and temporal dependencies. The goal is to learn representations that can reconstruct the dynamic graph, predict its behavior beyond given timestamps, or address specific tasks like node classification. When the graph topology changes, there are two possible interpretations: either the vector representations move within the embedding space, allowing the tracking of node trajectories, or the embedding space evolves over time, enabling the learning of mappings between consecutive timestamps. Notice that the temporal granularity of the dynamic graph and the temporal embedding do not need to be the same. In fact, it is entirely reasonable for dynamics graphs to capture low-level interactions (e.g., daily events) mapped into a coarser granularity (e.g., months or years).
Following the paper A survey on embedding dynamic graphs, we propose a taxonomy of dynamic graph embedding methods (Figure 11.1). The taxonomy categorizes dynamic graph methods into the following:
- Factorization-based methods
- Random walk-based methods
- Graph kernel methods
- Temporal point process methods
- Deep learning-based methods
- Agnostic models
These are depicted here:

Figure 11.1: Dynamic graph embedding taxonomy
Let’s discuss each of these methods in the following sections.
Factorization-based methods
Section titled “Factorization-based methods”Factorization-based techniques produce embeddings over time by decomposing low-rank representations of time-dependent similarity measures. As we saw in Chapter 4, Unsupervised Graph Learning, graphs can be represented either as a sequence of matrices or as three-way tensors linking nodes’ similarity. This matrix (or tensor) can be factorized to emphasize specific properties of the input graph.
Dynamic graph embedding with matrix factorization follows static graph principles but introduces temporal dependence into the decomposition process. There are three main methods for inserting temporal dependence in the matrix factorization process:
- Jointly optimizing reconstruction and temporal smoothing: Here, the loss function consists of two terms. The first term measures the quality of the reconstruction (as in the static graph scenario) and the second term measures the similarity between the embeddings for each pair of consecutive time stamps, thus ensuring a smooth evolution of the embedding envelope.
- Incremental updates on embeddings: With this approach, the embeddings are computed by iteratively adjusting an initial representation based on the changes observed in the similarity matrices over time. For example, such an adjustment can be done using first-order matrix perturbation theory in symmetric matrices iteratively.
- Temporal matrix factorization: Here, each snapshot is usually decomposed into two components: a constant matrix U representing persistent properties between a pair of nodes and a time-dependent matrix representing changes in topology over time. This temporally parameterized factorization (obtained, for example, by minimizing the sum of the squares between the adjacency matrix at time and its reconstruction ) can be used to reconstruct the structure of the network at any time (past or future).
As per tensor-based approaches, it is natural to represent dynamic graphs as a three-way tensor (that is, a stack of adjacency matrices). Then, tensor factorization methods such as CANDECOMP/PARAFAC (CP) and Tucker decomposition can be used to learn both node embeddings and temporal embeddings.
Random walk-based methods
Section titled “Random walk-based methods”An alternative set of techniques for graph embedding revolves around random walks. As shown in Chapter 4, Unsupervised Graph Learning, multiple fixed-length random walks are considered as sentences, creating a context for each node and capturing higher-order dependencies without relying on adjacency matrices. The resulting node sequence matrix is then factorized, often employing a neural network architecture such as skip-gram. There are three main types of methods for embedding temporal graphs:
- Random walks on snapshots: This involves generating time-dependent node sequences by exploring the evolving graph structure at different timestamps.
- Evolving random walks: This method adapts to topological changes by incrementally updating representations. It ensures that the embeddings capture the evolving nature of the network as it changes over time.
- Temporal random walks: This defines time-dependent contexts by exploring random walks across consecutive timestamps. It captures evolving patterns and temporal dependencies in the graph, providing a comprehensive understanding of the network’s dynamics.
Graph kernel-based methods
Section titled “Graph kernel-based methods”Another set of methods focuses on elementary substructures derived from an entire graph structure. These techniques integrate topological attributes, such as graphlet transition count, graphlet frequencies over time, and adjacency matrix summation, during network processing. The goal is to employ a shallow autoencoder to learn representations capable of reconstructing intricate attributes from these substructures. This enables a more nuanced understanding of the evolving nature of these topological building blocks in the network.
Temporal point process methods
Section titled “Temporal point process methods”Various techniques in dynamic graph embedding treat interactions between nodes as stochastic processes, where probabilities are influenced by the network’s topological structure, node features, and historical context. In these approaches, events are assumed to impact a specific node, leading to potential interactions with other nodes susceptible to the influence of the current node.
Deep learning-based methods
Section titled “Deep learning-based methods”Temporal graph neural networks (TGNNs) have seen significant progress in capturing spatial and temporal dependencies in graph-structured data. The first level of classification distinguishes between snapshot-based and event-based models:
- Snapshot-based models: These involve the use of two components: a suitable method to process the whole graph at each time point and a mechanism to learn the temporal dependencies. A further distinction is also made:
- Model evolution methods: This kind of model, such as EvolveGCN (Pareya et al. 2020) uses a recurrent neural network (RNN) to adapt the parameters of a graph convolutional network over time
- Embedding evolution methods: Instead of evolving the parameters of a static GNN, these methods use an RNN to evolve directly the embedding at the previous time point
- Event-based models: These models process event streams, updating node representations each time an event involving that node occurs. These models can be seen as an extension of the message-passing paradigm and can be further classified as follows:
- Temporal embedding methods: These models (often based on self-attention mechanisms) process event streams, incorporating time into the model sequential information, node features, and graph topology interactions
- Temporal neighborhood methods: These models use specialized modules to store and aggregate functions of events involving specific nodes at given times, updating node representations as time increases
Agnostic methods
Section titled “Agnostic methods”All the approaches discussed so far are based on specific algorithms. For example, factorization-based approaches are based on factorization techniques, random walk-based methods are based on random walk algorithms, and so on.
There is a set of approaches that do not rely on any specific paradigm, namely agnostic models. These models focus on learning connections between representations at consecutive time points or within a time window. Two paradigms within this classification are as follows:
- Retrofitted models: These models leverage static network embeddings to learn an initial representation of the graph, and then they adapt and refine these representations (retrofitting) to capture the dynamic evolution of the graph in subsequent snapshots
- Transformation methods: These methods calculate representations for each graph snapshot independently using any static method and learn a transformation function connecting embeddings at different timestamps
You have now learned about several encoding methods for temporal graphs. It is now time to take a look at temporal graph machine learning! We will do this in the next section.
Hands-on temporal graphs
Section titled “Hands-on temporal graphs”In this section, we will introduce representative examples of the machine learning approaches described in the previous sections for dealing with temporal graphs. We will offer a general understanding of how these approaches work and provide examples of their implementation using publicly available frameworks.
Temporal matrix factorization
Section titled “Temporal matrix factorization”Concerning the matrix factorization class of approaches, the Temporal Matrix Factorization (TMF) model by Yu et al. (2017) is a method used for temporal link prediction, particularly in dynamic network scenarios. This technique leverages matrix factorization with temporal dynamics to model the evolution of links in a dynamic network over time.
To exemplify this method, we adopted the implementation provided in the publicly available OpenTLP library (https://github.com/KuroginQin/OpenTLP). It integrates an encoder-decoder architecture, where the encoder learns model parameters through matrix factorization, and the decoder generates predictions based on these parameters. The optimization process involves minimizing a loss function that includes regularization and reconstruction error terms, capturing temporal dependencies in the network structure.
The core of this TMF implementation lies in the TMF class, which orchestrates the encoding-decoding process, as shown in the following code:
class TMF(Module): def __init__(self, num_nodes, hid_dim, win_size, num_epoch, alpha, beta, theta, learn_rate, device): # ... self.enc = TMF_Enc(num_nodes, hid_dim, win_size, num_epoch, alpha, beta, theta, learn_rate, device) self.dec = TMF_Dec()
def TMF_fun(self, adj_list): self.enc.model_opt(adj_list) param_list, _ = self.enc() adj_estimated = self.dec(param_list, self.win_size+1) return adj_estimatedLet’s break down the encoding and decoding steps.
The TMF_Enc class embodies the encoder, which is responsible for learning the model’s parameters:
class TMF_Enc(Module): def __init__(self, num_nodes, hid_dim, win_size, num_epoch, alpha, beta, theta, learn_rate, device): # ... self.dec_list = [] # List of decaying factor # ...
def forward(self): adj_est_list = [] for t in range(self.win_size): V = self.param[0] + self.param[1]*(t+1) + self.param[2]*(t+1)*(t+1) U = self.param[3] adj_est = torch.mm(U, V.t()) adj_est_list.append(adj_est) return self.param, adj_est_list
def get_loss(self, adj_list, adj_est_list, dec_list, alpha, beta): ''' Function to get training loss :param adj_list: sequence of historical adjacency matrix (ground-truth) :param adj_est_list: sequence of estimated adjacency matrix :param dec_list: list of decay factors :param alpha, beta: hyper-parameters :return: loss function ''' win_size = len(adj_list) # Window size (#historical snapshots) loss = 0.5*alpha*torch.norm(self.param[3], p='fro')**2 loss += 0.5*beta*torch.norm(self.param[0], p='fro')**2 loss += 0.5*beta*torch.norm(self.param[1], p='fro')**2 loss += 0.5*beta*torch.norm(self.param[2], p='fro')**2
for t in range(win_size): dec_t = dec_list[t] # Current decaying factor adj = adj_list[t] adj_est = adj_est_list[t] loss += 0.5*dec_t*torch.norm(adj - adj_est, p='fro')**2
return loss
def model_opt(self, adj_list): ''' Function to implement the model optimization :param adj_list: sequence of historical adjacency matrices (ground-truth) :return: ''' for epoch in range(self.num_epoch): _, adj_est_list = self.forward() loss = self.get_loss(adj_list, adj_est_list, self.dec_list, self.alpha, self.beta) self.opt.zero_grad() loss.backward() self.opt.step()The forward function reconstructs the adjacency matrices based on the learned parameters. The factorization is expressed as:
The get_loss function calculates the training loss, which includes terms for regularization and reconstruction errors:
The model_opt function implements model optimization using the Adam optimizer.
Finally, the TMF_Dec class serves as the decoder, which generates predictions based on the learned parameters:
class TMF_Dec(Module): ''' Class to define the decoder of TMF ''' def __init__(self): super(TMF_Dec, self).__init__()
def forward(self, param_list, pre_t): ''' Rewrite forward function :param param_list: list of learned model parameters :param pre_t: time step of prediction result (e.g., win_size+1) :return: prediction result ''' V = param_list[0] + param_list[1]*pre_t + param_list[2]*pre_t*pre_t U = param_list[3] adj_est = torch.mm(U, V.t()) return adj_estThe following code exemplifies the usage of the TMF method for temporal link prediction. An instance of the TMF model is created with specified parameters, and the TMF_fun function is applied to obtain predicted adjacency matrices based on a given sequence of historical adjacency matrices (adj_list):
TMF_model = TMF(num_nodes, hid_dim, win_size, num_epochs, alpha, beta, theta, learn_rate, device)adj_est = TMF_model.TMF_fun(adj_list)Temporal random walk
Section titled “Temporal random walk”As we saw in the previous section, random-walk-based approaches represent an important class of methods for the temporal domain. Among the various paradigms, we describe here a method based on temporal random walk called CTDNE, by Nguyen et al. (2018), for learning time-preserving embedding. Let’s introduce the general idea.
Imagine selecting an initial edge at a certain time step as the starting point of our temporal random walk. As in the static version described in Chapter 4, Unsupervised Graph Learning, at each step, we have to choose another edge to continue the walking. However, this time, the structure of the graph can change at each time step. Therefore, we need to define the set of temporal neighbors of a node at a particular time . One way is as follows:
That is, the set of all nodes that are connected to the node after the time step . Intuitively, starting from the node at time , we can walk over time by traversing all the edges that are present in a particular moment after . Note that it is possible for the same neighbor to appear in multiple times since they can be connected multiple times over time (for example, sends an email to at time , then replies to at time , and so on).
It is worth noting that, according to the way we sample the next edge to traverse over time, the resulting random walk can be biased, allowing us to define effective sampling strategies for particular tasks. For example, in the context of temporal link prediction, if we aim to predict edges at time , it is better to compute temporal walks from edges closer to time rather than temporal walks sampled in the distant past, since the latter may offer lower predictive value.
The CTDNE method is available in stellargraph. Let’s see an example of how to use it.
Let’s first define the random walk parameters, including walk_length (the maximum length of each random walk), context_window_size (the size of the context window employed for training the Word2Vec model), and num_cw (the number of context windows we want to obtain):
walk_length = 80context_window_size = 10num_cw = 20Let’s then define the walks:
from stellargraph.data import TemporalRandomWalk
temporal_rw = TemporalRandomWalk(graph)temporal_walks = temporal_rw.run( num_cw=num_cw, cw_size=context_window_size, max_walk_length=walk_length, walk_bias="exponential",)graph is the input graph. Notice the walk_bias parameter, which allows us to set the sampling strategy for the temporal walk.
Finally, we can train the Word2Vec model similarly to what we did in the static case but now using the obtained temporal walks, generating the embeddings, which can then be used for downstream machine learning tasks (such as link prediction or node classification):
from gensim.models import Word2Vec
embedding_size = 128temporal_model = Word2Vec(temporal_walks, vector_size=embedding_size, window=context_window_size, min_count=0, sg=1, workers=2, epochs=1)As GNNs have gained popularity, numerous architectures have emerged in recent years to address the temporal domain. From classical GNNs combined with recurrent modules (such as LSTM and GRU) to more specialized models, such as DynGEM, EvolveGCN, or generative models, these architectures have shown promising results in handling temporal dependencies.
In this section, we will introduce the temporal graph network (TGN) framework by Rossi et al. (2020), a generic and efficient approach for deep learning on dynamic graphs.
TGN is designed to handle continuous-time dynamic graphs represented as a sequence of time-stamped events. It produces as output a node-embedded representation. The core of the framework is composed of five different modules:
- Memory: The memory module of the TGN framework manages the model’s state at a given time . It consists of a state vector for each node seen so far (that is, every time a new node is involved in an event a new vector is added to the memory).
- Message function: The message function module calculates the messages that are used to update the memory of a node for each event it participates in. They are typically implemented using simple neural networks (for example, MLPs), taking as input the event details and the memory states of the nodes involved in the event.
- Message aggregator: Since multiple messages from the same node can occur in the same batch, an aggregator function can be used to aggregate messages (for example, by averaging all the messages for a given node).
- Memory updater: This is a learnable function that is typically implemented using recurrent units such as LSTM or GRU. It takes as input the current state of a node involved in a certain event and the output computed by the message function based on the event and updates the memory of the node .
- Embedding: This is a learnable function that computes the temporal embedding of a node using the graph and the memory. The embeddings are then used for downstream tasks such as link prediction.
TGN and its modules are implemented in pytorch_geometric and can be easily used to solve simple and complicated tasks. Let’s see how TGN can be used to embed temporal graphs. Below, we will be showing a general framework for computing embeddings using TGN. Notice that, to perform any downstream task such as link prediction and node classification, you should concatenate a proper decoder (a neural network that takes the embeddings and computes the predictions). You can find a complete example in the notebooks attached to this book.
The first step is to initialize the TGNMemory class, which will keep the model’s state and handle the message computation and memory update. As shown in the following snippet of code, the TGNMemory class can be customized by using proper message modules (in our example we chose the IdentityMessage module) and a message aggregator (in our case the LastAggregator module, which keeps the most recent event for a node):
from torch_geometric.nn import TGNMemoryfrom torch_geometric.nn.models.tgn import ( IdentityMessage, LastAggregator, LastNeighborLoader)
memory_dim = time_dim = embedding_dim = 100
memory = TGNMemory( data.num_nodes, data.msg.size(-1), memory_dim, time_dim, message_module=IdentityMessage(data.msg.size(-1), memory_dim, time_dim), aggregator_module=LastAggregator(),).to(device)
# a data loader that performs neighbor samplingneighbor_loader = LastNeighborLoader(data.num_nodes, size=10, device=device)Together with the TGNMemory, we will also create a GNN for obtaining the embeddings. In this example, we will define a GraphAttentionEmbedding class, which uses the TransformerConv module (a message-passing module implemented in PyTorch):
from torch_geometric.nn import TransformerConv
class GraphAttentionEmbedding(torch.nn.Module): def __init__(self, in_channels, out_channels, msg_dim, time_enc): super().__init__() self.time_enc = time_enc edge_dim = msg_dim + time_enc.out_channels self.conv = TransformerConv(in_channels, out_channels // 2, heads=2, dropout=0.1, edge_dim=edge_dim)
def forward(self, x, last_update, edge_index, t, msg): rel_t = last_update[edge_index[0]] - t rel_t_enc = self.time_enc(rel_t.to(x.dtype)) edge_attr = torch.cat([rel_t_enc, msg], dim=-1) return self.conv(x, edge_index, edge_attr)
gnn = GraphAttentionEmbedding( in_channels=memory_dim, out_channels=embedding_dim, msg_dim=data.msg.size(-1), time_enc=memory.time_enc,).to(device)Finally, we can insert the TGN components into a training loop, as shown in the following code:
def train(): memory.train() gnn.train() memory.reset_state() # Start with a fresh memory. neighbor_loader.reset_state() # Start with an empty graph. total_loss = 0
for batch in train_loader: optimizer.zero_grad() batch = batch.to(device) n_id, edge_index, e_id = neighbor_loader(batch.n_id) assoc[n_id] = torch.arange(n_id.size(0), device=device)
# Get updated memory of all nodes involved in the computation. z, last_update = memory(n_id) z = gnn(z, last_update, edge_index, data.t[e_id].to(device), data.msg[e_id].to(device))
# here we can compute the downstream task (for example link # prediction or node classification). This can be achieved by # concatenating a decoder (a neural network which takes the # embeddings and computes the predictions) # finally we can compute the loss and perform the update steps. # You can customize the criterion according to the downstream # task you want to perform loss = criterion(z, batch)
# Update memory and neighbor loader with ground-truth state. memory.update_state(batch.src, batch.dst, batch.t, batch.msg) neighbor_loader.insert(batch.src, batch.dst)
loss.backward() optimizer.step() memory.detach() total_loss += float(loss) * batch.num_eventsWith this, we conclude the section where we have learned about the TGN framework, an advanced method for modeling dynamic graphs using memory-based representations. We also know how TGN’s modular architecture enables effective temporal node embeddings for downstream tasks such as link prediction and node classification.
Summary
Section titled “Summary”In this chapter, we introduced the concept of temporal graph machine learning. We discovered why it is needed and what the main problems that can be addressed using this paradigm are. We also learned a taxonomy for classifying temporal graph machine learning algorithms. Finally, we explored practical examples to understand how the theory can be applied to practical problems.
In the next chapter, we will explore the integration of language models with graphs, a rapidly evolving area at the intersection of natural language processing and graph-based learning. We will discuss recent advancements in leveraging graph structures to enhance language models, as well as techniques that incorporate textual data into graph-based representations.
Further reading
Section titled “Further reading”- Kazemi et al. Representation learning for dynamic graphs: A survey. The Journal of Machine Learning Research 21.1 (2020): 2648-2720.
- Barros et al. A survey on embedding dynamic graphs. ACM Computing Surveys (CSUR) 55.1 (2021): 1-37.
- Yang et al. (2024). Dynamic graph representation learning with neural networks: A survey. IEEE Access, 12, 43460-43484.
- Skarding et al. Foundations and modeling of dynamic networks using dynamic graph neural networks: A survey. IEEE Access 9 (2021): 79143-79168.
- Labonne, Maxime. Hands-On Graph Neural Networks Using Python. Packt Publishing Ltd. (2023)
- Nguyen et al. Continuous-time dynamic network embeddings. Companion proceedings of the web conference (2018)