Skip to content
ImagineWorld

Supervised Graph Learning

node_idnode-book_graph-machine-learning_chapter-05-supervised-graph-learning
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num5
chapter_titleSupervised Graph Learning
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

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)

In supervised learning, a training set consists of a sequence of ordered pairs (xx, yy), where xx is a set of input features (often signals defined on graphs) and yy is the output label assigned to it. The goal of ML models, then, is to learn the function mapping each xx value to each yy value. Here, yy 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

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.

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:

  1. Select a set of good descriptive graph properties.
  2. 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:

  1. First, let’s load the dataset through the stellargraph Python library, as follows:

    from stellargraph import datasets
    from IPython.display import display, HTML
    dataset = datasets.PROTEINS()
    graphs, graph_labels = dataset.load()
  2. 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 the stellargraph format to the networkx format. This can be done in two steps: first, convert the graphs from the stellargraph representation to numpy adjacency matrices. Then, use the adjacency matrices to retrieve the networkx representation. In addition (as we will see in the next steps), we also transform the labels (which are stored as a pandas Series) to a numpy array, which can be better exploited by the evaluation functions. The code is illustrated in the following snippet:

    # convert from StellarGraph format to numpy adj matrices
    adjs = [graph.to_adjacency_matrix().A for graph in graphs]
    # convert labels from Pandas.Series to numpy array
    labels = graph_labels.to_numpy(dtype=int)
  3. 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 np
    import networkx as nx
    metrics = []
    for adj in adjs:
    # from numpy to networkx
    G = nx.from_numpy_matrix(adj)
    # basic properties
    num_edges = G.number_of_edges()
    # clustering measures
    cc = nx.average_clustering(G)
    # measure of efficiency
    eff = nx.global_efficiency(G)
    metrics.append([num_edges, cc, eff])
  4. 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_split function provided by scikit-learn, as follows:

    from sklearn.model_selection import train_test_split
    X_train, X_test, y_train, y_test = train_test_split(metrics, labels, test_size=0.3, random_state=42)
  5. 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 SVC module of scikit-learn. In addition, we use the accuracy, precision, recall, and F1-score to evaluate how well the algorithm is performing on the test set:

    from sklearn import svm
    from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
    clf = 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.7455
Precision 0.7709
Recall 0.8413
F1-score 0.8045

We 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.

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.

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

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 G=(V,E)G=(V,E) be a graph and let YY be a set of labels. Since the algorithm is semi-supervised, just a subset of nodes will have an assigned label. Moreover, let AA be the adjacency matrix of the input graph GG and DD be the diagonal degree matrix where each element dijd_{ij} is defined as follows:

dij={diif i=j0otherwised_{ij} = \begin{cases} d_i & \text{if } i = j \\ 0 & \text{otherwise} \end{cases}

Where did_i is the degree of the node ii. 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

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 TT. This matrix defines the probability of a node being reached from another node. More precisely, TijT_{ij} is the probability of reaching node jj from node ii. 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

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 Y(0)Y^{(0)} the initial label assignment, the probability of label assignment for each node obtained using the TT matrix can be computed as Y(1)=TY(0)Y^{(1)} = T Y^{(0)}. The Y(1)Y^{(1)} 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

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 Y(0)Y^{(0)}.

In order to solve the first point, the algorithm will perform tt different iterations; at each iteration tt, the algorithm will compute the solution for that iteration, as follows:

Y(t)=TY(t−1)Y^{(t)} = T Y^{(t-1)}

Where T is the transition matrix and Y(t−1)Y^{(t-1)} 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 Y(t)Y^{(t)}, 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 self

The fit(X,y) function takes as input a networkx graph XX and an array yy 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 Y(t)Y^{(t)} 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, Y(t)Y^{(t)} and Y(t−1)Y^{(t-1)}, 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] = 0
y[6] = 1
glp.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

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.

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 G=(V,E)G=(V,E) be a graph and let YY be a set of labels (since the algorithm is semi-supervised, just a subset of nodes will have an assigned label), and let AA and DD 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:

L=D−1/2AD−1/2L = D^{-1/2} A D^{-1/2}

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_power
D_inv = fractional_matrix_power(D, -0.5)
L = D_inv*nx.to_numpy_matrix(G)*D_inv

As a result, we get the following:

Figure 5.7: The normalized graph Laplacian matrix

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 Y(0)Y^{(0)} the initial label assignment, the probability of a label assignment for each node obtained using the LL matrix can be computed as follows:

Y(1)=αLY(0)+(1−α)Y(0)Y^{(1)} = \alpha L Y^{(0)} + (1 - \alpha) Y^{(0)}

