Supervised Graph Learning
local graph
Chapter 05: Supervised Graph Learning
Section titled “Chapter 05: Supervised Graph Learning”Supervised graph embedding — feature-based methods, label propagation, graph regularization, manifold regularization, neural graph learning, Planetoid, GCN graph classification, GraphSAGE node classification.
Supervised learning likely represents the majority of practical machine learning (ML) tasks. Thanks to more and more active and effective data collection activities, it is very common nowadays to deal with labeled datasets.
This is also true for graph data, where labels can be assigned to nodes, communities, or even an entire structure. The task, then, is to learn a mapping function between the input and the label (also known as a target or an annotation).
For example, given a graph representing a social network, we might be asked to guess which user (node) will close their account. Or, similarly, we might be asked to predict the number of posts a user will make over the next month. We can learn these predictive functions by training graph ML on retrospective data, where each user is labeled as “faithful” or “quitter” based on whether they closed their account after a few months. Similarly, users could be associated with the number of posts they published in the previous month.
In this chapter, we will explore the concept of supervised graph learning. Therefore, we will also be providing an overview of the main supervised graph embedding methods. The following topics will be covered:
- The supervised graph embedding roadmap
- Feature-based methods
- Shallow embedding methods
- Graph regularization methods
- Graph convolutional neural networks (CNNs)
The supervised graph embedding roadmap
Section titled “The supervised graph embedding roadmap”In supervised learning, a training set consists of a sequence of ordered pairs (, ), where is a set of input features (often signals defined on graphs) and is the output label assigned to it. The goal of ML models, then, is to learn the function mapping each value to each value. Here, can be either a categorical or a continuous variable, depending on whether we are addressing a classification or a regression problem. Common supervised tasks include predicting user properties in a large social network or predicting molecules’ attributes, where each molecule is a graph. Sometimes, however, not all instances can be provided with a label. In this scenario, a typical dataset consists of a small set of labeled instances and a larger set of unlabeled instances. For such situations, semi-supervised learning is proposed, whereby algorithms aim to exploit label dependency information reflected by available label information in order to learn the predicting function for the unlabeled samples.
With regard to supervised graph ML techniques, many algorithms have been developed, aimed at learning an embedding function for graphs while solving a certain supervised task. However as previously reported by different scientific papers (https://arxiv.org/abs/2005.03675), they can be grouped into macro-groups, depending on how each method encodes the graph information to produce the embeddings. These groups are:
- Feature-based methods
- Shallow embedding methods
- Regularization methods
- Graph neural networks (GNNs)
They are graphically depicted in the following diagram:

Figure 5.1: Hierarchical structure of the different supervised embedding algorithms described in this book
In the following sections, you will learn the main principles behind each group of algorithms. We will try to provide insight into the most well-known algorithms in the field as well, as these can be used to solve real-world problems.
Feature-based methods
Section titled “Feature-based methods”One very simple (yet powerful) method for applying ML on graphs is to consider the encoding function as a simple embedding lookup. When dealing with supervised tasks, one simple way of doing this is to exploit graph properties. In Chapter 1, Getting Started with Graphs, we learned how graphs (or nodes in a graph) can be described by means of structural properties, each “encoding” important information from the graph itself.
Let’s forget graph ML for a moment; in classical supervised ML, the task is to find a function that maps a set of (descriptive) features of an instance to a particular output. Such features should be carefully engineered so that they are sufficiently representative to learn that concept. Therefore, as the number of petals and the sepal length might be good descriptors for a flower, when describing a graph, we might rely on its average degree, its global efficiency, and its characteristic path length.
This naïve approach acts in two steps, outlined as follows:
- Select a set of good descriptive graph properties.
- Use such properties as input for a traditional ML algorithm.
Unfortunately, there is no general definition of good descriptive properties, and their choice strictly depends on the specific problem to solve. However, you can still compute a wide variety of graph properties and then perform feature selection to select the most informative ones. Feature selection is a widely studied topic in ML, but providing details about the various methods is outside the scope of this book. However, we refer you to the book Machine Learning Algorithms – Second Edition (https://subscription.packtpub.com/book/big_data_and_business_intelligence/9781789347999), published by Packt Publishing, for further reading on this subject.
Let’s now see a practical example of how such a basic method can be applied. We will be performing a supervised graph classification task by using the PROTEINS dataset. The PROTEINS dataset contains several graphs representing protein structures. Each graph is labeled, defining whether the protein is an enzyme or not. We will follow these steps:
-
First, let’s load the dataset through the
stellargraphPython library, as follows:from stellargraph import datasetsfrom IPython.display import display, HTMLdataset = datasets.PROTEINS()graphs, graph_labels = dataset.load() -
For computing graph properties, we will be using
networkx, as described in Chapter 1, Getting Started with Graphs. To that end, we need to convert graphs from thestellargraphformat to thenetworkxformat. This can be done in two steps: first, convert the graphs from thestellargraphrepresentation tonumpyadjacency matrices. Then, use the adjacency matrices to retrieve thenetworkxrepresentation. In addition (as we will see in the next steps), we also transform the labels (which are stored as apandasSeries) to anumpyarray, which can be better exploited by the evaluation functions. The code is illustrated in the following snippet:# convert from StellarGraph format to numpy adj matricesadjs = [graph.to_adjacency_matrix().A for graph in graphs]# convert labels from Pandas.Series to numpy arraylabels = graph_labels.to_numpy(dtype=int) -
Then, for each graph, we compute global metrics to describe it. For this example, we have chosen the number of edges, the average cluster coefficient, and the global efficiency. However, we suggest you compute several other properties you may find worth exploring. We can extract the graph metrics using
networkx, as follows:import numpy as npimport networkx as nxmetrics = []for adj in adjs:# from numpy to networkxG = nx.from_numpy_matrix(adj)# basic propertiesnum_edges = G.number_of_edges()# clustering measurescc = nx.average_clustering(G)# measure of efficiencyeff = nx.global_efficiency(G)metrics.append([num_edges, cc, eff]) -
We can now exploit scikit-learn utilities to create train and test sets. In our experiments, we will be using 70% of the dataset as the training set and the remainder as the test set. We can do that by using the
train_test_splitfunction provided by scikit-learn, as follows:from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(metrics, labels, test_size=0.3, random_state=42) -
It’s now time to train a proper ML algorithm. We chose a support vector machine (SVM) for this task. More precisely, the SVM is trained to minimize the difference between the predicted labels and the actual labels (the ground truth). We can do this by using the
SVCmodule of scikit-learn. In addition, we use the accuracy, precision, recall, andF1-scoreto evaluate how well the algorithm is performing on the test set:from sklearn import svmfrom sklearn.metrics import accuracy_score, precision_score, recall_score, f1_scoreclf = svm.SVC()clf.fit(X_train, y_train)y_pred = clf.predict(X_test)print('Accuracy', accuracy_score(y_test,y_pred))print('Precision', precision_score(y_test,y_pred))print('Recall', recall_score(y_test,y_pred))print('F1-score', f1_score(y_test,y_pred))
This should be the output of the previous snippet of code:
Accuracy 0.7455Precision 0.7709Recall 0.8413F1-score 0.8045We achieved about 80% for the F1 score, which is already quite good for such a naïve task. Moreover, we can observe from the accuracy, precision and recall that performance is quite balanced between classes!
Using graph properties as descriptive features for traditional supervised learning has several strengths. It is straightforward to implement, leverages well-established ML techniques, and allows for interpretability through human-understandable features like average degree or path length. However, it heavily relies on the careful selection and engineering of graph properties, which can be time-consuming and domain-specific. Additionally, this approach may struggle at capturing complex relationships inherent in graph data.
These limitations pave the way for shallow embedding methods, which automate the process of feature extraction by learning representations directly from the graph structure.
Shallow embedding methods
Section titled “Shallow embedding methods”As we already described in Chapter 4, Unsupervised Graph Learning, shallow embedding methods are a subset of graph embedding methods that learn node, edge, or graph representations for only a finite set of input data. They are transductive methods, since they cannot be applied to other instances different from the ones used to train the model. Before starting our discussion, it is important to define how supervised and unsupervised shallow embedding algorithms differ.
The main difference between unsupervised and supervised embedding methods essentially lies in the task they attempt to solve. Indeed, if unsupervised shallow embedding algorithms try to learn a good graph, node, or edge representation in order to understand the underlying structure, the supervised algorithms try to find the best solution for a prediction task such as node classification, label prediction, or graph classification.
In this section, we will explain in detail some of those supervised shallow embedding algorithms. Moreover, we will enrich our description by providing several examples of how to use those algorithms in Python. For all the algorithms described in this section, we will present a custom implementation using the base classes available in the scikit-learn library.
Label propagation algorithm
Section titled “Label propagation algorithm”The label propagation algorithm is a well-known semi-supervised algorithm widely applied in data science and used to solve the node classification task. More precisely, the algorithm propagates the label of a given node to its neighbors or to nodes with a high probability of being reached from that node.
The general idea behind this approach is quite simple: given a graph with a set of labeled and unlabeled nodes, the labeled nodes propagate their label to the nodes with the highest probability of being reached. In the following diagram, we can see an example of a graph with labeled and unlabeled nodes:

Figure 5.2: Example of a graph with two labeled nodes (class 0 in red and class 1 in green) and six unlabeled nodes
According to Figure 5.2, using the information of the labeled nodes (node 0 and 6), the algorithm will calculate the probability of moving to another unlabeled node. The nodes with the highest probability from a labeled node will get the label of that node.
Formally, let be a graph and let be a set of labels. Since the algorithm is semi-supervised, just a subset of nodes will have an assigned label. Moreover, let be the adjacency matrix of the input graph and be the diagonal degree matrix where each element is defined as follows:
Where is the degree of the node . In other words, the only nonzero elements of the degree matrix are the diagonal elements whose values are given by the degree of the node represented by the row. In the following figure, we can see the diagonal degree matrix of the graph represented in Figure 5.2:

Figure 5.3: Diagonal degree matrix for the graph in Figure 5.2
From Figure 5.3, it is possible to see how only the diagonal elements of the matrix contain nonzero values, and those values represent the degree of the specific node. We also need to introduce the transition matrix . This matrix defines the probability of a node being reached from another node. More precisely, is the probability of reaching node from node . The following figure shows the transition matrix L for the graph depicted in Figure 5.2:

Figure 5.4: Transition matrix for the graph in Figure 5.2
In Figure 5.4, the matrix shows the probability of reaching an end node given a start node. For instance, from the first row of the matrix, we can see how from node 0 it is possible to reach, with equal probability of 0.5, only nodes 1 and 2. If we defined with the initial label assignment, the probability of label assignment for each node obtained using the matrix can be computed as . The matrix computed for the graph in Figure 5.2 is shown in the following figure:

Figure 5.5: Solution obtained using the matrix for the graph in Figure 5.2
From Figure 5.5, we can see that using the transition matrix, node 1 and node 2 have a probability of being assigned to the [1 0] label of 0.5 and 0.33, respectively, while node 5 and node 6 have a probability of being assigned to the [0 1] label of 0.33 and 0.5, respectively.
Moreover, if we better analyze Figure 5.5, we can see two main problems, as follows:
- With this solution, it is possible to assign only to nodes [1 2] and [5 7] a probability associated with a label.
- The initial labels of nodes 0 and 6 are different from the one defined in .
In order to solve the first point, the algorithm will perform different iterations; at each iteration , the algorithm will compute the solution for that iteration, as follows:
Where T is the transition matrix and is the label assignment at time t-1. The algorithm stops its iteration when a certain condition is met, such as when the labels of all nodes remain unchanged between iterations, or a maximum number of iterations is reached. The second problem is solved by the label propagation algorithm by imposing, in the solution of a given iteration , the labeled nodes to have the initial class values. For example, after computing the result visible in Figure 5.5, the algorithm will force the first line of the result matrix to be [1 0] and the seventh line of the matrix to be [0 1].
Here, we propose a modified version of the LabelPropagation class available in the scikit-learn library. The main reason behind this choice is given by the fact that the LabelPropagation class takes as input a matrix representing a dataset. Each row of the matrix represents a sample, and each column represents a feature.
Before performing a fit operation, the LabelPropagation class internally executes the _build_graph function. This function builds a graph representation of the input dataset by applying a parametric kernel, such as k-nearest neighbors (kNNs) or radial basis functions.
The kernel can be specified using the _get_kernel function. As a result, the original dataset is transformed into a graph (in its adjacency matrix representation) where each node is a sample (a row of the input dataset) and each edge is an interaction between the samples.
In our specific case, the input dataset is already a graph, so we need to define a new class capable of dealing with a networkx graph and performing the computation operation on the original graph. The goal is achieved by creating a new class—namely, GraphLabelPropagation—by extending the ClassifierMixin, BaseEstimator, and ABCMeta base classes. The algorithm proposed here is mainly used in order to help you understand the concept behind the algorithm. The whole algorithm is provided in the 05_supervised_graph_machine_learning/02_Shallow_embeddings.ipynb notebook available in the GitHub repository of this book. In order to describe the algorithm, we will use only the fit(X,y) function as a reference. The code is illustrated in the following snippet:
class GraphLabelPropagation(ClassifierMixin, BaseEstimator, metaclass=ABCMeta): def fit(self, X, y): X, y = self._validate_data(X, y) self.X_ = X check_classification_targets(y) D = [X.degree(n) for n in X.nodes()] D = np.diag(D) # label construction # construct a categorical distribution for classification only unlabeled_index = np.where(y==-1)[0] labeled_index = np.where(y!=-1)[0] unique_classes = np.unique(y[labeled_index]) self.classes_ = unique_classes Y0 = np.array([self.build_label(y[x], len(unique_classes)) if x in labeled_index else np.zeros(len(unique_classes)) for x in range(len(y))]) A = inv(D)*nx.to_numpy_matrix(G) Y_prev = Y0 it = 0 c_tool = 10 while it < self.max_iter & c_tool > self.tol: Y = A*Y_prev Y = Y / (Y.sum(axis=1) + 1e-7) # Normalize # force labeled nodes Y[labeled_index] = Y0[labeled_index] it +=1 c_tol = np.sum(np.abs(Y-Y_prev)) Y_prev = Y self.label_distributions_ = Y return selfThe fit(X,y) function takes as input a networkx graph and an array representing the labels assigned to each node. Nodes without labels should have a representative value of -1. The while loop performs the real computation. More precisely, it computes the value at each iteration and forces the labeled nodes in the solution to be equal to their original input value. The algorithm performs the computation until the two stop conditions are satisfied. In this implementation, the following two criteria have been used:
- Number of iterations: The algorithm runs the computation until a given number of iterations has been performed.
- Solution tolerance error: The algorithm runs the computation until the absolute difference of the solution obtained in two consecutive iterations, and , is lower than a given threshold value.
The algorithm can be applied to the example graph depicted in Figure 5.2 using the following code:
glp = GraphLabelPropagation()y = np.array([-1 for x in range(len(G.nodes()))])y[0] = 0y[6] = 1glp.fit(G,y)glp.predict_proba(G)The result obtained by the algorithm is shown in the following diagram:

Figure 5.6: The final labeled graph (left) and the final probability assignment matrix (right) generated after applying the label propagation algorithm on the graph shown in Figure 5.2
In Figure 5.6, we can see the results of the algorithm applied to the example shown in Figure 5.2. From the final probability assignment matrix, it is possible to see how the probability of the initial labeled nodes is 1 due to the constraints of the algorithm and how nodes that are “near” to labeled nodes get their label.
Label spreading algorithm
Section titled “Label spreading algorithm”The label spreading algorithm is another semi-supervised shallow embedding algorithm. It was built in order to overcome one big limitation of the label propagation method: the initial labeling. Indeed, according to the label propagation algorithm, the initial labels cannot be modified in the training process and, in each iteration, they are forced to be equal to their original value. This constraint could generate incorrect results when the initial labeling is affected by errors or noise. As a consequence, the error will be propagated in all nodes of the input graph.
In order to solve this limitation, the label spreading algorithm tries to relax the constraint of the original labeled data, allowing the labeled input nodes to change their label during the training process.
Formally, let be a graph and let be a set of labels (since the algorithm is semi-supervised, just a subset of nodes will have an assigned label), and let and be the adjacency matrix and diagonal degree matrix of graph G, respectively. Instead of computing the probability transition matrix, the label spreading algorithm uses the normalized graph Laplacian matrix, defined as follows:
Where A is the adjacency matrix and D is the diagonal matrix. As with label propagation, this matrix can be seen as a sort of compact low-dimensional representation of the connections defined in the whole graph. This matrix can be easily computed using networkx with the following code:
from scipy.linalg import fractional_matrix_powerD_inv = fractional_matrix_power(D, -0.5)L = D_inv*nx.to_numpy_matrix(G)*D_invAs a result, we get the following:

Figure 5.7: The normalized graph Laplacian matrix
The most important difference between the label spreading and label propagation algorithms is related to the function used to extract the labels. If we define with the initial label assignment, the probability of a label assignment for each node obtained using the matrix can be computed as follows:
Where is the regularization parameter that controls the influence of the graph structure versus the initial label assignment. As with label propagation, label spreading has an iterative process to compute the end solution. The algorithm will perform n different iterations; in each iteration t, the algorithm will compute the solution for that iteration, as follows:
The algorithm stops its iteration when a certain condition is met. Common stopping conditions include convergence, where the labels no longer change between iterations, or reaching a maximum number of iterations specified by the user. It is important to underline the term of the equation. Indeed, as we said, label spreading does not force the labeled element of the solution to be equal to its original value. Instead, the algorithm uses a regularization parameter to weigh the influence of the original solution at each iteration. This allows us to explicitly impose the “quality” of the original solution and its influence on the end solution.
As with the label propagation algorithm, in the following code snippet, we propose a modified version of the LabelSpreading class available in the scikit-learn library due to the motivations we already mentioned in the previous section. We propose the GraphLabelSpreading class by extending our GraphLabelPropagation class, since the only difference will be in the fit() method of the class. The whole algorithm is provided in the 05_supervised_graph_machine_learning/02_Shallow_embeddings.ipynb notebook available in the GitHub repository of this book:
class GraphLabelSpreading(GraphLabelPropagation): def fit(self, X, y): X, y = self._validate_data(X, y) self.X_ = X check_classification_targets(y) D = [X.degree(n) for n in X.nodes()] D = np.diag(D) D_inv = np.matrix(fractional_matrix_power(D,-0.5)) L = D_inv*nx.to_numpy_matrix(G)*D_inv # label construction # construct a categorical distribution for classification only labeled_index = np.where(y!=-1)[0] unique_classes = np.unique(y[labeled_index]) self.classes_ = unique_classes Y0 = np.array([self.build_label(y[x], len(unique_classes)) if x in labeled_index else np.zeros(len(unique_classes)) for x in range(len(y))]) Y_prev = Y0 it = 0 c_tool = 10 while it < self.max_iter & c_tool > self.tol: Y = (self.alpha*(L*Y_prev))+((1-self.alpha)*Y0) it +=1 Y = Y / (Y.sum(axis=1) + 1e-7) # Normalize c_tol = np.sum(np.abs(Y-Y_prev)) Y_prev = Y self.label_distributions_ = Y return selfAlso in this class, the fit() function is the focal point. The function takes as input a networkx graph X and an array Y representing the labels assigned to each node. Nodes without labels should have a representative value of -1. The while loop computes the value at each iteration, weighting the influence of the initial labeling via the parameter . Also, for this algorithm, the number of iterations and the difference between two consecutive solutions are used as stop criteria.
The algorithm can be applied to the example graph depicted in Figure 5.2 using the following code:
gls = GraphLabelSpreading()y = np.array([-1 for x in range(len(G.nodes()))])y[0] = 0y[6] = 1gls.fit(G,y)gls.predict_proba(G)In the following diagram, the result obtained by the algorithm is shown:

Figure 5.8: The final labeled graph (left) and the final probability assignment matrix (right) generated after applying the label propagation algorithm on the graph shown in Figure 5.2
The result visible in the diagram shown in Figure 5.8 looks similar to the one obtained using the label propagation algorithm.
In the next section, we will continue our description of supervised graph embedding methods. We will describe how network-based information helps regularize the training and create more robust models.
Graph regularization methods
Section titled “Graph regularization methods”The shallow embedding methods described in the previous section show how topological information and relations between data points can be encoded and leveraged in order to build more robust classifiers and address semi-supervised tasks. In general terms, network information can be extremely useful in constraining models and enforcing the output to be smooth within neighboring nodes. As we have already seen in previous sections, this idea can be efficiently used in semi-supervised tasks, when propagating the information on neighbor unlabeled nodes.
On the other hand, this can also be used to regularize the learning phase in order to create more robust models that tend to better generalize to unseen examples. Both the label propagation and the label spreading algorithms we have seen previously can be implemented as a cost function to be minimized when we add an additional regularization term. Generally, in supervised tasks, we can write the cost function to be minimized in the following form:
Let’s break down the equation. We have two terms in the sum: the first term focuses on fitting the model to the labeled data, while the second term ensures that the model takes advantage of the graph structure to regularize predictions. Let’s look at this in more detail.
is the supervised loss term. It measures how well the predicted label matches the true label for each labeled sample . Its exact form depends on the problem; it can be a common loss function like mean squared error (MSE) (for regression tasks) or cross-entropy loss (for classification tasks).
is the graph-based regularization term. It uses the graph structure G to enforce consistency in predictions. Specifically, it ensures that connected nodes and in the graph have similar predicted labels and for each labeled sample and unlabeled sample . This term depends on the graph topology and the relationship between node features.
In this section, we will further describe such an idea and see how this can be very powerful, especially when regularizing the training of neural networks, which—as you might know—naturally tend to overfit and/or need large amounts of data to be trained efficiently.
Manifold regularization and semi-supervised embedding
Section titled “Manifold regularization and semi-supervised embedding”Manifold regularization (Belkin et al., 2006) extends the label propagation framework by parametrizing the model function in the reproducing kernel Hilbert space (RKHS) and using as a supervised loss function (first term in the previous equation) the MSE or the hinge loss. In other words, when training an SVM or a least squares fit manifold regularization applies, a graph regularization term based on the Laplacian matrix L, as follows:
Here, represents the weight of the edge between nodes i and j, while and are the predicted labels. The equation enforces smoothness in the learned prediction function by penalizing differences in function values between connected nodes. Essentially, the term ensures that neighboring nodes in the graph have similar representations, reinforcing the manifold assumption that similar data points lie close to each other in the feature space.
For this reason, these methods are generally labeled as Laplacian regularization, and such a formulation leads to Laplacian regularized least squares (LapRLS) and LapSVM classifications. Label propagation and label spreading can be seen as a special case of manifold regularization. Besides, these algorithms can also be used in the case of no-labeled data (first term in the equation disappearing) reducing to Laplacian eigenmaps.
On the other hand, they can also be used in the case of a fully labeled dataset, in which case the preceding terms constrain the training phase to regularize the training and achieve more robust models. Moreover, being the classifier parametrized in the RKHS, the model can be used on unobserved samples and does not require test samples to belong to the input graph. In this sense, it is therefore an inductive model.
Manifold learning still represents a form of shallow learning, whereby the parametrized function does not leverage on any form of intermediate embeddings. Semi-supervised embedding (Weston et al., 2012) extends the concepts of graph regularization to deeper architectures by imposing the constraint and the smoothness of the function on intermediate layers of a neural network. Let’s define as the intermediate output of the kth hidden layer. The regularization term proposed in the semi-supervised embedding framework reads as follows:
Here, the function enforces similarity between representations of connected nodes i and j at a specific layer . This encourages smoothness in the learned embeddings, ensuring that the network learns meaningful representations that align with the graph structure.
Depending on where the regularization is imposed, three different configurations (shown in Figure 5.9) can be achieved, as follows:
- Regularization is applied to the final output of the network. This corresponds to a generalization of the manifold learning technique to multilayer neural networks.
- Regularization is applied to an intermediate layer of the network, thus regularizing the embedding representation.
- Regularization is applied to an auxiliary network that shares the first k-1 layers. This basically corresponds to training an unsupervised embedding network while simultaneously training a supervised network. This technique basically imposes a derived regularization on the first k-1 layers that are constrained by the unsupervised network as well and simultaneously promotes an embedding of the network nodes.
The following diagram shows an illustration of the three different configurations—with their similarities and differences—that can be achieved using a semi-supervised embedding framework:

Figure 5.9: Semi-supervised embedding regularization configurations: graph regularization, indicated by the cross, can be applied to the output (left), to an intermediate layer (center), or to an auxiliary network (right)
In its original formulation, the loss function used for the embeddings is the one derived from the Siamese network formulation, as follows:
As can be seen by this equation, the loss function ensures the embeddings of neighboring nodes stay close. On the other hand, non-neighbors are instead pulled apart to a distance (at least) specified by the threshold m. As compared to the regularization based on the Laplacian (although for neighboring points, the penalization factor is effectively recovered), the one shown here is generally easier to optimize with gradient descent.
The best choice among the three configurations presented in Figure 5.9 is largely influenced by the data at your disposal as well as on your specific use case—that is, whether you need a regularized model output or to learn a high-level data representation. However, you should always keep in mind that when using softmax layers (usually done at the output layer), the regularization based on the hinge loss may not be very appropriate or suited for log probabilities. In such cases, regularized embeddings and relative loss should instead be introduced at intermediate layers. However, be aware that embeddings that reside in deeper layers are generally harder to train and require careful tuning of the learning rate and margins to be used. In the next section, we will learn about a generalization of manifold learning. While we have not yet discussed a practical example of manifold learning, we will cover it as part of this generalization.
Neural graph learning
Section titled “Neural graph learning”Neural graph learning (NGL) basically generalizes the previous formulations and, as we will see, makes it possible to seamlessly apply graph regularization to any form of a neural network, including CNNs and recurrent neural networks (RNNs). In particular, there exists an extremely powerful framework named neural structured learning (NSL) that allows us to extend in a very few lines of code a neural network implemented in TensorFlow with graph regularization. The networks can be of any kind: natural or synthetic.
When synthetic, graphs can be generated in several ways. For instance, one approach involves constructing embeddings of raw input features (e.g., using feature vectors from images, text, or tabular data) in an unsupervised manner, then using a similarity or distance metric to define edges between nodes. You can also generate synthetic graphs using adversarial examples. Adversarial examples are artificially generated samples obtained by perturbing actual (real) examples in such a way that we confound the network, trying to force a prediction error. These very carefully designed samples (obtained by perturbing a given sample in the gradient-descent direction in order to maximize errors) can be connected to their related samples, thus generating a graph. These connections can then be used to train a graph-regularized version of the network, allowing us to obtain models that are more robust against adversarially generated examples.
NGL extends the regularization by augmenting the tuning parameters for graph regularization in neural networks, decomposing the contribution of labeled-labeled, labeled-unlabeled, and unlabeled-unlabeled relations using three parameters, , , and , respectively, as follows:
The function d represents a generic distance between two vectors—for instance, the L2 norm . By varying the coefficients and the definition of , we can arrive at the different algorithms seen previously as limiting behavior, as follows:
- When , we retrieve the non-regularized version of a neural network.
- When only , we recover a fully supervised formulation where relationships between nodes act to regularize the training.
- When we substitute (which is parametrized by a set of alpha coefficients) with a set of values (to be learned) that map each sample to its instance class, we recover the label propagation formulation.
Loosely speaking, the NGL formulations can be seen as non-linear versions of the label propagation and label spreading algorithms, or as a form of a graph-regularized neural network for which the manifold learning or semi-supervising embedding can be obtained.
We will now apply NGL to a practical example, where you will learn how to use graph regularization in neural networks. To do so, we will use the NLS framework (https://github.com/tensorflow/neural-structured-learning), which is a library built on top of TensorFlow that makes it possible to implement graph regularization with only a few lines of codes on top of standard neural networks.
For our example, we will be using the Cora dataset, which is a labeled dataset that consists of 2,708 scientific papers in computer science that have been classified into seven classes. Each paper represents a node that is connected to other nodes based on citations. In total, there are 5,429 links in the network.
Moreover, each node is further described by a 1,433-long vector of binary values (0 or 1) that represent a dichotomic bag-of-words (BOW) representation of the paper: a one-hot-encoding algorithm indicating the presence/absence of a word in a given vocabulary made up of 1,433 terms.
The Cora dataset can be downloaded directly from the stellargraph library with a few lines of code, as follows:
from stellargraph import datasetsdataset = datasets.Cora()dataset.download()G, labels = dataset.load()This returns two outputs, outlined as follows:
-
G, which is the citation network containing the network nodes, edges, and the features describing the BOW representation. -
labels, which is apandasSeries that maps each paper ID (node) to one of the following classes:['Neural_Networks', 'Rule_Learning', 'Reinforcement_Learning','Probabilistic_Methods', 'Theory', 'Genetic_Algorithms', 'Case_Based']
Starting from this information, we will create a training set and a validation set. In the training samples, we will include information relating to neighbors (which may or may not belong to the training set and therefore have a label), and this will be used to regularize the training.
Validation samples, on the other hand, will not have neighbor information and the predicted label will only depend on the node features—namely, the BOW representation. Therefore, we will leverage both labeled and unlabeled samples (semi-supervised task) in order to produce an inductive model that can also be used against unobserved samples.
-
As a preparatory step, we conveniently structure the node features as a DataFrame, whereas we store the graph as an adjacency matrix, as follows:
adjMatrix = pd.DataFrame.sparse.from_spmatrix(G.to_adjacency_matrix(),index=G.nodes(), columns=G.nodes())features = pd.DataFrame(G.node_features(), index=G.nodes())
Using adjMatrix, we implement a helper function that is able to retrieve the closest topn neighbors of a node, returning the node ID and the edge weight, as illustrated in the following code snippet:
def getNeighbors(idx, adjMatrix, topn=5): weights = adjMatrix.loc[idx] neighbors = weights[weights>0]\ .sort_values(ascending=False)\ .head(topn) return [(k, v) for k, v in neighbors.items()]Using the preceding information together with the helper function, we can merge the information into a single DataFrame, as follows:
dataset = { index: { "id": index, "words": [float(x) for x in features.loc[index].values], "label": label_index[label], "neighbors": getNeighbors(index, adjMatrix, topn) } for index, label in labels.items()}df = pd.DataFrame.from_dict(dataset, orient="index")This DataFrame represents the node-centric feature space. This would suffice if we were to use a regular classifier that does not exploit the information of the relationships between nodes. However, in order to allow the computation of the graph regularization term, we need to join the preceding DataFrame with information relating to the neighborhood of each node. We then define a function able to retrieve and join the neighborhood information, as follows:
def getFeatureOrDefault(ith, row): try: Node, value = row["neighbors"][ith] return { f"{GRAPH_PREFIX}_{ith}_weight": value, f"{GRAPH_PREFIX}_{ith}_words": df.loc[Node]["words"] } except: return { f"{GRAPH_PREFIX}_{ith}_weight": 0.0, f"{GRAPH_PREFIX}_{ith}_words": [float(x) for x in np.zeros(1433)] }
def neighborsFeatures(row): featureList = [getFeatureOrDefault(ith, row) for ith in range(topn)] return pd.Series( {k: v for feat in featureList for k, v in feat.items()} )As shown in the preceding code snippet, when the neighbors are less than topn, we set the weight and the one-hot encoding of the words to 0. The GRAPH_PREFIX constant is a prefix that is to be prepended to all features that will later be used by the nsl library to regularize the training. Although it can be changed, in the following code snippet we will keep its value equal to the default value: "NL_nbr".
This function can be applied to the DataFrame in order to compute the full feature space, as follows:
neighbors = df.apply(neighborsFeatures, axis=1)allFeatures = pd.concat([df, neighbors], axis=1)We now have in allFeatures all the ingredients we need to implement our graph-regularized model.
-
We can now start the training process by splitting our dataset into a training set and a validation set, as follows:
n = int(np.round(len(labels)*ratio))labelled, unlabelled = model_selection.train_test_split(allFeatures, train_size=n, test_size=None, stratify=labels)
Here, ratio is the proportion of the dataset that will be labeled. As the ratio decreases, we expect the performance of standard, non-regularized classifiers to reduce. However, such a reduction can be compensated by leveraging network information provided by unlabeled data. We thus expect graph-regularized neural networks to provide better performance thanks to the augmented information they leverage. For the following code snippet, we will assume a ratio value equal to 0.2.
Before feeding this data into our neural network, we convert the DataFrame into a TensorFlow tensor and dataset, which is a convenient representation that will allow the model to refer to feature names in its input layers.
Since the input features have different data types, it is best to handle the dataset creation separately for the weights, words, and labels values, as follows:
train_base = { "words": tf.constant([ tuple(x) for x in labelled["words"].values ]), "label": tf.constant([ x for x in labelled["label"].values ])}train_neighbor_words = { k: tf.constant([tuple(x) for x in labelled[k].values]) for k in neighbors if "words" in k}train_neighbor_weights = { k: tf.constant([tuple([x]) for x in labelled[k].values]) for k in neighbors if "weight" in k}Now that we have the tensor, we can merge all this information into a TensorFlow dataset, as follows:
trainSet = tf.data.Dataset.from_tensor_slices({ k: v for feature in [train_base, train_neighbor_words, train_neighbor_weights] for k, v in feature.items()})We can similarly create a validation set. As mentioned previously, since we want to design an inductive algorithm, the validation dataset does not need any neighborhood information. The code is illustrated in the following snippet:
validSet = tf.data.Dataset.from_tensor_slices({ "words": tf.constant([ tuple(x) for x in unlabelled["words"].values ]), "label": tf.constant([ x for x in unlabelled["label"].values ])})Before feeding the dataset into the model, we split the features from the labels, as follows:
def split(features): labels=features.pop("label") return features, labels
trainSet = trainSet.map(split)validSet = validSet.map(split)That’s it! We have generated the inputs to our model. We could also inspect one sample batch of our dataset by printing the values of features and labels, as shown in the following code block:
for features, labels in trainSet.batch(2).take(1): print(features) print(labels)-
It is now time to create our first model. To do this, we start from a simple architecture that takes as input the one-hot representation and has two hidden layers, composed of a
Denselayer plus aDropoutlayer with 50 units each, as follows:inputs = tf.keras.Input(shape=(vocabularySize,), dtype='float32', name='words')cur_layer = inputsfor num_units in [50, 50]:cur_layer = tf.keras.layers.Dense(num_units, activation='relu')(cur_layer)cur_layer = tf.keras.layers.Dropout(0.8)(cur_layer)outputs = tf.keras.layers.Dense(len(label_index), activation='softmax',name="label")(cur_layer)model = tf.keras.Model(inputs, outputs=outputs)
Indeed, we could also train this model without graph regularization by simply compiling the model to create a computational graph, as follows:
model.compile( optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])And then, we could run it as usual, also allowing the history file to be written to disk in order to be monitored using TensorBoard, as illustrated in the following code snippet:
from tensorflow.keras.callbacks import TensorBoardmodel.fit( trainSet.batch(128), epochs=200, verbose=1, validation_data=validSet.batch(128), callbacks=[TensorBoard(log_dir='/tmp/base')])At the end of the process, we should have something similar to the following output:
Epoch 200/200loss: 0.7798 – accuracy: 06795 – val_loss: 1.5948 – val_accuracy: 0.5873- With a top performance around 0.6 in accuracy, we now need to create a graph-regularized version of the preceding model. For this step, it is important to recreate our model from scratch, especially when comparing the results: if we were to use layers already initialized and used in the previous model, the layer weights would not be random but would be used with the ones already optimized in the preceding run.
Once a new model has been created, adding a graph regularization technique to be used at training time can be done in just a few lines of code, as follows:
import neural_structured_learning as nslgraph_reg_config = nsl.configs.make_graph_reg_config( max_neighbors=2, multiplier=0.1, distance_type=nsl.configs.DistanceType.L2, sum_over_axis=-1)graph_reg= nsl.keras.GraphRegularization( model, graph_reg_config)Let’s analyze the different hyperparameters of the regularization, as follows:
max_neighborstunes the number of neighbors that ought to be used for computing the regularization loss for each node.multipliercorresponds to the coefficients that tune the importance of the regularization loss. Since we only consider labeled-labeled and labeled-unlabeled, this effectively corresponds to and .distance_typerepresents the pairwise distance d to be used.sum_over_axissets whether the weighted average sum should be calculated with respect to features (when set toNone) or to samples (when set to-1).
The graph-regularized model can be compiled and run in the same way as before with the following commands:
graph_reg.compile( optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])model.fit( trainSet.batch(128), epochs=200, verbose=1, validation_data=validSet.batch(128), callbacks=[TensorBoard(log_dir='/tmp/nsl')])Note that the loss function now also accounts for the graph regularization term, as defined previously. Therefore, we now also introduce information coming from neighboring nodes that regularizes the training of our neural network. The preceding code, after about 200 iterations, provides the following output:
Epoch 200/200loss: 0.9136 – accuracy: 06405 – scaled_graph_loss: 0.0328 - val_loss: 1.2526 – val_accuracy: 0.6320As you can see, graph regularization, when compared to the vanilla version, has allowed us to boost the performance in terms of validation accuracy by about 7%. Not bad at all! This is because the model is now able to exploit relational information between data points. While the non-regularized version relies just on individual feature representations, the graph-regularized version now incorporates neighborhood information, which can reduce overfitting and improve generalization, particularly in cases where the data contains inherent structure or relationships.
You can perform several experiments, changing the ratio of labeled/unlabeled samples, the number of neighbors to be used, the regularization coefficient, the distance, and more. We encourage you to play around with the notebook that is provided with this book to explore the effect of different parameters yourself.
In the right panel of the following screenshot, we show the dependence of the performance measured by the accuracy as the supervised ratio increases. As expected, performance increases as the ratio increases. On the left panel, we show the accuracy increments on the validation set for various configurations of neighbors and supervised ratio, defined by:
As can be seen in Figure 5.10, almost all graph-regularized versions outperform the vanilla models:

Figure 5.10: Accuracy on the validation set for the graph-regularized neural networks with neighbors = 2 and various supervised ratios (left); accuracy increments on the validation set for the graph-regularized neural networks compared to the vanilla version (right)
The only exceptions are configuration neighbors = 2 and ratio = 0.5, for which the two models perform very similarly. However, the curve has a clear positive trend and we reasonably expect the graph-regularized version to outperform the vanilla model for a larger number of epochs.
In the notebook, we also use another interesting feature of TensorFlow for creating the datasets. Instead of using a pandas DataFrame, as we did previously, we will create a dataset using the TensorFlow Example, Features, and Feature classes, which, besides providing a high-level description of samples, also allow us to serialize the input data (using protobuf) to make them compatible across platforms and programming languages.
If you are interested in further using TensorFlow both for prototyping models and deploying them into production via data-driven applications (maybe written in other languages), we strongly advise you to dig further into these concepts.
Planetoid
Section titled “Planetoid”The methods discussed so far provide graph regularization that is based on the Laplacian matrix. As we have seen in previous chapters, enforcing constraints based on ensures that first-order proximity is preserved. Yang et al. (2016) proposed a method to extend graph regularization in order to also account for higher-order proximities. Their approach, which they named Planetoid (short for Predicting Labels And Neighbors with Embeddings Transductively Or Inductively from Data), extends skip-gram methods used for computing node embeddings to incorporate node-label information.
As we have seen in the previous chapter, skip-gram methods are based on generating random walks through a graph and then using the generated sequences to learn embeddings via a skip-gram model. The following diagram shows how the unsupervised version is modified to account for the supervised loss:

Figure 5.11: Sketch of the Planetoid architecture: the dotted line represents a parametrized function that allows the method to extend from transductive to inductive
As shown in Figure 5.11, embeddings are fed to both of the following:
- A softmax layer to predict the graph context of the sampled random-walk sequences
- A set of hidden layers that combine with the hidden layers derived from the node features in order to predict the class labels
The cost function to be minimized to train the combined network is composed of a supervised and an unsupervised loss — and , respectively. The unsupervised loss is analogous to the one used with skip-gram with negative sampling, whereas the supervised loss minimizes the conditional probability of predicting the label and can be written as follows:
Where S is the set of labeled points and and are the input feature and the learned embeddings for the ith data point, respectively. The goal, then, is to minimize the loss by encouraging the model to make predictions that are closely aligned with the ground truth. The preceding formulation is transductive as it requires samples to belong to the graph in order to be applied. In a semi-supervised task, this method can be efficiently used to predict labels for unlabeled examples. However, it cannot be used for unobserved samples. As shown by the dotted line in Figure 5.11, an inductive version of the Planetoid algorithm can be obtained by parametrizing the embeddings as a function of the node features, via dedicated connected layers.
As you can see, Planetoid represents a simple extension of the example in the previous section. Therefore, we will not implement it here in the book. Nevertheless, you can find a possible implementation in our GitHub repository.
All the techniques described so far remain valuable for their simplicity, interpretability, and efficiency. Nevertheless, nowadays, with the rise of neural network-based techniques, it is common to solve such problems using modern techniques such as GNNs. It is important to remark, however, that simpler methods can often achieve comparable results in specific scenarios, offering computational advantages and complementing modern techniques. Highlighting these foundational methods underscores their relevance and prevents them from being overshadowed by the drive for innovation.
Graph CNNs
Section titled “Graph CNNs”In Chapter 4, Unsupervised Graph Learning, we learned the main concepts behind GNNs and graph convolutional networks (GCNs). We also learned the difference between spectral graph convolution and spatial graph convolution. More precisely, we saw that GCN layers can be used to encode graphs or nodes under unsupervised settings by learning how to preserve graph properties such as node similarity.
In this chapter, we will explore such methods under supervised settings. This time, our goal is to learn graphs or node representations that can accurately predict node or graph labels. It is indeed worth noting that the encoding function remains the same. What will change is the objective!
Graph classification using GCNs
Section titled “Graph classification using GCNs”Let’s consider again our PROTEINS dataset. Let’s load the dataset as follows:
import pandas as pdfrom stellargraph import datasetsdataset = datasets.PROTEINS()graphs, graph_labels = dataset.load()# necessary for converting default string labels to intlabels = pd.get_dummies(graph_labels, drop_first=True)In the following example, we are going to use (and compare) one of the most widely used GCN algorithms for graph classification—GCN by Kipf and Welling:
-
stellargraph, which we are using to build the model, usestf.Kerasas the backend. According to its specific criteria, we need a data generator to feed the model. More precisely, since we are addressing a supervised graph classification problem, we can use an instance of thePaddedGraphGeneratorclass ofstellargraph, which automatically resolves differences in the number of nodes by using padding. Here is the code required for this step:from stellargraph.mapper import PaddedGraphGeneratorgenerator = PaddedGraphGenerator(graphs=graphs) -
We are now ready to actually create our first model. We will create and stack together four GCN layers through the
utilityfunction ofstellargraph, as follows:from stellargraph.layer import DeepGraphCNNfrom tensorflow.keras import Modelfrom tensorflow.keras.optimizers import Adamfrom tensorflow.keras.layers import Dense, Conv1D, MaxPool1D, Dropout, Flattenfrom tensorflow.keras.losses import binary_crossentropyimport tensorflow as tfnrows = 35 # the number of rows for the output tensorlayer_dims = [32, 32, 32, 1]# backbone part of the model (Encoder)dgcnn_model = DeepGraphCNN(layer_sizes=layer_dims,activations=["tanh", "tanh", "tanh", "tanh"],k=nrows,bias=False,generator=generator,) -
This
backbonewill be concatenated to one-dimensional (1D) convolutional layers and fully connected layers usingtf.Keras, as follows:# necessary for connecting the backbone to the headgnn_inp, gnn_out = dgcnn_model.in_out_tensors()# head part of the model (classification)x_out = Conv1D(filters=16, kernel_size=sum(layer_dims), strides=sum(layer_dims))(gnn_out)x_out = MaxPool1D(pool_size=2)(x_out)x_out = Conv1D(filters=32, kernel_size=5, strides=1)(x_out)x_out = Flatten()(x_out)x_out = Dense(units=128, activation="relu")(x_out)x_out = Dropout(rate=0.5)(x_out)predictions = Dense(units=1, activation="sigmoid")(x_out) -
Let’s create and compile a model using
tf.Kerasutilities. We will train the model with abinary_crossentropyloss function (to measure the difference between predicted labels and ground truth) with theAdamoptimizer and a learning rate of0.0001. We will also monitor the accuracy metric while training. The code is illustrated in the following snippet:model = Model(inputs=gnn_inp, outputs=predictions)model.compile(optimizer=Adam(lr=0.0001), loss=binary_crossentropy, metrics=["acc"]) -
We can now exploit scikit-learn utilities to create train and test sets. In our experiments, we will be using 70% of the dataset as a training set and the remainder as a test set. In addition, we need to use the
flowmethod of the generator to supply them to the model. The code to achieve this is shown in the following snippet:from sklearn.model_selection import train_test_splittrain_graphs, test_graphs = train_test_split(graph_labels, test_size=.3, stratify=labels)gen = PaddedGraphGenerator(graphs=graphs)train_gen = gen.flow(list(train_graphs.index - 1),targets=train_graphs.values,symmetric_normalization=False,batch_size=50,)test_gen = gen.flow(list(test_graphs.index - 1),targets=test_graphs.values,symmetric_normalization=False,batch_size=1,) -
It’s now time for training. We train the model for 100 epochs. However, feel free to play with the hyperparameters to gain better performance. Here is the code for this:
epochs = 100history = model.fit(train_gen, epochs=epochs, verbose=1,validation_data=test_gen, shuffle=True)
After 100 epochs, this should be the output:
Epoch 100/100loss: 0.5121 – acc: 0.7636 – val_loss: 0.5636 – val_acc: 0.7305Here, we are achieving about 76% accuracy on the training set and about 73% accuracy on the test set. These results indicate that the model has learned meaningful patterns from the graph structure and node features, which it is exploiting effectively to generalize reasonably well.
Node classification using GraphSAGE
Section titled “Node classification using GraphSAGE”In the next example, we will train GraphSAGE to classify nodes of the Cora dataset.
Let’s first load the dataset using stellargraph utilities, as follows:
dataset = datasets.Cora()G, nodes = dataset.load()Follow this list of steps to train GraphSAGE to classify nodes of the Cora dataset:
-
As in the previous example, the first step is to split the dataset. We will be using 90% of the dataset as a training set and the remainder for testing. Here is the code for this step:
train_nodes, test_nodes = train_test_split(nodes, train_size=0.1,test_size=None, stratify=nodes) -
This time, we will convert labels using one-hot representation. This representation is often used for classification tasks and usually leads to better performance. Specifically, let
cbe the number of possible targets (seven, in the case of theCoradataset), and each label will be converted to a vector of sizec, where all the elements are0except for the one corresponding to the target class. The code is illustrated in the following snippet:from sklearn import preprocessinglabel_encoding = preprocessing.LabelBinarizer()train_labels = label_encoding.fit_transform(train_nodes)test_labels = label_encoding.transform(test_nodes) -
Let’s create a generator to feed the data into the model. We will be using an instance of the
GraphSAGENodeGeneratorclass ofstellargraph. We will use theflowmethod to feed the model with the train and test sets, as follows:from stellargraph.mapper import GraphSAGENodeGeneratorbatchsize = 50n_samples = [10, 5, 7]generator = GraphSAGENodeGenerator(G, batchsize, n_samples)train_gen = generator.flow(train_nodes.index, train_labels, shuffle=True)test_gen = generator.flow(test_labels.index, test_labels) -
Finally, let’s create the model and compile it. For this exercise, we will be using a
GraphSAGEencoder with three layers of32,32, and16dimensions, respectively. The encoder will then be connected to a dense layer withsoftmaxactivation to perform the classification. We will use anAdamoptimizer with a learning rate of0.03andcategorical_crossentropyas the loss function. The code is illustrated in the following snippet:from stellargraph.layer import GraphSAGEfrom tensorflow.keras.losses import categorical_crossentropygraphsage_model = GraphSAGE(layer_sizes=[32, 32, 16], generator=generator, bias=True, dropout=0.6,)gnn_inp, gnn_out = graphsage_model.in_out_tensors()outputs = Dense(units=train_labels.shape[1], activation="softmax")(gnn_out)# create the model and compilemodel = Model(inputs=gnn_inp, outputs=outputs)model.compile(optimizer=Adam(lr=0.003), loss=categorical_crossentropy, metrics=["acc"],) -
It’s now time to train the model. We will train the model for 20 epochs, as follows:
model.fit(train_gen, epochs=20, validation_data=test_gen, verbose=2, shuffle=False) -
This should be the output:
Epoch 20/20loss: 0.8252 – acc: 0.8889 – val_loss: 0.9070 – val_acc: 0.8011
We achieved about 89% accuracy over the training set and about 80% accuracy over the test set, indicating that GraphSAGE has strong capability to learn meaningful information from the graph while avoiding excessive overfitting.
Summary
Section titled “Summary”In this chapter, we have learned how supervised ML can be effectively applied on graphs to solve real problems such as node and graph classification. In particular, we first analyzed how graph and node properties can be directly used as features to train classic ML algorithms. We have seen shallow methods and simple approaches to learning node, edge, or graph representations for only a finite set of input data. We then learned how regularization techniques can be used during the learning phase in order to create more robust models that tend to generalize better. Finally, we have seen how GNNs can be applied to solve supervised ML problems on graphs.
But what can these algorithms be useful for? In the next chapter, we will explore common problems that can be solved using graph-based ML techniques.