Neural Networks and Graphs
local graph
Chapter 03: Neural Networks and Graphs
Section titled “Chapter 03: Neural Networks and Graphs”Neural networks applied to graphs — ANNs with TensorFlow and PyTorch, classification beyond fully connected layers, introduction to GNNs, GNN variants, frameworks for deep learning on graphs (PyG, StellarGraph, DGL).
The machine learning landscape of the last decade has seen the rise and explosion of a particular type of model that is extremely popular nowadays, and whose name is becoming very familiar even to non-technical people and practitioners: artificial neural networks (ANNs). Their versatility and potency have resulted in widespread adoption globally, including in the graph domain. Several frameworks have been developed to support their study, use, and development.
Although the first attempts to train ANNs date back to the early 1980s (with the seminal work of Paul Werbos and Geoffrey Hinton), their rise and success has come around only recently, thanks to the advances in computing power (via CPUs but mostly thanks to the highly efficient parallelization of computation enabled by GPUs) as well as the availability of large datasets. ANNs are in fact very general models, able to virtually learn any function, but as such, they need to be trained on vast amounts of data with a large computational cost. In return, however, they can achieve extremely high performances (even super-human) on very complex tasks.
Given such capabilities, recent research and advances in graph machine learning have therefore gone through the development of ANN-based algorithms. The integration between neural networks and graphs has generated a new class of algorithms that are commonly referred to as graph neural networks (GNNs), which – as you will see in the next chapters – will constitute an important backbone of this book.
In this chapter, we will introduce the basic concepts around neural networks and the libraries/frameworks commonly used to deal with ANNs and GNNs.
The following topics will be covered in this chapter:
- A refresher on ANNs and deep learning
- An overview of the most widely used deep learning frameworks
- An introduction to GNNs and the most widely used frameworks for deep learning on graphs
Introduction to ANNs
Section titled “Introduction to ANNs”Neural networks are formed by the integration of several simpler units, called neurons. A neuron is just a representation of the following relation between some inputs and one output of the form:
Here:
- is called the bias
- is called the weights
- is the activation function
The earliest biological models of the neuron in animals and humans historically use a mathematical formulation similar to the one above, in which dendrites transmit incoming information from synapses, propagating and combining it in the neuron’s axons, which is then connected to the synapses of nearby, connected neurons. However, it is worth stressing that the formula above is an extremely simplified, naive, and (to some extent) poor representation of what really happens in our brains, lacking the more complex time-dependence behaviors produced by the propagation of electric signals. Over the years, researchers have come up with more realistic and complex models (i.e., generalized integrate-and-fire models) that can more closely capture the neuronal firing patterns observed in living creatures.
Nevertheless, it is extremely interesting to see what a combination of simple relations such as the one above can provide. Indeed, neural networks generally build upon this simplified neuron mode where the output of one neuron becomes the input of the following one.
This is represented using a diagram like the one shown in Figure 3.1 (this representation will also be used throughout this book), where you can see that neurons can be stacked in progressive and subsequent layers. An ANN is therefore specified by the set of biases, activation functions, and weights (also defining the connectivity) of its neurons.
As you can see from Figure 3.1, we use the notation to define the weight connecting the -th neuron of the -th layer to the -th neuron of the -th layer. Similarly, represents the bias of the -th neuron of layer . Although the activation functions could vary from neuron to neuron, it is common to choose a single function for each layer. Some common choices are sigmoid, rectified linear unit (ReLU), and softmax.