Where α\alpha 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:

Y(t)=αLY(t−1)+(1−α)Y(0)Y^{(t)} = \alpha L Y^{(t-1)} + (1 - \alpha) Y^{(0)}

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 (1−α)Y(0)(1 - \alpha) Y^{(0)} 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 α\alpha 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 self

Also 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 Y(t)Y^{(t)} value at each iteration, weighting the influence of the initial labeling via the parameter α\alpha. 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] = 0
y[6] = 1
gls.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

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.

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 L\mathcal{L} to be minimized in the following form:

L=∑i∈Ll(yi,f(xi))+λ∑i,jAijd(f(xi),f(xj))\mathcal{L} = \sum_{i \in L} l(y_i, f(x_i)) + \lambda \sum_{i,j} A_{ij} d(f(x_i), f(x_j))

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.

l(yi,f(xi))l(y_i, f(x_i)) is the supervised loss term. It measures how well the predicted label f(xi)f(x_i) matches the true label yiy_i for each labeled sample xix_i. 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).

∑i,jAijd(f(xi),f(xj))\sum_{i,j} A_{ij} d(f(x_i), f(x_j)) is the graph-based regularization term. It uses the graph structure G to enforce consistency in predictions. Specifically, it ensures that connected nodes xix_i and xjx_j in the graph have similar predicted labels f(xi)f(x_i) and f(xj)f(x_j) for each labeled sample xix_i and unlabeled sample xjx_j. 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:

Reg=∑i,jWij(f(xi)−f(xj))2=fTLf\text{Reg} = \sum_{i,j} W_{ij} (f(x_i) - f(x_j))^2 = f^T L f

Here, WijW_{ij} represents the weight of the edge between nodes i and j, while f(xi)f(x_i) and f(xj)f(x_j) 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 hk(x)h_k(x) as the intermediate output of the kth hidden layer. The regularization term proposed in the semi-supervised embedding framework reads as follows:

Reg=∑i,jWijd(hk(xi),hk(xj))\text{Reg} = \sum_{i,j} W_{ij} d(h_k(x_i), h_k(x_j))

Here, the function enforces similarity between representations of connected nodes i and j at a specific layer hkh_k. 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)

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:

d(h(xi),h(xj))={∣∣h(xi)−h(xj)∣∣2if Aij=1max⁡(0,m−∣∣h(xi)−h(xj)∣∣2)if Aij=0d(h(x_i), h(x_j)) = \begin{cases} ||h(x_i) - h(x_j)||^2 & \text{if } A_{ij} = 1 \\ \max(0, m - ||h(x_i) - h(x_j)||^2) & \text{if } A_{ij} = 0 \end{cases}

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 LL (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 (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, λ1\lambda_1, λ2\lambda_2, and λ3\lambda_3, respectively, as follows:

Reg=λ1∑i,j∈LAijd(f(xi),f(xj))+λ2∑i∈L,j∈UAijd(f(xi),f(xj))+λ3∑i,j∈UAijd(f(xi),f(xj))\text{Reg} = \lambda_1 \sum_{i,j \in L} A_{ij} d(f(x_i), f(x_j)) + \lambda_2 \sum_{i \in L, j \in U} A_{ij} d(f(x_i), f(x_j)) + \lambda_3 \sum_{i,j \in U} A_{ij} d(f(x_i), f(x_j))

The function d represents a generic distance between two vectors—for instance, the L2 norm ∣∣f(xi)−f(xj)∣∣2|| f(x_i) - f(x_j) ||^2. By varying the coefficients and the definition of λi\lambda_i, we can arrive at the different algorithms seen previously as limiting behavior, as follows:

  • When λ1=λ2=λ3=0\lambda_1 = \lambda_2 = \lambda_3 = 0, we retrieve the non-regularized version of a neural network.
  • When only λ1>0\lambda_1 > 0, we recover a fully supervised formulation where relationships between nodes act to regularize the training.
  • When we substitute f(x)f(x) (which is parametrized by a set of alpha coefficients) with a set of values YY (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 datasets
dataset = 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 a pandas Series 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.

  1. 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.

  1. 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)
  1. 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 Dense layer plus a Dropout layer with 50 units each, as follows:

    inputs = tf.keras.Input(
    shape=(vocabularySize,), dtype='float32', name='words'
    )
    cur_layer = inputs
    for 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 TensorBoard
model.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/200
loss: 0.7798 – accuracy: 06795 – val_loss: 1.5948 – val_accuracy: 0.5873
  1. 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 nsl
graph_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_neighbors tunes the number of neighbors that ought to be used for computing the regularization loss for each node.
  • multiplier corresponds to the coefficients that tune the importance of the regularization loss. Since we only consider labeled-labeled and labeled-unlabeled, this effectively corresponds to λ1\lambda_1 and λ2\lambda_2.
  • distance_type represents the pairwise distance d to be used.
  • sum_over_axis sets whether the weighted average sum should be calculated with respect to features (when set to None) 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/200
loss: 0.9136 – accuracy: 06405 – scaled_graph_loss: 0.0328 - val_loss: 1.2526 – val_accuracy: 0.6320

As 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:

ΔAccuracy=Accuracyregularized−Accuracyvanilla\Delta \text{Accuracy} = \text{Accuracy}_{\text{regularized}} - \text{Accuracy}_{\text{vanilla}}

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)

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.

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 LL 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

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 — LsL_s and LuL_u, 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 yiy_i and can be written as follows:

Ls=−∑i∈Slog⁡P(yi∣xi,zi)L_s = -\sum_{i \in S} \log P(y_i | x_i, z_i)

Where S is the set of labeled points and xix_i and ziz_i 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.

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!

Let’s consider again our PROTEINS dataset. Let’s load the dataset as follows:

import pandas as pd
from stellargraph import datasets
dataset = datasets.PROTEINS()
graphs, graph_labels = dataset.load()
# necessary for converting default string labels to int
labels = 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:

  1. stellargraph, which we are using to build the model, uses tf.Keras as 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 the PaddedGraphGenerator class of stellargraph, which automatically resolves differences in the number of nodes by using padding. Here is the code required for this step:

    from stellargraph.mapper import PaddedGraphGenerator
    generator = PaddedGraphGenerator(graphs=graphs)
  2. We are now ready to actually create our first model. We will create and stack together four GCN layers through the utility function of stellargraph, as follows:

    from stellargraph.layer import DeepGraphCNN
    from tensorflow.keras import Model
    from tensorflow.keras.optimizers import Adam
    from tensorflow.keras.layers import Dense, Conv1D, MaxPool1D, Dropout, Flatten
    from tensorflow.keras.losses import binary_crossentropy
    import tensorflow as tf
    nrows = 35 # the number of rows for the output tensor
    layer_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,
    )
  3. This backbone will be concatenated to one-dimensional (1D) convolutional layers and fully connected layers using tf.Keras, as follows:

    # necessary for connecting the backbone to the head
    gnn_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)
  4. Let’s create and compile a model using tf.Keras utilities. We will train the model with a binary_crossentropy loss function (to measure the difference between predicted labels and ground truth) with the Adam optimizer and a learning rate of 0.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"])
  5. 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 flow method 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_split
    train_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,
    )
  6. 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 = 100
    history = model.fit(
    train_gen, epochs=epochs, verbose=1,
    validation_data=test_gen, shuffle=True
    )

After 100 epochs, this should be the output:

Epoch 100/100
loss: 0.5121 – acc: 0.7636 – val_loss: 0.5636 – val_acc: 0.7305

Here, 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.

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:

  1. 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)
  2. 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 c be the number of possible targets (seven, in the case of the Cora dataset), and each label will be converted to a vector of size c, where all the elements are 0 except for the one corresponding to the target class. The code is illustrated in the following snippet:

    from sklearn import preprocessing
    label_encoding = preprocessing.LabelBinarizer()
    train_labels = label_encoding.fit_transform(train_nodes)
    test_labels = label_encoding.transform(test_nodes)
  3. Let’s create a generator to feed the data into the model. We will be using an instance of the GraphSAGENodeGenerator class of stellargraph. We will use the flow method to feed the model with the train and test sets, as follows:

    from stellargraph.mapper import GraphSAGENodeGenerator
    batchsize = 50
    n_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)
  4. Finally, let’s create the model and compile it. For this exercise, we will be using a GraphSAGE encoder with three layers of 32, 32, and 16 dimensions, respectively. The encoder will then be connected to a dense layer with softmax activation to perform the classification. We will use an Adam optimizer with a learning rate of 0.03 and categorical_crossentropy as the loss function. The code is illustrated in the following snippet:

    from stellargraph.layer import GraphSAGE
    from tensorflow.keras.losses import categorical_crossentropy
    graphsage_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 compile
    model = Model(inputs=gnn_inp, outputs=outputs)
    model.compile(optimizer=Adam(lr=0.003), loss=categorical_crossentropy, metrics=["acc"],)
  5. 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)
  6. This should be the output:

    Epoch 20/20
    loss: 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.

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.