Figure 3.1: Simple schematic representation of a neural network
The various combinations and choices for the network’s parameters give rise to the most common neural network architectures nowadays. One can also pose some sort of constraints among the parameters, like imposing that some weights must have the same values (in other words, are shared between neural connections). This is quite common for kernels largely used in Convolutional Neural Networks (CNNs), where a given mask (of generally small size) carrying the same set of weights is applied to nearby neurons and rolled throughout the entire layer.
It is possible to demonstrate that such simple combinations of smaller units are – quite surprisingly – extremely powerful and general, as stated by the universal approximation theorem: a simple neural network made of just one hidden layer (besides the input and output layers) can represent any continuous function, provided it has a large enough number of units on its hidden layer. For some time, this theorem has provided support to people for building wide neural networks, thus characterized by a small number of large-neuron layers. However, experience and practice over the years have shown that deep neural networks, characterized by a very large number of layers stacked and connected on top of each other, are able to “learn” high-level features that allow the network to generalize better.
Training neural networks
Section titled “Training neural networks”So far, we have just described the way that some inputs can be propagated through the neural network to produce one or multiple outputs. This would be of little use if we did not have a way to find a combination of the biases and weights to produce meaningful outputs. Training a neural network refers to the process that allows us to optimize the values of the parameters to make the neural network able to carry out a specific task. And to do so, we need data. Often, a lot of data.
For the training data, in fact, we know exactly what the input and the output of the neural network should be, and the training process can be seen as the optimization problem to identify the set of values of the biases and weights that makes the predicted outputs the closest to the expected ones. Therefore, like in any optimization problem, when training a neural network, we define a loss function that we would like to minimize:
Here, and represent the predicted and expected output, is the loss function quantifying the dissimilarity between predicted and expected outputs, based on the value of , and is a regularization term. Note that the single bar on top of b and the double bar on top of W indicate that we are dealing with arrays and matrices, respectively. The activation functions of the neural network are not “trained” but rather encoded in the neural network architecture, although there have also been attempts to use families of activation functions and/or a combination of activation functions of some sort to be identified during the learning process.
If all the functions used in the formulation above – namely, the activation function , the dissimilarity function , and the regularization function are continuous and differentiable, the loss to be minimized is also differentiable; therefore, minimization gradient-based techniques can generally be applied. The very famous backpropagation algorithm is one implementation of such methods where the gradients of the loss with respect to the weights are computed very efficiently by iterating backward from the last layers up to the first, making use of the chain rule and avoiding redundant calculation. There exist several variants of the general approach, depending on how the direction and the step updates are handled across the learning. Unfortunately, you must also note that the shape of the loss function can be extremely complex, with multiple local minima as well as saddle points. Finding the absolute minima is often very hard, but finding local minima can be good enough for most cases. For more information, please refer to Deep Learning, a book by Goodfellow et al.
Computational frameworks for ANNs
Section titled “Computational frameworks for ANNs”Over the years, many frameworks and libraries have been developed to deal with the implementation, training, and computation of ANNs, also following the different trends in the programming languages traditionally used by researchers, like C, C++, Lua, Python, and Java. Generally, all these libraries provide a framework to define:
- The representation of the network, which specifies the relationship between inputs, outputs, and the parameter that this representation depends on
- The loss function relating input, outputs, and parameters, which we want to minimize
- The optimizer algorithm to be used to minimize the loss function
Besides this basic information needed to train ANNs, the different libraries also commonly offer (and this is where the key differences between libraries often emerge from a developer’s standpoint) some predefined types of neurons, kernels, and layers. These predefined components make it easier to define new neural network architectures – even very complex ones – resulting in an extremely easy and lean coding process.
Of course, besides the high-level functionalities, the different frameworks and libraries may very well achieve significantly different performances, in terms of CPU/GPU usage, memory usage, and training time, as well as support (or lack thereof) for distributed training.
These capabilities can determine the choice of one framework over another, and these key performance indicators (KPIs) are tightly connected to the backbone and low-level implementation of the underlying computational engine.
All the neural network frameworks depend – in one way or another – on a symbolic representation of the graph, allowing you to build a structure that describes how inputs are combined to produce intermediate results and the final outputs. This is often referred to as a computational graph or a stateful dataflow graph, where nodes are the variables (scalar, arrays, and tensors) – eventually transformed using activation functions – and edges represent the combinations of variables (edge source) to produce the output (edge target) of a single neuron. Each edge is also described by a weight that is multiplied to the input. You can therefore understand how such a graph can generically represent a composition of equations of the form shown in the Training neural networks section above.
The loss function can equally be represented symbolically, and the computational graph representation is extremely useful for computing the differentiation of the loss function (needed by the backpropagation algorithm) with respect to the various parameters (i.e., the weights and biases) in a modular way.
However, two classes of neural networks emerged based on how the differentiation is done: symbol-to-number and symbol-to-symbol differentiation.
Some neural network frameworks implement differentiation by taking the computational graph and a set of inputs and then returning a set of numerical values representing the gradients of the loss function with respect to their parameters. This approach is commonly referred to as symbol-to-number differentiation, and it is used by PyTorch and Caffe. On the other hand, other frameworks take the input computation graph and the loss function, and they generate additional nodes and edges that provide a symbolic description of the derivatives, therefore effectively creating a computational graph for the differentiation computations. This is referred to as symbol-to-symbol differentiation, and – compared to the symbol-to-number approach – it provides the advantage of easily extending to higher derivatives very naturally since the same logic can be recursively applied to the resulting graph of the differentiation. This is the approach that is taken by Theano and TensorFlow.
But this advantage comes with a cost. In fact, symbol-to-symbol frameworks are characterized by a static graph, where the computational graph (and its derivatives) is usually defined upfront, and – in this immutable structure – the data is then fed into it, flowing through the operations, providing either predictions or derivatives. The idea of the data flowing through the graph is also the reason behind the Flow suffix in TensorFlow. On the other hand, frameworks like Torch build the computational graph at execution time (when data is fed to it), therefore easily allowing you to change its topology and deal with dynamic graphs.
In the next subsections, we provide a more detailed description of two popular neural network frameworks that will be used in this book – TensorFlow and PyTorch – giving you tools that will hopefully allow you to tackle different use cases. As we will see in the Frameworks for deep learning on graphs section, this is also true when dealing with GNNs: some algorithms and frameworks will be better suited for your tasks, depending on their requirements.
TensorFlow
Section titled “TensorFlow”Released as open source by Google in 2017, TensorFlow is now the standard, de facto framework that allows symbolic computations and differential programming, especially in production and industrial use cases. By abstracting its computation, TensorFlow is a tool that can run on multiple backends: on machines powered by CPUs, GPUs, or even ad hoc, specifically-designed processing units such as the tensor processing units (TPUs) designed by Google. TensorFlow-powered applications can also be deployed on different devices, ranging from single and distributed servers to mobile devices.
As previously mentioned, TensorFlow provides a framework to perform symbol-to-symbol differentiation, which allows you to symbolically define a computational graph to be differentiated with respect to any of its variables, resulting in a new computational graph that can also be differentiated to produce higher-order derivatives. Historically, TensorFlow only supported static graphs. However, with the release of version 2, TensorFlow now also provides support for dynamic graphs, with the so-called eager execution in which the graph is built at execution time.
TensorFlow is organized around the concept of tensors. These abstractions represent any kind of data, be it inputs, outputs, intermediate results, and/or variables to be optimized during training. Although one could implement the different operations between tensors (e.g., matrix multiplication between inputs and weights as well as the application of activation functions), since its last major release, 2.x, the standard way of building a model with TensorFlow is by using the Keras API.
Keras was natively a side external project with respect to TensorFlow, aimed at providing a common and simple API to use several differential programming frameworks, such as TensorFlow, Theano, and CNTK, for implementing a neural network model. It abstracts the low-level implementation of the computation graph and provides you with the most common layers used when building neural networks (although custom layers can also be easily implemented), such as the following:
- Convolutional layers
- Recurrent layers
- Regularization layers
- Loss functions
Keras also exposes APIs that are very similar to scikit-learn, the most popular library for machine learning in the Python ecosystem, making it very easy for data scientists to build, train, and integrate neural network-based models in their applications.
Moreover, TensorFlow comes with a set of modules and tools that makes it a very mature technology, oriented for industrial and production use cases. One such tool worth mentioning is TensorBoard, which is a graphical user interface (GUI) that allows you to monitor model training and debug/understand models. It is extremely helpful to data scientists and seamlessly integrated into the framework.
A simple classification example
Section titled “A simple classification example”To showcase how easy it is to train a neural network in TensorFlow and Keras, we will apply this framework to a simple case of image classification using the Fashion-MNIST dataset. This example, based on a well-known task, will serve as preparation for later understanding graph-based applications.
The Fashion-MNIST dataset is similar to the famous MNIST dataset, a collection of hand-written numbers on a black-and-white image. In fact, Fashion-MNIST has 10 categories and consists of 60k and 10k (training dataset and test dataset) 28x28 pixel grayscale images that represent a piece of clothing (T-shirt, Trouser, Pullover, Dress, Coat, Sandal, Shirt, Sneaker, Bag, and Ankle boot). However, the Fashion-MNIST dataset image classification is a harder task than the original MNIST dataset and it has historically been used for benchmarking algorithms, with recent algorithms achieving top performances on this dataset.
The dataset is already integrated into the Keras library and can be easily imported using the following code:
from tensorflow.keras.datasets import fashion_mnist(x_train, y_train), (x_test, y_test) = fashion_mnist.load_data()It is usually good practice to rescale the inputs with an order of magnitude of around 1 (for which activation functions are most efficient) and make sure that the numerical data is in single precision (32 bits) instead of double precision (64 bits). This is because it is often desirable to promote speed rather than precision when training a neural network, which is a computationally expensive process. In certain cases, the precision could even be lowered to half-precision (16 bits).
We transform the input with the following:
x_train = x_train.astype('float32') / 255.x_test = x_test.astype('float32') / 255.We can grasp the type of inputs we are dealing with by plotting some of the samples from the training set using the following code:
n = 6plt.figure(figsize=(20, 4))for i in range(n): ax = plt.subplot(1, n, i + 1) plt.imshow(x_train[i]) plt.title(classes[y_train[i]]) plt.gray() ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False)plt.show()In the preceding code, classes represents the mapping between integers and class names, for example, T-shirt, Trouser, Pullover, Dress, Coat, Sandal, Shirt, Sneaker, Bag, and Ankle boot:

Figure 3.2 – Some samples taken from the training set of the Fashion-MNIST dataset
Note that images in this dataset have 28x28 pixels, which is why they appear low-resolution and blurry in the preceding figure to accurately reflect the original raw data.
Let’s now build the first model. Using the Keras API, we create a simple model that unrolls the images into a flat structure (1D vector of 784 elements) and adds one hidden layer, fully connected, of 128 units:
model = tf.keras.models.Sequential([ tf.keras.layers.Flatten(input_shape=(28, 28)), tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dropout(0.2), tf.keras.layers.Dense(10)])Note that the last layer represents a fully connected layer that maps out the number of classes of our task (e.g., 10), representing the probabilities for each of the 10 classes. To prevent overfitting, before the output layer, we use a Dropout layer, which randomly removes (with a probability of 0.2 – i.e., 20%) the activation of a neuron during training. The idea is that the neural network should be resilient and able to make good predictions, even when some of its single units are removed.
Once the model is defined, it can be helpful to inspect it with the following:
model.summary()This should provide the following output:
Model: "sequential"_________________________________________________________________Layer (type) Output Shape Param #=================================================================flatten (Flatten) (None, 784) 0
dense (Dense) (None, 128) 100480
dropout (Dropout) (None, 128) 0
dense_1 (Dense) (None, 10) 1290
=================================================================Total params: 101,770Trainable params: 101,770Non-trainable params: 0Even this very simple model has more than 100k parameters.
Once the topology/architecture of our neural network is defined, we need to “compile” the model, which effectively means building the computational graph associated with its training. However, to fully specify the computational plan of the training, we also need to define the loss function (with respect to which we need to compute the gradients of the weights) as well as the optimization algorithm (that defines how the gradients are to be used):
loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)optimizer = tf.keras.optimizers.Adam()We can now compile the model with the following code:
model.compile(optimizer=optimizer, loss=loss_fn, metrics=['accuracy'])As you can see, when compiling the model, we can also provide extra metrics that will be monitored during training and evaluation. In fact, the loss function we would like to minimize may be – in some cases, such as this one – somewhat obscure, based on the difference between probability distributions. This allows efficient training, but it is not readily meaningful to us. It is indeed a lot more natural to refer to the “accuracy,” which represents how many correct predictions (taking the class with the highest probability) the model is able to make.
We are now fully ready to train the neural network, which can be easily done with:
model.fit( x_train, y_train, validation_data=(x_test, y_test), epochs=20, batch_size=128, shuffle=True)Although a very simple example, the model achieves interesting performance, with accuracy on the validation set of around 90%.
In the notebook, we also provide a more complex network, using convolutional and max-pooling layers, which will be explained more in the following section. Feel free to try using and training more complex networks.
PyTorch
Section titled “PyTorch”PyTorch is a library that is based on the Torch framework. Historically, Torch was initially developed at EPFL and it included a core implemented in C, wrapped by a framework in Lua. However, in 2016, Meta AI started to develop PyTorch, written in Python and offering an API more accessible to data scientists to train neural networks, still leveraging the same low-level core computational engine written in C. Since then, the framework has gained a lot of momentum. It is now part of the Linux Foundation and also implements APIs in other languages, such as C++.
Similar to TensorFlow, PyTorch revolves around the use and transformation of tensors. However, in PyTorch, tensors not only represent the inputs but also store the computational graph that is required to compute them. Notably, one of the key differences of PyTorch with respect to TensorFlow is that there is no static graph. In fact, in PyTorch, the computational graph is recreated from scratch at every iteration.
During the forward pass, PyTorch both performs the required computations and builds up the graph representing the operations that allow the gradient computation for any intermediate result/parameter. Every tensor has an attribute (called grad_fn) that represents the entry point to this computational graph, and that is evaluated in the backward pass to compute the actual gradients.
Because of such a flexible design, PyTorch is naturally designed to deal with dynamic neural networks whose topology may change from one iteration to another. Moreover, such a design also generally feels more natural for beginners and new users since there is no strict separation between building the computational graph and executing/feeding data to it, as in TensorFlow v1. Because of its flexible design and ease of use, PyTorch has historically been very popular among researchers and people building prototypes.
Also, PyTorch is fairly lightweight, with several independent modules bundling datasets, transformations, and specific models for a given high-level topic, e.g., torchvision for image-processing tasks, torchtext for NLP tasks, torchaudio for audio and signal processing, torchrec for recommendation system use cases, and torchmetrics for metrics computation.
A simple classification example
Section titled “A simple classification example”We will now translate the previous example of classification with the Fashion-MNIST dataset to highlight the similarities and the key differences between the PyTorch API and syntax (owing to the different designs discussed above). As you will see shortly, since this is an image classification task, we will heavily rely on features of the torchvision library.
Similar to TensorFlow and Keras, PyTorch provides a simple API to load benchmark datasets. However, with PyTorch, we can also set a simple transformation (e.g., rescaling) during the input reading phase. To do so, we need to first define the transformation:
from torchvision import transformstransformer=transforms.Compose([transforms.ToTensor()])This allows us to convert the input images into a tensor with rescaled values. We can then use this transformation when reading the data (note that PyTorch is looking for the dataset in the ./data folder and it will download the dataset if this folder does not exist):
train_dataset = datasets.FashionMNIST( './data', train=True, download=True, transform=transformer)test_dataset = datasets.FashionMNIST('./data', train=False, transform=transformer)Here, the dataset already comes with meta-information about the classes of the samples, which can be accessed through the train_dataset.classes and train_dataset.class_to_idx attributes.
Now that we have loaded the data, we can build the neural network architecture. In PyTorch, this is achieved by extending the torch.nn.Module class and implementing the forward method, with similar layers to the ones used previously in the TensorFlow example:
import torch.nn as nnimport torch.nn.functional as F
class Model(nn.Module): def __init__(self): super().__init__() self.flatten = nn.Flatten() self.fc1 = nn.Linear(28*28, 128) self.dropout = nn.Dropout(0.2) self.fc2 = nn.Linear(128,10)
def forward(self, x): x = self.flatten(x) x = F.relu(self.fc1(x)) x = self.dropout(x) x = self.fc2(x) return F.log_softmax(x, dim=1)
# Instantiate the modelmodel=Model()Once the model is defined, we need to specify the loss function as well as the optimization algorithm to fully specify our training process. Similar to TensorFlow, PyTorch provides some natively implemented functionalities for specifying these settings:
import torch.optim as optimcriterion = nn.CrossEntropyLoss()optimizer = optim.Adam(model.parameters())In addition to using the cross-entropy loss, we will also gather some more insightful performance indicators during training and evaluation using the torchmetrics module:
from torchmetrics.classification import MulticlassAccuracyn_classes = len(train_dataset.classes)accuracy = MulticlassAccuracy(num_classes = n_classes)We now need to implement the training process. As pointed out earlier, PyTorch builds the computational graph at each iteration, and consequently, we will need to implement the gradient updates for each batch separately. PyTorch provides convenient utilities to split the dataset into batches, returning an iterable class:
trainloader = torch.utils.data.DataLoader( train_dataset, batch_size=128, shuffle=True)testloader = torch.utils.data.DataLoader( test_dataset, batch_size=test_dataset.data.shape[0])Note that for tests, we have just created a single batch that includes the full test dataset. With this, we can decompose the training into its batch steps:
for epoch in range(n_epochs): # loop over the dataset multiple times for i, data in enumerate(trainloader, 0): # implement a backpropagation step ... # Evaluate accuracy at the end of epoch for inputs, labels in testloader: preds = model(inputs) print(f"Accuracy on validation set: {float(accuracy(preds, labels))}")PyTorch provides primitives that make it very easy and natural to implement the backpropagation step, explicitly defining the forward pass and the backward one:
inputs, labels = data# Initialize parameters gradientsoptimizer.zero_grad()# Forward passoutputs = model(inputs)loss = criterion(outputs, labels)# Backward passloss.backward() # Computes the gradientoptimizer.step() # Updates the parametersThat’s it! The training of your first neural network in PyTorch is complete. You can find the full example in the notebook attached to this book. Feel free to run it and play around with some of the parameters (model architecture, optimizer specs, etc.).
Classification beyond fully connected layers
Section titled “Classification beyond fully connected layers”In addition to using fully connected layers, we can easily extend our model to incorporate convolutional layers, which are more effective for image data as they utilize the 2D structure of the input. CNNs apply filters across the input image to detect patterns such as edges, textures, or objects. Here’s an example of how to build a simple CNN using Keras:
model = tf.keras.models.Sequential([ tf.keras.layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)), tf.keras.layers.MaxPooling2D((2, 2)), tf.keras.layers.Conv2D(64, (3, 3), activation='relu'), tf.keras.layers.MaxPooling2D((2, 2)), tf.keras.layers.Conv2D(64, (3, 3), activation='relu'), tf.keras.layers.Flatten(), tf.keras.layers.Dense(64, activation='relu'), tf.keras.layers.Dense(10)])In this model, we first apply several convolutional layers followed by max pooling to reduce spatial dimensions, extract features, and pass them to a Dense layer for classification. You can compile and train this model in the same way as before, and it should yield improved performance due to the hierarchical feature extraction from the image.
In PyTorch, building a CNN is just as straightforward as using fully connected layers. CNNs are ideal for image classification tasks because they apply filters to detect patterns in the input images, such as edges or textures, hierarchically. Below is an example of a simple CNN architecture using torch.nn.Conv2d and torch.nn.MaxPool2d layers:
import torch.nn as nnimport torch.nn.functional as F
class CNNModel(nn.Module): def __init__(self): super(CNNModel, self).__init__() # 1 input channel (grayscale), 32 output filters self.conv1 = nn.Conv2d(1, 32, kernel_size=3) self.pool = nn.MaxPool2d(2, 2) # Pooling with a 2x2 window self.conv2 = nn.Conv2d(32, 64, kernel_size=3) self.fc1 = nn.Linear(64 * 5 * 5, 64) # 64 filters output, 5x5 feature map self.fc2 = nn.Linear(64, 10) # 10 output classes
def forward(self, x): x = self.pool(F.relu(self.conv1(x))) x = self.pool(F.relu(self.conv2(x))) x = x.view(-1, 64 * 5 * 5) x = F.relu(self.fc1(x)) x = self.fc2(x) return F.log_softmax(x, dim=1)In this CNN model, we use two convolutional layers (Conv2d) to extract features from the images, followed by max-pooling layers to downsample the feature maps. The output is then flattened and passed through fully connected layers for classification. As before, you can define the loss function, optimizer, and training loop, but now you’re using a more advanced architecture suited for image data.
You may be wondering why we are using images in a graph machine learning book. Just bear with us for now, and hopefully, by the end of this chapter, you’ll realize that this example was not that off-path after all.
Introduction to GNNs
Section titled “Introduction to GNNs”As you will see shortly, the concepts introduced in the previous section can be quite naturally extended to deal with graphs.
GNNs are deep learning methods that work on graph-structured data. This family of methods is sometimes also referred to as geometric deep learning and is gaining increasing popularity in a variety of applications, including social network analysis and computer graphics. The underlying idea of GNNs is a natural extension of CNNs, which we just used in the previous example to process images and have achieved impressive results when dealing with regular Euclidean spaces, such as text (one-dimensional), images (two-dimensional), and videos (three-dimensional). As shown in the previous example, CNN layers combine inputs from their neighborhood, applying a static kernel that is swept throughout the entire space – that is, every single pixel making up the image. Moreover, a classic CNN consists of a sequence of layers and each layer extracts multi-scale localized spatial features. Those features are exploited by deeper layers to construct more complex and highly expressive representations.
We can extend the same concept for graphs that are defined over a non-Euclidean space, for which neighboring information is not provided by the Euclidean distance between the points but provided by the connection information embedded in the graph, as shown in Figure 3.3. Indeed, the original formulation of GNNs (proposed by Scarselli et al. back in 2009) relies, similarly to CNNs, on the fact that each node can be described by its features and its neighborhood. Information coming from the neighborhood (which represents the concept of locality in the graph domain) can be aggregated and used to compute more complex and high-level features.

Figure 3.3 – Visual difference between Euclidean and non-Euclidean neighborhoods
Each node is therefore associated with a set of features or hidden state , where represents the -th layer and is the node’s index. We will be ignoring node attributes for simplicity. At each layer, nodes accumulate input from their neighbors using a simple neural network layer:
Here, and are trainable parameters (where is the number of nodes and the dimension of the features/hidden state). is a non-linear function. It’s important to note that the summation only extends to the neighboring nodes. These equations can be applied recursively, where the previous state, computed at the previous layer, is used to calculate the hidden state of the next layer (similarly to what is generally done in recurrent neural networks).
As a result of this process, we can therefore imagine that we obtain a final hidden state or embedded representation, , which is a function of the input set of features and the topology of the network, represented by the adjacency matrix :
Here, can be seen as a compressed latent representation of the nodes. Note that is actually a new set of features for each node, which can be downstream to other (GNN) layers to create deeper representations. These features can be used to achieve a number of tasks, as we will see in the rest of the book, including classification and forecasting, among others.
Variants of GNNs
Section titled “Variants of GNNs”Several attempts have been made in recent years to address the problem of learning from graph data. Variants of the previously described GNN have been proposed, with the aim of improving its representation learning capability. Some of them are specifically designed to process specific types of graphs (direct, indirect, weighted, unweighted, static, dynamic, and so on).
Graph convolutional network (GCN)-based encoders are one of the most diffused variants of GNN for unsupervised learning. GCNs are GNN models inspired by many of the basic ideas behind CNNs. Filter parameters are typically shared over all locations in the graph and several layers are concatenated to form a deep network.
There are essentially two types of convolutional operations for graph data – namely, spectral approaches and non-spectral (spatial) approaches. The first, as the name suggests, defines convolution in the spectral domain (that is, decomposing graphs in a combination of simpler elements). Spatial convolution formulates the convolution as aggregating feature information from neighbors, as we previously described.
Also, several modifications have been proposed for the propagation step (convolution, gate mechanisms, attention mechanisms, and skip connections, among others), with the aim of improving representation at different levels. Also, different training methods have been proposed to improve learning.
Although these concepts could be implemented using the framework we presented earlier in the chapter (namely, TensorFlow and PyTorch) there also exist libraries built on top of them that make integrating GNNs (in all their flavors) extremely easy, seamless, and fast. In the next section, we will present the most relevant ones.
Frameworks for deep learning on graphs
Section titled “Frameworks for deep learning on graphs”Over the years, a few libraries have been developed to help data scientists integrate graph machine learning, and more specifically, GNNs, into their analytical pipelines. The existence of different libraries is due to different choices of the framework used in the backend (e.g., TensorFlow, PyTorch, etc.), the research group authoring the library (sometimes being an industrial group and sometimes an academic department), as well as some specific needs addressed by the library (e.g., large graphs, dynamic graphs, etc.).
In the following, we will consider three frameworks:
- PyTorch Geometric (PyG):
As the name suggests, PyG (https://pytorch-geometric.readthedocs.io/en/latest/) is a library that is built upon PyTorch, and it provides abstractions and functionalities for defining, training, and evaluating GNNs. More generally, it provides various methods for performing deep learning on graphs and irregular structures. It also constitutes a central repository for existing implementations of published papers and academic research.
- StellarGraph:
StellarGraph was possibly one of the first libraries to appear in the landscape of graph machine learning and GNNs and was designed, developed, and supported by the Data61 team at CSIRO (https://data61.csiro.au/). StellarGraph was built upon TensorFlow 2.x and therefore uses Keras and scikit-learn APIs to provide a modular, extensible, and user-friendly user experience that can be easily integrated with common data analytics pipelines. Besides its analytical capabilities, StellarGraph also features a set of classes and utilities to represent and work with graph data, seamlessly parsing and importing NetworkX objects.
- Deep Graph Library (DGL):
DGL can work on top of multiple existing frameworks, currently supporting PyTorch, MXNet, and TensorFlow (although at the time of writing, the community is progressing more and more toward PyTorch). Moreover, it is powered by a group of committers spanning multiple organizations and universities, including AWS, NVIDIA, New York University, and Georgia Institute of Technology. More importantly, DGL also provides very structured and extensible functionalities to implement message passing and reduction steps, which, as you will see in the next chapters, are some fundamental building blocks for implementing more complex and scalable GNN layers and models.
Despite their unique features and design philosophies, these frameworks share a similar structure that facilitates a comparative analysis. In fact, all the frameworks provide primitives for the following:
- Graph representation
- Data loading
- Model definition
- Training loop
In the following subsections, we will provide an overview of the main similarities and differences that the various framework provides for implementing the operations above.
Graph representation
Section titled “Graph representation”PyG, StellarGraph, and DGL have specific classes to model pairwise relations (edges) between objects (nodes). PyG represents graphs using PyTorch tensors and provides a versatile data structure for storing various types of graph-related information such as adjacency matrices, edge lists, and node features. StellarGraph uses optimized data structures to offer support for different graph formats including NetworkX graphs and pandas DataFrames. Moreover, it uses specialized structures such as the StellarGraph class and StellarDiGraph class for handling different types of graphs efficiently. DGL has its own graph object that can be created from diverse input formats such as adjacency matrices and edge lists. Its unified interface handles both static and dynamic graphs, and this helps ensure compatibility with deep learning models across different scenarios.
Nevertheless, despite the specific implementations of the classes, all three libraries offer methods and attributes to explore and access the graph structure (number of nodes, number of edges, node features, edge features, etc.).
Data loading
Section titled “Data loading”The way the graph structure is loaded into memory depends on several factors, including the specific training algorithm. For example, some models should be trained using samples of nodes, others need subgraphs as input or even the full graph. Moreover, especially when dealing with large-scale graphs that may not fit entirely into memory, designing proper data-loading strategies is crucial. Graph deep learning frameworks offer various strategies to tackle this challenge, enabling the processing of graphs of varying sizes while optimizing resource utilization.
For well-known graph models, the specific graph-splitting implementation (to properly generate training, validation, and test sets) may be already implemented for you. For example, for the well-known GraphSAGE, PyG implements the NeighborLoader and LinkNeighborLoader to choose from, thus making sure the input feeding the models is constructed correctly.
To summarize, the main data loading methods are:
- Loading whole graphs: The simplest approach is to load the entire graph into memory. This method is suitable for smaller graphs that can be accommodated within available memory constraints. All three frameworks support this method, providing utilities to load graph data directly into memory for processing.
- Edge loading: To handle larger graphs, batching the edges is a common strategy employed by these frameworks. In this approach, the graph is partitioned into smaller subgraphs based on edges. Each subgraph is then loaded into memory separately, allowing for efficient processing of large graphs by working on smaller chunks at a time.
- Node loading: Similar to edges, batching of nodes involves partitioning the graph based on nodes instead of edges. This method divides the graph into smaller subgraphs, each containing a subset of nodes and their associated edges. By loading these subgraphs individually, node splitting enables the processing of large graphs in a memory-efficient manner.
Moreover, in addition to traditional data-loading methods, these frameworks also support data augmentation techniques for generating synthetic graphs or augmenting existing graph data.
Note that the implementation of the data-loading process for each framework reflects the style of the framework itself (Keras for StellarGraph, PyTorch for PyG, and DGL). Therefore, you will find “generators” for Keras-inspired frameworks and “data loaders” for PyTorch-inspired ones. It is worth mentioning that, unlike traditional deep learning settings where splitting data into training and validation sets is straightforward, doing the same for graph data is not easy. When dealing with a graph-level task (your dataset consists of a set of graphs), splitting a single graph into training and validation sets involves sampling a set of edges or nodes in a proper way; otherwise, improper splitting can lead to data leakage. Some of these “splitting” (or sampling) strategies are already implemented in the various frameworks and are often embedded in the data-loading process. We will discuss this topic further and how to avoid data leakage in graph settings in Chapter 6, Solving Common Graph-Based Machine Learning Problems, when discussing the link prediction problem.
Model definition
Section titled “Model definition”Once you understand how to represent a graph in the specific framework and how to load it (or part of it), it is time to define the actual deep learning model. In the next chapters, you will learn about several variants of GNNs. For now, it is sufficient to know that each of these frameworks implements most of these variants and you can simply use them to solve your problem without dealing with their internal implementation (similarly to what you do when using standard CNN models and layers in Tensorflow and PyTorch). Some of these classes include graph convolutional layers, GraphSAGE, and graph attention layers, among others.
Training loop
Section titled “Training loop”Optimizing the model involves iterative batch processing, loss calculation, and parameter updates. These operations are supported by all three frameworks and are strictly related to the deep learning framework used as the backend (PyG and DGL use a PyTorch-like training approach, while StellarGraph exposes the “fit” method typical of Keras).
In the rest of the chapter, we will show you how easy it is to use each of these frameworks by implementing a simple “link prediction” task on top of the Cora dataset. Without going into much detail (you will be learning about several problems that can be solved with machine learning on graphs in the next chapters), the task of link prediction consists of predicting whether a link exists between two given nodes. The Cora dataset is a perfect example for this task, featuring a collaboration network of 2,700+ scientific publications, classified into 7 classes. The citation links consist of 5,400+ links and each node (representing a publication) is described by a 1,433-size vector indicating the presence/absence of a particular word from a restricted vocabulary of 1,433 words. This representation is a simplified version of the so-called bag-of-words representation. Therefore, the Cora dataset, thanks to the node features, represents a very suitable dataset on which a GNN and GCN can be implemented.
Interestingly, the link prediction task may also correspond to reconstructing the original graph from the compact representation of the nodes, . Indeed, we would be successful at our prediction task when the “predicted” edges correspond to the ones actually existing in the “target” graph. In view of this, the link prediction task is therefore closely connected to graph auto-encoders (GAEs), which encode the nodes into a compact representation and then decode such information to reconstruct the original topology, minimizing the difference between the original and the reconstructed graph. We will digress more on auto-encoders in the next chapter, but to start, a simple way to reconstruct the adjacency matrix using the compressed representation is by means of the inner product:
Here, can be viewed as the probability that a link exists between node and node . The reconstructed matrix can be expressed as:
In the next examples, you will see how this can easily be done with the frameworks.
PyG provides a simple API to load the Cora dataset. Similar to what we have done previously, we add some transformation in the data-loading phase to normalize the data and to split it (note that, this time, the function comes from PyG as it is specifically designed to work with graph datasets). Moreover, besides normalization, we generate a positive (existing) and negative (non-existing) list of edges, which we will use to make sure that the reconstructed graph correctly provides edges only where they exist. Because of the specific auto-encoder implementation in PyG, negative edges are not required for the training; therefore, we will only generate them for the test set:
import torch_geometric.transforms as Tfrom torch_geometric.datasets import Planetoid
transform = T.Compose([ T.NormalizeFeatures(), T.RandomLinkSplit( num_val=0., num_test=0.1, is_undirected=True, split_labels=True, add_negative_train_samples=False ),])path = os.path.join(DATA_PATH, 'data')dataset = Planetoid(path, "Cora", transform=transform)train_data, val_data, test_data = dataset[0]The datasets that have been generated (train_data, val_data, and test_data) bundle topology information, node features, and labels. For instance, the matrix with node features can be accessed via the following:
train_data.x # of shape (N_nodes, 1433)The vector with label information can be accessed via:
train_data.y # of shape (N_nodes) with numerical values representing # the labelsThe edges (topology) of the graph can be found with:
train_data.edge_index # of shape (2, N_edges)Moreover, the RandomLinkSplit class also generates a list of positive and negative labels:
test_data.pos_edge_label_index # of shape (2, N_positive_edges)test_data.neg_edge_label_index # of shape (2, N_negative_edges)Note that since we specified add_negative_train_samples=False, negative edges are not generated for the training set.
To build the model, we will implement a GAE in PyG that will allow us to reconstruct the original graph. We first start by defining the structure for the encoder using a GNN based on two GCN layers. PyG makes this extremely easy. We first create the encoder layer:
from torch_geometric.nn import GCNConv
class GCNEncoder(torch.nn.Module): def __init__(self, num_node_features, num_embedding): super().__init__() self.conv1 = GCNConv(num_node_features, 2 * num_embedding) self.conv2 = GCNConv(2 * num_embedding, num_embedding)
def forward(self, x, edge_index): x = self.conv1(x, edge_index).relu() return self.conv2(x, edge_index)Note that the forward function of GCNs in PyG always takes two required arguments and one optional argument: the first required argument is the tensor of the node features, the second required argument is edge_indices (or the adjacency matrix), and the third, optional argument is the edge weights. Once the encoder is defined, the GAE can be created with one single command:
from torch_geometric.nn import GAE
model = GAE(GCNEncoder(1433, n_embeddings))The GAE class already implements the decoder layer for us (using the inner product between the vector of embedding). It also provides some useful functions to compute the loss as well as evaluate the model during training, as we will see shortly.
As usual, to fully specify the training, we need to define the optimizer to be used (since we will be using the loss implemented in the GAE class):
optimizer = torch.optim.Adam(model.parameters(), lr=0.01)Using this, we can implement the training procedure using the usual PyTorch functionalities:
for epoch in range(num_epochs): # zero the parameter gradients model.train() optimizer.zero_grad() z = model.encode(train_data.x, train_data.edge_index) loss = model.recon_loss(z, train_data.pos_edge_label_index) loss.backward() optimizer.step()
# Test/Evaluate model.eval() z = model.encode(test_data.x, test_data.edge_index) auc, ap = model.test( z, test_data.pos_edge_label_index, test_data.neg_edge_label_index )print(f"Performance on validation set => Area Under the ROC Curve: {auc} Average Precision: {ap}")During training, we can monitor prediction performances by using common metrics such as area under the ROC curve (AUC) or average precision. By maximizing one of these, we can build a robust model that may either prioritize precision or recall, or a combination of them, and that is able to best generalize on future cases.
The GAE is now implemented and trained, and its output can be used to generate some node embeddings, similar to what was previously done for images.
StellarGraph
Section titled “StellarGraph”To load the Cora dataset into a StellarGraph Graph object, you can simply run the following code:
from stellargraph import datasets
dataset = datasets.Cora()G, _ = dataset.load()G represents the graph structure with several useful methods readily available to the user, such as G.info() to display the main information of the dataset:
StellarGraph: Undirected multigraph Nodes: 2708, Edges: 5429 Node types: paper: [2708] Features: float32 vector, length 1433 Edge types: paper-cites->paper Edge types: paper-cites->paper: [5429] Weights: all 1 (default) Features: noneAs you can see, StellarGraph supports both node and edge features (although, in this case, edges do not have any features) as well as the possibility of defining a taxonomy for the node and edge types.
Similar to what is provided in PyG, StellarGraph also provides functionality to split edges into positive and negative samples:
edge_splitter_test = EdgeSplitter(G)G_test, edge_ids_test, edge_labels_test = edge_splitter_test.train_test_split( p=0.1, method="global", keep_connected=True)
edge_splitter_train = EdgeSplitter(G_test)G_train, edge_ids_train, edge_labels_train = edge_splitter_train.train_test_split( p=0.1, method="global", keep_connected=True)Note that, in this case, we also create the reduced graph where we remove the test edges (G_test) and the test and train edges (G_train). Since this is an auto-encoder, we will not use these graphs, but as you will see in the following code, in predictive tasks (e.g., node/edge classification), this will be very important to prevent data leakage from training to test sets.
StellarGraph also provides a simple API to create both the input tensors and the computational graph that will be fed into TensorFlow. In particular, FullBatchLinkGenerator allows us to supply both the node features as well as the graph data (i.e., adjacency matrix) to be used on different kinds of models. In the following code, since we will be using a GCN, we create the inputs as follows:
train_gen = FullBatchLinkGenerator(G, method="gcn")train_flow = train_gen.flow(edge_ids_train, edge_labels_train)FullBatchLinkGenerator specifically generates batches that include all the nodes in the graph in a single batch. This is in contrast to mini-batch training, where only a subset of the graph is used in each iteration. Full-batch training can be memory-intensive, but it’s useful when you want to train a model on the whole graph at once. The flow method of the generator creates a data generator (a flow) that will feed the graph data to the model during training. This method prepares the actual data that will be passed to the GNN model, including the edges and their corresponding labels.
Creating a GCN model is extremely easy using the built-in functionalities:
gcn = GCN( layer_sizes=[16, 16], activations=["relu", "relu"], generator=train_gen, dropout=0.3)The GCN class also allows us to extract the input and output tensors:
x_input, z = gcn.in_out_tensors()If you inspect the x_input result, you will note that x_input is formed by four sub-inputs, corresponding to:
- The matrix of node features
- The edges we want to evaluate (whether they exist or not)
- The edge list of the graph
- The corresponding labels of the graph edges
These inputs also correspond to what is provided by the train_flow.inputs property, therefore making it seamless to create a full model of our auto-encoder. In fact, we only need to combine the embeddings using the inner product (as specified below by “ip”) and reshape it to match the expected dimension:
prediction = LinkEmbedding(activation="relu", method="ip")(z)prediction = keras.layers.Reshape((-1,))(prediction)As with a normal TensorFlow model, we now just need to compile the model:
model = keras.Model(inputs=x_input, outputs=prediction)model.compile( optimizer=keras.optimizers.Adam(lr=0.01), loss=keras.losses.binary_crossentropy, metrics=["binary_accuracy"])Finally, the GNN can be simply trained using the standard API:
history = model.fit(train_flow, epochs=50)Disclaimer
Owing to such a clean API and structured integration with TensorFlow (which is perhaps the standard de facto for production-ready applications based on neural networks), StellarGraph was the library chosen in the first edition of this book. Unfortunately, shortly after the publication of the first edition, this library stopped being actively maintained. Therefore, although the functionalities provided by the library are still extremely useful (especially for dynamic and temporal graphs), we advise you to consider this choice carefully if you need to provide long-term support for applications powered by your graph machine models. In this scenario, currently maintained frameworks such as PyG or DGL would be more appropriate, and whenever possible, examples using these frameworks will be provided alongside their StellarGraph implementations in the GitHub repository. However, it is important to note that StellarGraph still retains significant pedagogical value: its Keras-based coding style allows for concise and clear demonstrations of key concepts, making it an excellent tool for learning and experimentation. Therefore, the core ideas presented using StellarGraph can be easily translated to other frameworks, ensuring that the knowledge gained remains broadly applicable.
Similar to PyG and StellarGraph, DGL aims to provide a set of tools for an easy implementation of GNNs. To perform link prediction using DGL, first, you need to construct the graph object representing your dataset. DGL provides various methods to load and manipulate graph data efficiently. For example, to load a dataset like Cora into a DGL Graph object, you might use the following code:
import dglimport dgl.data
dataset = dgl.data.CoraGraphDataset()G = dataset[0]Once you have your graph, let’s split it into positive and negative examples and divide them into training and test sets, similar to other libraries like PyG. DGL provides some utilities to iterate over edges for link prediction tasks. One such way is to use a “sampler” to sample edges from the graph. With the following code, you will be creating a data loader that samples five negative examples per positive example:
sampler = dgl.dataloading.MultiLayerFullNeighborSampler(2)sampler = dgl.dataloading.as_edge_prediction_sampler( sampler, negative_sampler=dgl.dataloading.negative_sampler.Uniform(5))train_seeds = torch.arange(G.num_nodes())batch_size = 48num_workers = 4
dataloader = dgl.dataloading.DataLoader( G, train_seeds, sampler, batch_size=batch_size, shuffle=True, drop_last=False, num_workers=num_workers)Next, you can define your model architecture. DGL supports various types of GNNs, including GCNs, graph attention networks (GATs), and more (we will take a look at these types of models next, in Chapter 4, Unsupervised Graph Learning). For example, to create a GCN for link prediction, you can use the following code:
import torchimport torch.nn as nnimport dgl.nn as dglnnimport torch.nn.functional as F
class StochasticTwoLayerGCN(nn.Module): def __init__(self, in_features, hidden_features, out_features): super().__init__() self.conv1 = dgl.nn.GraphConv(in_features, hidden_features) self.conv2 = dgl.nn.GraphConv(hidden_features, out_features)
def forward(self, blocks, x): x = F.relu(self.conv1(blocks[0], x)) x = F.relu(self.conv2(blocks[1], x)) return x
class ScorePredictor(nn.Module): def forward(self, edge_subgraph, x): with edge_subgraph.local_scope(): edge_subgraph.ndata['x'] = x edge_subgraph.apply_edges(dgl.function.u_dot_v('x', 'x', 'score')) return edge_subgraph.edata['score']
class Model(nn.Module): def __init__(self, in_features, hidden_features, out_features): super().__init__() self.gcn = StochasticTwoLayerGCN( in_features, hidden_features, out_features) self.predictor = ScorePredictor()
def forward(self, positive_graph, negative_graph, blocks, x): x = self.gcn(blocks, x) pos_score = self.predictor(positive_graph, x) neg_score = self.predictor(negative_graph, x) return pos_score, neg_scoreAfter defining the model, you can train it using the standard PyTorch training loop, similar to other deep learning tasks:
def compute_loss(pos_score, neg_score): # an example hinge loss n = pos_score.shape[0] return (neg_score.view(n, -1) - pos_score.view(n, -1) + 1).clamp(min=0).mean()
in_features = G.ndata["feat"].shape[1]model = Model(in_features, 256, 1)opt = torch.optim.Adam(model.parameters())
for input_nodes, positive_graph, negative_graph, blocks in dataloader: blocks = [b for b in blocks] input_features = blocks[0].srcdata['feat']
# inference and loss computation pos_score, neg_score = model(positive_graph, negative_graph, blocks, input_features) loss = compute_loss(pos_score, neg_score) print(loss)
opt.zero_grad() loss.backward() opt.step()Notice that we skipped the validation part to improve readability. However, similar to the standard PyTorch training loop, you can implement it by defining a proper data loader and calling it in the training loop.
Be aware that, at the time of writing, DGL has just discontinued support on Darwin and Windows platforms, applying to versions higher than 2.2.1. In the following, we will often make use of version 2.4.0+. If you are running on one of the unsupported platforms, we recommend using the Docker images provided with the book.
Summary
Section titled “Summary”In this chapter, you have seen an introduction to neural networks and how they can be used in practice using popular frameworks like TensorFlow and PyTorch. You have seen how to translate those concepts into the graph domain, and you have learned the basics of three modern frameworks for deep learning on graphs: PyG, StellarGraph, and DGL. It is worth noting that some concepts may seem unclear at this point. Don’t worry! In the next chapters, all these concepts will be examined in more detail.
Get ready to embark on our journey into the GraphML landscape as we explore Unsupervised Graph Learning in the next chapter!