Solving Common Graph-Based ML Problems
local graph
Chapter 06: Solving Common Graph-Based ML Problems
Section titled “Chapter 06: Solving Common Graph-Based ML Problems”Common graph ML tasks — link prediction (similarity-based, community-based, embedding-based), community detection (spectral, probabilistic, cost-function), graph similarity and matching (embedding-based, kernel-based, GNN-based).
Graph machine learning (ML) approaches can be useful for a wide range of tasks, with applications ranging from drug design to recommender systems in social networks. Furthermore, given the fact that such methods are general by design (meaning that they are not tailored to a specific problem), the same algorithm can be used to solve different problems.
There are common problems that can be effectively solved using graph-based learning techniques, as they excel at capturing relationships and structures in data. In this chapter, we will mention some of the most well studied of these by providing details about how a specific algorithm, among the ones we have already learned about in Chapter 4, Unsupervised Graph Learning, and Chapter 5, Supervised Graph Learning, can be used to solve a task. After reading this chapter, you will be aware of the formal definition of many common problems you may encounter when dealing with graphs. In addition, you will learn about useful ML pipelines that you can reuse on future real-world problems you will deal with.
More precisely, the following topics will be covered in this chapter:
- Predicting missing links in a graph
- Detecting meaningful structures such as communities
- Detecting graph similarities and graph matching
Predicting missing links in a graph
Section titled “Predicting missing links in a graph”Link prediction, also known as graph completion, is a common problem when dealing with graphs. More precisely, from a partially observed graph—that is a graph for which only a portion of the existing edges are known—we want to predict whether or not an edge exists between any given node pairs, as seen in Figure 6.1. Formally, let be a graph where is its set of nodes and is its set of edges. The set of edges are known as observed links, while the set of edges are known as unknown links. The goal of the link prediction problem is to exploit the information of and to estimate . The partially observed graph can be seen here:

Figure 6.1: Partially observed graph with observed link (solid lines) and unknown link (dashed lines)
The link prediction problem is widely used in different domains, such as a recommender system, in order to propose friendships in social networks or items to purchase on e-commerce websites. It is also used in criminal network investigations in order to find hidden connections between criminal clusters, as well as in bioinformatics for the analysis of protein-protein interactions. In the next sections, we will discuss two families of approaches to solve the link prediction problem—namely, similarity-based and embedding-based methods.
Similarity-based methods
Section titled “Similarity-based methods”In this subsection, we show several simple algorithms to solve the link prediction problem. The main shared idea behind all these algorithms is to estimate a similarity function between each couple of nodes in a graph. If, according to the function, the nodes look similar, they will have a higher probability of being connected by an edge. We will divide these algorithms into two sub-families: index-based and community-based methods. The former contains all the methods through a simple calculation of an index based on the neighbors of a given couple of nodes. The latter contains more sophisticated algorithms, whereby the index is computed using information about the community to which a given pair of nodes belong. In order to give a practical example of these algorithms, we will use the standard implementation available in the networkx library in the networkx.algorithms.link_prediction package.
Index-based methods
Section titled “Index-based methods”In this section, we will show some algorithms available in networkx to compute the probability of an edge between two disconnected nodes. These algorithms are based on the calculation of a simple index through information obtained by analyzing the neighbors of the two disconnected nodes. Note that they are not implemented for DiGraph or MultiGraph and do not take relationship weights into account, as implementing such approaches would require additional theoretical considerations on directionality, edge multiplicity, and weight impact on indices.
Resource allocation index
Section titled “Resource allocation index”The resource allocation index method estimates the probability that two nodes and are connected by estimating the resource allocation index for all node pairs according to the following formula:
Here, and computes the neighbors of nodes and , respectively, and is a node that is a neighbor of both and . Thus, for each node in the common neighborhood , the inverse of its degree captures the idea that nodes with fewer neighbors contribute more to the probability of an edge between and .
This index can be computed in networkx using the following code:
import networkx as nxedges = [[1,3],[2,3],[2,4],[4,5],[5,6],[5,7]]G = nx.from_edgelist(edges)preds = nx.resource_allocation_index(G,[(1,2),(2,5),(3,4)])The first parameter for the resource_allocation_index function is an input graph (depicted in Figure 6.1), while the second parameter is a list of possible edges. We want to compute the probability of a connection. As a result, we get the following output:
[(1, 2, 0.5), (2, 5, 0.5), (3, 4, 0.5)]The output is a list containing couples of nodes such as (1,2), (2,5), and (3,4), which form the resource allocation index. According to this output, the probability of having an edge between those couples of nodes is 0.5.
Jaccard coefficient
Section titled “Jaccard coefficient”The algorithm computes the probability of a connection between two nodes and , according to the Jaccard coefficient, which measures the similarity between their neighborhoods as the ratio of the size of their intersection to the size of their union, computed as follows:
The function can be used in networkx using the following code:
import networkx as nxedges = [[1,3],[2,3],[2,4],[4,5],[5,6],[5,7]]G = nx.from_edgelist(edges)preds = nx.resource_allocation_index(G,[(1,2),(2,5),(3,4)])The resource_allocation_index function has the same parameters as the previous function. The result of the code is shown here:
[(1, 2, 0.5), (2, 5, 0.25), (3, 4, 0.3333333333333333)]According to this output, the probability of having an edge between nodes (1,2) is 0.5, while between nodes (2,5) this is 0.25, and between nodes (3,4) this is 0.333.
In networkx, other methods to compute the probability of a connection between two nodes based on their similarity score are nx.adamic_adar_index and nx.preferential_attachment, based on Adamic/Adar index and preferential attachment index calculations respectively. Those functions have the same parameters as the others, and accept a graph and a list of a pair of nodes where we want to compute the score. In the next section, we will show another family of algorithms based on community detection.
Summarizing, index-based methods are well suited for social networks, recommendation systems with dense graphs, and applications where computational efficiency is a priority. Indeed, their simplicity and efficiency is one of their main strengths. They also work well in networks where local neighborhood information is sufficient to infer missing links. However, they may struggle in case of sparse networks where nodes have few connections. Furthermore, they do not consider higher-order structural properties of the graph.
Community-based methods
Section titled “Community-based methods”As with index-based methods, the algorithms belonging to this family also compute an index representing the probability of the disconnected nodes being connected. The main difference between index-based and community-based methods is related to the logic behind them. Indeed, community-based methods, before generating the index, need to compute information about the community to which a given pair of nodes belong. In this subsection, we will show—also providing several examples—some common community-based methods.
Community common neighbor
Section titled “Community common neighbor”In order to estimate the probability of two nodes being connected, this algorithm computes the number of common neighbors and adds to this value the number of common neighbors belonging to the same community. Formally, for two nodes and , the community common neighbor value is computed as follows:
In this formula, if belongs to the same community of and ; otherwise, this is 0. The function can be computed in networkx using the following code:
import networkx as nxedges = [[1,3],[2,3],[2,4],[4,5],[5,6],[5,7]]G = nx.from_edgelist(edges)G.nodes[1]["community"] = 0G.nodes[2]["community"] = 0G.nodes[3]["community"] = 0G.nodes[4]["community"] = 1G.nodes[5]["community"] = 1G.nodes[6]["community"] = 1G.nodes[7]["community"] = 1preds = nx.cn_soundarajan_hopcroft(G,[(1,2),(2,5),(3,4)])From the preceding code snippet, it is possible to see how we need to assign the community property to each node of the graph. This property is used to identify nodes belonging to the same community when computing the function defined in the previous equation. The community value, as we will see in the next section, can also be automatically computed using specific algorithms. As the example code above shows, the cn_soundarajan_hopcroft function takes the input graph and a couple of nodes for which we want to compute the score. As a result, we get the following output:
[(1, 2, 2), (2, 5, 1), (3, 4, 1)]The output indicates the pairs of nodes and their corresponding scores, where the score reflects the number of shared neighbors between the nodes, adjusted by their community membership. The main difference from the previous function is in the index value. Indeed, we can easily see that the output is not in the range (0,1).
Community resource allocation
Section titled “Community resource allocation”As with the previous method, the community resource allocation algorithm merges information obtained from the neighbors of the nodes with the community, as shown in the following formula:
Here, if belongs to the same community of and ; otherwise, this is 0. The function can be computed in networkx using the following code:
import networkx as nxedges = [[1,3],[2,3],[2,4],[4,5],[5,6],[5,7]]G = nx.from_edgelist(edges)G.nodes[1]["community"] = 0G.nodes[2]["community"] = 0G.nodes[3]["community"] = 0G.nodes[4]["community"] = 1G.nodes[5]["community"] = 1G.nodes[6]["community"] = 1G.nodes[7]["community"] = 1preds = nx.ra_index_soundarajan_hopcroft(G,[(1,2),(2,5),(3,4)])From the preceding code snippet, it is possible to see how we need to assign the community property to each node of the graph. This property is used to identify nodes belonging to the same community when computing the function defined in the previous equation. The community value, as we will see in the next section, can also be automatically computed using specific algorithms. As we saw, the ra_index_soundarajan_hopcroft function takes the input graph and a couple of nodes for which we want to compute the score. As a result, we get the following output:
[(1, 2, 0.5), (2, 5, 0), (3, 4, 0)]From the preceding output, it is possible to see the influence of the community in the computation of the index. Since nodes 1 and 2 belong to the same community, they have a higher value in the index. On the contrary, edges (2,5) and (3,4) feature the value 0, since they belong to a different community from each other.
In networkx, two other methods to compute the probability of a connection between two nodes based on their similarity score merged with community information are nx.within_inter_cluster and nx.common_neighbor_centrality.
Community-based methods, therefore, are best suited for applications where structural information is crucial, such as criminal network analysis and protein-protein interaction networks, since they leverage community structure to improve accuracy. Furthermore, they are effective in detecting hidden connections in sparse networks. However, they are more computationally expensive than index-based methods and may require community detection as a preprocessing step.
In the next section, we will describe a more complex method based on machine learning techniques and edge embedding to perform prediction of unknown edges.
Embedding-based methods
Section titled “Embedding-based methods”In this section, we describe a more advanced way to perform link prediction. The idea behind this approach is to solve the link prediction problem as a supervised classification task. More precisely, for a given graph, each couple of nodes is represented with a feature vector (), and a class label () is assigned to each of those node couples. Formally, let be a graph, and for each couple of nodes , we build the following formula:
Here, is the feature vector representing the couple of nodes , and is their label. The value for is defined as follows: if, in the graph G, the edge connecting node exists; otherwise, . Using the feature vector and the labels, we can then train an ML algorithm in order to predict whether a given couple of nodes constitutes a plausible edge for the given graph.
If it is easy to build the label vector for each couple of nodes, it is not so straightforward to build the feature space. In order to generate the feature vector for each couple of nodes, we will use some embedding techniques, such as node2vec and edge2vec, already discussed in Chapter 4, Unsupervised Graph Learning. Using those embedding algorithms, the generation of the feature space will be greatly simplified. Indeed, the whole process can be summarized in two main steps, outlined as follows:
- For each node of the graph
G, its embedding vector is computed using anode2vecalgorithm. - For all the possible pairs of nodes in the graph, the embedding is computed using an
edge2vecalgorithm.
We can now apply a generic ML algorithm to the generated feature vector in order to solve the classification problem.
In order to give you a practical explanation of this procedure, we will provide an example in the following code snippet. More precisely, we will describe the whole pipeline (from graph construction to link prediction) using the networkx, stellargraph, and node2vec libraries. We will split the whole process into different steps in order to simplify our understanding of the different parts. The link prediction problem was applied to the citation network dataset described in Chapter 1, Getting Started with Graphs, available at the following link: https://linqs-data.soe.ucsc.edu/public/lbc/cora.tgz.
Have a look at the steps mentioned ahead.
We will build a networkx graph using the citation dataset, as follows:
import networkx as nximport pandas as pdedgelist = pd.read_csv("cora.cites", sep='\t', header=None, names=["target", "source"])G = nx.from_pandas_edgelist(edgelist)Since the dataset is represented as an edge list (see Chapter 1, Getting Started with Graphs), we used the from_pandas_edgelist function to build the graph.
Next, we need to create, from the graph G, training and test sets. More precisely, our training and test sets should contain not only a subset of real edges of the graph G but also couples of nodes that do not represent a real edge in G. The couples representing real edges will be positive instances (class label 1), while the couples that do not represent real edges will be negative instances (class label 0). This process can be easily performed as follows:
from stellargraph.data import EdgeSplitteredgeSplitter = EdgeSplitter(G)graph_test, samples_test, labels_test = edgeSplitter.train_test_split(p=0.1, method="global")We used the EdgeSplitter class available in stellargraph. The main constructor parameter of the EdgeSplitter class is the graph (G) we want to use to perform our split. The real splitting is performed using the train_test_split function, with p being the percentage of total edges to be returned (the percentage that will be allocated to the test set), which will generate the following outputs:
graph_testis a subset of the original graph containing all the nodes but just a selected subset of edges.samples_testis a vector containing in each position a couple of nodes. This vector will contain couples of nodes representing real edges (positive instance) but also couples of nodes that do not represent real edges (negative instance).labels_testis a vector having the same length assamples_test. It contains only 0 or 1. The value of 0 is present in the position representing a negative instance in thesamples_testvector, while the value of 1 is present in the position representing a positive instance insamples_test.
By following the same procedure used to generate the test set, it is possible to generate the training set, as illustrated in the following code snippet:
edgeSplitter = EdgeSplitter(graph_test, G)graph_train, samples_train, labels_train = edgeSplitter.train_test_split(p=0.1, method="global")The main difference in this part of code is related to the initialization of EdgeSplitter. In this case, we also provide graph_test in order to not repeat positive and negative instances generated for the test set.
At this point, we have our training and testing datasets with negative and positive instances, where 81% of the edges are in graph_train and will be used to calculate the node2vec embeddings. 9% of the edges are in samples_train, paired with an equal number of negative samples, while 10% of the edges are in samples_test, also matched with an equal number of negative samples. For each of those instances, we now need to generate their feature vectors. In this example, we used the node2vec library to generate the node embedding. In general, every node embedding algorithm can be used to perform this task. For the training set, we can thus generate the feature vector with the following code:
from node2vec import Node2Vecfrom node2vec.edges import HadamardEmbeddernode2vec = Node2Vec(graph_train)model = node2vec.fit()edges_embs = HadamardEmbedder(keyed_vectors=model.wv)train_embeddings = [edges_embs[str(x[0]),str(x[1])] for x in samples_train]From the previous code snippet, it is possible to see the following:
- We generate the embedding for each node in the training graph using the
node2veclibrary. - We use the
HadamardEmbedderclass to generate the embedding of each couple of nodes contained in the training set. Those values will be used as feature vectors to perform the training of our model.
It is worth noticing that we generate the embeddings only for the training graph, since calculating embeddings or other node properties on the full graph, including test data, is a common mistake that leads to data leakage. Furthermore, in this example, we used the HadamardEmbedder algorithm, but in general, other embedding algorithms can be used, such as the ones described in Chapter 4, Unsupervised Graph Learning.
The previous step needs to also be performed for the test set, with the following code:
edges_embs = HadamardEmbedder(keyed_vectors=model.wv)test_embeddings = [edges_embs[str(x[0]),str(x[1])] for x in samples_test]The only difference here is given by the samples_test array used to compute the edge embeddings. Indeed, in this case, we use the data generated for the test set. Moreover, it should be noted that the node2vec algorithm was not recomputed for the test set.
Indeed, given the stochastic nature of node2vec, it is not possible to ensure that the two learned embeddings are “comparable” and therefore node2vec embeddings will change between runs.
Everything is set now. We can finally train—using the train_embeddings feature space and the train_labels label assignment—an ML algorithm to solve the label prediction problem, as follows:
from sklearn.ensemble import RandomForestClassifierrf = RandomForestClassifier(n_estimators=1000)rf.fit(train_embeddings, labels_train)In this example, we used a simple RandomForestClassifier class, but every ML algorithm can be used to solve this task. We can then apply the trained model on the test_embeddings feature space in order to quantify the quality of the classification, as shown in the following code block:
from sklearn import metricsy_pred = rf.predict(test_embeddings)print('Precision:', metrics.precision_score(labels_test, y_pred))print('Recall:', metrics.recall_score(labels_test, y_pred))print('F1-Score:', metrics.f1_score(labels_test, y_pred))As a result, we get the following output:
Precision: 0.8557114228456913Recall: 0.8102466793168881F1-Score: 0.8323586744639375The methods we just described are just a general schema; each piece of the pipeline—such as the train/test split, the node/edge embedding, and the ML algorithm—can be changed according to the specific problem we are facing. For example, the choice of train/test split may vary depending on the size and structure of the graph: for large graphs, techniques like stratified sampling or temporal splits (that we will see in Chapter 11, Temporal Graph Machine Learning) may be more appropriate, while smaller graphs might allow for simpler random splits. Similarly, the embedding method, whether using node2vec or other algorithms, should be selected based on the graph’s characteristics (e.g., if the graph is dense or sparse, directed or undirected), as well as the specific downstream task.
This simple yet powerful pipeline can capture complex patterns beyond local neighborhood similarity. However, it requires high computational costs (to train and tune the ML algorithm) and performances, as in other supervised tasks, may depend on the quality and quantity of labels.
In this section, we introduced the link prediction problem. We enriched our explanation by providing a description, with several examples, of different techniques used to find a solution to the link prediction problem. We showed that different ways to tackle the problem are available, from simple index-based techniques to more complex embedding-based techniques. However, it is worth noticing that the scientific literature is full of algorithms to solve the link prediction task. In the paper by Mutlu et al., Review on Learning and Extracting Graph Features for Link Prediction (https://arxiv.org/pdf/1901.03425.pdf), a good overview of different techniques used to solve the link prediction problem is available. In the next section, we will investigate the community detection problem.
Detecting meaningful structures such as communities
Section titled “Detecting meaningful structures such as communities”One common problem data scientists face when dealing with networks is how to identify clusters and communities within a graph. This often arises when graphs are derived from social networks for which communities are known to exist. However, the underlying algorithms and methods can also be used in other contexts, representing another option to perform clustering and segmentation. For example, these methods can effectively be used in text mining to identify emerging topics and to cluster documents that refer to single events/topics. A community detection task consists of partitioning a graph such that nodes belonging to the same community are tightly connected with each other and are weakly connected with nodes from other communities. There exist several strategies to identify communities. In general, we can define them as belonging to one of two categories, outlined as follows:
- Non-overlapping community detection algorithms that provide a one-to-one association between nodes and communities, thus with no overlapping nodes between communities
- Overlapping community detection algorithms that allow a node to be included in more than one community—for instance, reflecting the natural tendencies of social networks to develop overlapping communities (for example, friends from school, neighbors, playmates, people being in the same football team, and so on), or in biology, where a single protein can be involved in more than one process and bioreaction.
In the following section, we will review some of the most used techniques in the context of community detection.
Embedding-based community detection
Section titled “Embedding-based community detection”One class of methods that allow us to partition nodes into communities can be simply obtained by applying standard shallow clustering techniques on the node embeddings, computed using the methods described in Chapter 4, Unsupervised Graph Learning. The embedding methods in fact allow us to project nodes into a vector space where a distance measure that represents a similarity between nodes can be defined. As we have shown in Chapter 4, Unsupervised Graph Learning, embedding algorithms are very effective in separating nodes with similar neighborhood and/or connectivity properties. Then, standard clustering techniques can be used, such as distance-based clustering (K-means), connectivity clustering (hierarchical clustering), distribution clustering (Gaussian mixture), and density-based clustering (Density-Based Spatial Clustering of Applications with Noise (DBSCAN)). Depending on the algorithm, these techniques may both provide a single-association community detection or a soft cluster assignment. We will showcase how they would work on a simple barbell graph. We start by creating a simple barbell graph using the networkx utility function, as follows:
import networkx as nxG = nx.barbell_graph(m1=10, m2=4)We can then first get the reduced dense node representation using one of the embedding algorithms we have seen previously (for instance, HOPE), shown as follows:
from gem.embedding.hope import HOPEgf = HOPE(d=4, beta=0.01)gf.learn_embedding(G)embeddings = gf.get_embedding()We can finally run a clustering algorithm on the resulting vector representation provided by the node embeddings, like this:
from sklearn.mixture import GaussianMixturegm = GaussianMixture(n_components=3, random_state=0)labels = gm.fit_predict(embeddings)We can plot the network with the computed communities highlighted in different colors, like this:
colors = ["blue", "green", "red"]nx.draw_spring(G, node_color=[colors[label] for label in labels])By doing so, you should obtain the output shown in the following screenshot:

Figure 6.2: Barbell graph where the community detection algorithm has been applied using embedding-based methods
The two clusters, as well as the connecting nodes, have been correctly grouped into three different communities, reflecting the internal structure of the graph.
Spectral methods and matrix factorization
Section titled “Spectral methods and matrix factorization”Another way to achieve a graph partition is to process the adjacency matrix or the Laplacian matrix that represents the connectivity properties of the graph. For instance, spectral clustering can be obtained by applying standard clustering algorithms on the eigenvectors of the Laplacian matrix. In some sense, spectral clustering can also be seen as a special case of an embedding-based community detection algorithm where the embedding technique is so-called spectral embedding, obtained by considering the first k-eigenvectors of the Laplacian matrix. By considering different definitions of the Laplacian as well as different similarity matrices, variations to this method can be obtained. A convenient implementation of this method can be found within the communities Python library and can be used on the adjacency matrix representation easily obtained from a networkx graph, as illustrated in the following code snippet:
from communities.algorithms import spectral_clusteringadj=np.array(nx.adjacency_matrix(G).todense())communities = spectral_clustering(adj, k=2)Where k is the number of communities to cluster nodes into. Moreover, the adjacency matrix (or the Laplacian) can also be decomposed using matrix factorization techniques such as non-negative matrix factorization (NMF)—that allow similar descriptions, as illustrated in the following code snippet:
from sklearn.decomposition import NMFnmf = NMF(n_components=2)score = nmf.fit_transform(adj)communities = [set(np.where(score [:,ith]>0)[0]) for ith in range(2)]The threshold for belonging to the community was set in this example to 0, although other values can also be used to retain only the community cores. Note that these methods are overlapping community detection algorithms, and nodes might belong to more than one community.
Probability models
Section titled “Probability models”Community detection methods can also be derived from fitting the parameters of generative probabilistic graph models. Examples of generative models were already described in Chapter 1, Getting Started with Graphs. However, they did not assume the presence of any underlying community, unlike the so-called stochastic block model (SBM). In fact, this model is based on the assumption that nodes can be partitioned into K disjoint communities and each community has a defined probability of being connected to another. Imagine we want to generate graphs with community structure. For a network of n nodes and K communities, the generative model can be parametrized by the following:
- Membership matrix: , which is an matrix, represents the probabilities of each node belonging to each community. For a node , the row contains the probabilities for being in each of the communities. Sampling from this distribution gives the community assignment .
- Probability matrix: , which is a matrix and represents the probability of an edge existing between two nodes based on their community assignment. For communities and , the edge probability is .
The adjacency matrix A of the graph is then generated probabilistically by the following formula:
For community detection, the goal is reversed. Instead of generating A from M and B, we estimate the community membership (M) and the connection probabilities (B) given the observed adjacency matrix A. This can be done via maximum likelihood estimation, which identifies the M and B that best explain A.
Note that the SBM in the limit of the constant probability matrix (that is, ) corresponds to the Erdős-Rényi model. These models have the advantage of also describing a relation between communities, identifying community-community relationships. This is particularly useful in large-scale-graphs for tasks like social network analysis or biological network modeling.
It is worth noticing that we explained here the idea of the method, but the actual implementation would be more complex. A more detailed mathematical formulation can be found in the paper A review of stochastic block models and extensions for graph clustering (Lee and Wilkinson, 2019).
Cost function minimization
Section titled “Cost function minimization”Community detection in graphs can be approached by optimizing a cost function that evaluates the structure of the graph. Such cost functions typically reward edges within the same community while penalizing edges between different communities. One popular approach involves defining a measure of community quality (such as modularity, for example) and optimizing the assignment of nodes to communities to maximize this measure.
For a binary community structure, each node i is assigned a community label , a variable that takes the values 1 or -1 depending on whether the node belongs to one or two communities. The association between two nodes and can then be expressed using their labels, and . Therefore, a cost function to evaluate the presence of edges between different communities can be defined as:
Where is the adjacency matrix of the graph. When two connected nodes belong to a different community , the contribution provided by the edge is positive. On the other hand, the contribution is 0, both when two nodes are not connected () and when two connected nodes belong to the same community (). Therefore, the problem is to find the best community assignment ( and ) in order to minimize the preceding function. This method, however, applies only to binary community detection and is therefore rather limited in its application.
Another very popular algorithm belonging to this class is the Louvain method, which takes its name from the university where it was invented. This algorithm aims to maximize the modularity, defined as follows:
Here, represents the number of edges, and represent the degree of the -th and -th node respectively, and is the Kronecker delta function, which is 1 when and belong to the same community and 0 otherwise.
By subtracting from the adjacency matrix the expected number of edges that i and j would have in a random graph, , we can estimate how much the actual graph is deviating from the randomness (the Kronecker delta function ensures contribution from only pairs in the same community). The summation, then, aggregates this information across all node pairs, and the division by normalizes modularity, keeping it between −1 and 1. A higher Q indicates that the detected communities have more internal edges than expected by chance, highlighting meaningful structure.
To maximize this modularity efficiently, the Louvain methods iteratively compute the following steps, until no further improvement in modularity can be achieved:
- Modularity optimization: Nodes are swept iteratively, and for each node we compute the change of modularity Q there would be if the node were to be assigned to each community of its neighbors. Once all the values are computed, the node is assigned to the community that provides the largest increase. If there is no increase obtained by placing the node in any other community than the one it is in, the node remains in its original community. This optimization process continues until no changes are induced.
- Node aggregation: In the second step, we build a new network by grouping all the nodes in the same community and connecting the communities using edges that result from the sum of all edges across the two communities. Edges within communities are accounted for as well by means of self-loops that have weights resulting from the sum of all edge weights belonging to the community.
A Louvain implementation can already be found in the communities library, as can be seen in the following code snippet:
from communities.algorithms import louvain_methodcommunities = louvain_method(adj)Another method to maximize the modularity is the Girvan-Newman algorithm, which is based on iteratively removing edges that have the highest betweenness centrality (and thus connect two separate clusters of nodes) to create connected component communities. Here is the code related to this:
from communities.algorithms import girvan_newmancommunities = girvan_newman(adj, n=2)NOTE
The latter algorithm needs to compute the betweenness centrality of all edges to remove the edges. Such computations may be very expensive in large graphs. The Girvan-Newman algorithm in fact scales as , where is the number of edges and is the number of nodes, and should not be used when dealing with large datasets.
Detecting graph similarities and graph matching
Section titled “Detecting graph similarities and graph matching”Learning a quantitative measure of the similarity among graphs is considered a key problem. Indeed, it is a critical step for network analysis and can also facilitate many ML problems, such as classification, clustering, and ranking. Many clustering algorithms, for example, use the concept of similarity for determining if an object should or should not be a member of a group.
In the graph domain, finding an effective similarity measure constitutes a crucial problem for many applications. Consider, for instance, the role of a node inside a graph. This node might be very important for spreading information across a network or guaranteeing network robustness: for example, it could be the center of a star graph or it could be a member of a clique. In this scenario, it would be very useful to have a powerful method for comparing nodes according to their roles. For example, you might be interested in searching for individuals showing similar roles or presenting similar unusual and anomalous behaviors. You might also use it for searching similar subgraphs or to determine network compatibility for knowledge transfer. For example, if you find a method for increasing the robustness of a network and you know that such a network is very similar to another one, you may apply the same solution that worked well for the first network directly to the second one:

Figure 6.3: Example of differences between two graphs
Several metrics can be used for measuring the similarity (distance) between two objects. Some examples include the Euclidean distance, Manhattan distance, cosine similarity, and so on. However, these metrics might fail to capture the specific characteristics of the data being studied, especially on non-Euclidean structures such as graphs. Take the setup shown in Figure 6.3: how “distant” are G1 and G2? They indeed look pretty similar. But what if the missing connection in the red community of G2 causes a severe loss of information? Do they still look similar?
Several algorithmic approaches and heuristics have been proposed for measuring similarity among graphs, based on mathematical concepts such as graph isomorphism, edit distance, and common subgraphs (we suggest reading https://link.springer.com/article/10.1007/s10044-012-0284-8 for a detailed review). Many of these approaches are currently used in practical applications, even if they often require exponentially high computational time to provide a solution to NP-complete problems in general (where NP stands for nondeterministic polynomial time). Therefore, it is essential to find or learn a metric for measuring the similarity of data points involved in the specific task. Here is where ML comes to our aid.
Many algorithms among the ones we have already seen in Chapter 4, Unsupervised Graph Learning, and Chapter 5, Supervised Graph Learning, might be useful for learning an effective similarity metric. According to the way they are used, a precise taxonomy can be defined. Here, we provide a simple overview of graph similarity techniques. A more comprehensive list can be found in the paper Deep Graph Similarity Learning: A Survey (https://arxiv.org/pdf/1912.11615.pdf). They can be essentially divided into three main categories, even if sophisticated combinations can also be developed. Graph embedding-based methods use embedding techniques to obtain an embedded representation of the graphs and exploit such a representation to learn the similarity function; graph kernel-based methods define the similarity between graphs by measuring the similarity of their constituting substructures; graph neural network-based methods use graph neural networks (GNNs) to jointly learn an embedded representation and a similarity function. Let’s see all of them in more detail.
Graph embedding-based methods
Section titled “Graph embedding-based methods”Such techniques seek to apply graph embedding techniques to obtain node-level or graph-level representations and further use the representations for similarity learning. For example, DeepWalk and Node2Vec can be used to extract meaningful embedding that can then be used to define a similarity function or to predict similarity scores. For example, in Tixier et al. (2015), node2vec was used for encoding node embeddings for representing a graph as an image.
Specifically, two-dimensional (2D) histograms obtained from those node embeddings were passed to a classical 2D convolutional neural network (CNN) architecture designed for images. Such a simple yet powerful approach enabled good results to be obtained for many benchmark datasets.
Let’s see an example of how such methods could work. First, let’s define a toy dataset with simple graphs and let’s define random labels for each graph:
# Create toy dataset with simple graphsnum_graphs = 10graphs = [nx.erdos_renyi_graph(10, np.random.rand()) for _ in range(num_graphs)]# Generate random labelslabels = [np.random.choice([0,1]) for _ in range(num_graphs)]We can now define a proper function to generate the 2D histograms and use it on node embeddings:
# Function to generate 2D histogram from node embeddingsdef generate_2d_histogram(node_embeddings, bins=16): # Flatten embeddings to create histograms embeddings = np.vstack(node_embeddings) histogram, xedges, yedges = np.histogram2d(embeddings[:, 0], embeddings[:, 1], bins=bins) return histogram
# Prepare graph-level 2D histograms from node embeddingsgraph_histograms = []for i, graph in enumerate(graphs): node2vec = Node2Vec(graph, dimensions=64, walk_length=10, num_walks=80, workers=4) model = node2vec.fit() node_embeddings = [model.wv.get_vector(str(node)) for node in graph.nodes()] histogram = generate_2d_histogram(node_embeddings) graph_histograms.append(histogram)We can now split our dataset into training and testing sets:
# Split histograms into training and testing setstrain_histograms, test_histograms, train_labels, test_labels = train_test_split(graph_histograms, labels, test_size=0.5, random_state=42)Finally, let’s define and train our GraphCNN model. We will be using PyTorch for this:
# Initialize and train the CNN modelnum_classes = 2 # Binary classificationinput_channels = 1 # Single channel for histogrambins = 16 # Same as used in generate_2d_histogram functiontrain_histograms = train_histograms.unsqueeze(1) # Add channel dimensiontest_histograms = test_histograms.unsqueeze(1)cnn_model = GraphCNN(input_channels, num_classes)criterion = nn.CrossEntropyLoss()optimizer = optim.Adam(cnn_model.parameters(), lr=0.001)
# Training loopcnn_model.train()epochs = 20for epoch in range(epochs): optimizer.zero_grad() outputs = cnn_model(train_histograms) loss = criterion(outputs, torch.tensor(train_labels, dtype=torch.long)) loss.backward() optimizer.step() print(f"Epoch {epoch+1}/{epochs}, Loss: {loss.item()}")
# Evaluate on test setcnn_model.eval()with torch.no_grad(): test_outputs = cnn_model(test_histograms) predictions = torch.argmax(test_outputs, axis=1) accuracy = accuracy_score(test_labels, predictions.numpy()) print(f"Test Accuracy: {accuracy}")The above code is an example based on a toy random dataset. For this reason, the accuracy would probably be low. However, it effectively shows how such a technique can be used on real graphs and we will invite the reader to explore this approach as an exercise.
Graph kernel-based methods
Section titled “Graph kernel-based methods”Graph kernel-based methods have generated a lot of interest in terms of capturing the similarity between graphs. These approaches compute the similarity between two graphs as a function of the similarities between some of their substructures. Different graph kernels exist based on the substructures they use, which include random walks, shortest paths, and subgraphs.
As an example, a method called Deep Graph Kernels (DGK) (Yanardag et al., 2015) decomposes graphs into substructures that are viewed as “words.” Then, natural language processing (NLP) approaches such as continuous bag of words (CBOW) and skip-gram are used to learn latent representations of the substructures. This way, the kernel between two graphs is defined based on the similarity of the substructure space.
Let’s see how such an approach can be used on the toy dataset generated in the previous example. First, let’s define a proper function to decompose graphs into substructures using random walks. Then, let’s use it to create a “document” for each graph:
# Decompose graphs into substructures using random walksdef random_walks_as_words(graph, walk_length=6, num_walks=10): """Generates 'words' from random walks on the graph.""" walks = [] for _ in range(num_walks): for node in graph.nodes(): walk = [str(node)] for _ in range(walk_length - 1): neighbors = list(graph.neighbors(int(walk[-1]))) if neighbors: walk.append(str(np.random.choice(neighbors))) else: break walks.append(" ".join(walk)) return walks
# Create a "document" for each graph using its random walksgraph_documents = []for graph in graphs: walks = random_walks_as_words(graph) # Combine all walks into a single document graph_documents.append(" ".join(walks))We can now use the CountVectorizer function to create a numerical representation of each graph based on the frequency of specific patterns or features. This function processes a collection of textual data and generates a matrix where each entry indicates how often a particular pattern or feature appears in the graph:
# Generate "bag of words" representation for each graphvectorizer = CountVectorizer()# Sparse matrix of shape (num_graphs, num_features)graph_bow = vectorizer.fit_transform(graph_documents)Then, we can compute pairwise similarity out of it:
# Compute pairwise similarities between graphsgraph_similarity_matrix = cosine_similarity(graph_bow)We now have all the ingredients to train a machine learning algorithm. As usual, we will now split the dataset into training and test sets and use the similarity matrix as input features for a classification task:
# Split dataset into training and testing setstrain_indices, test_indices = train_test_split(range(len(graphs)), test_size=0.5, random_state=42)train_similarity = graph_similarity_matrix[np.ix_(train_indices, train_indices)]test_similarity = graph_similarity_matrix[np.ix_(test_indices, train_indices)] # Test against training similaritiestrain_labels = [labels[i] for i in train_indices]test_labels = [labels[i] for i in test_indices]
# Train a classifier using the training similarity matrixsvm = SVC(kernel="precomputed") # Precomputed kernelsvm.fit(train_similarity, train_labels)
# Predict on the test settest_predictions = svm.predict(test_similarity)
# Evaluate the classification accuracyaccuracy = accuracy_score(test_labels, test_predictions)print(f"Test Accuracy using Deep Graph Kernels (DGK): {accuracy}")Also, in this case, the output is not meaningful, since we are training the algorithm on random labels for demonstration purposes. Feel free to use the approach on a real dataset!
It is worth noticing that we have introduced some NLP concepts here. We will cover the topic in more detail in Chapter 8, Text Analytics and Natural Language Processing Using Graphs.
GNN-based methods
Section titled “GNN-based methods”With the emergence of deep learning (DL) techniques, GNNs have become a powerful new tool for learning representations on graphs. Such powerful models can be easily adapted to various tasks, including graph similarity learning. Furthermore, they present a key advantage with respect to other traditional graph embedding approaches. Indeed, while the latter generally learn the representation in an isolated stage, in this kind of approach, the representation learning and the target learning task are conducted jointly. Therefore, the GNN deep models can better leverage the graph features for the specific learning task. We have already seen an example of similarity learning using GNNs in Chapter 4, Unsupervised Graph Learning, where a two-branch network was trained to estimate the proximity distance between two graphs.
Applications
Section titled “Applications”Similarity learning on graphs has already achieved promising results in many domains. Important applications may be found in chemistry and bioinformatics—for example, for finding the chemical compounds that are most similar to a query compound, as illustrated on the left-hand side of the following diagram. In neuroscience, similarity learning methods have started to be applied to measure the similarity of brain networks among multiple subjects, allowing the novel clinical investigation of brain diseases.

Figure 6.4: Example of how graphs can be useful for representing various objects: (a) differences between two chemical compounds; (b) differences between two human poses
Graph similarity learning has also been explored in computer security, where novel approaches have been proposed for the detection of vulnerabilities in software systems as well as hardware security problems (a survey of these approaches can be found at https://eprint.iacr.org/2019/983.pdf). Recently, a trend for applying such solutions to solve computer vision problems has been observed (you may check https://ieeexplore.ieee.org/document/9263681 for further reading). Once the challenging problem of converting images into graph data has been solved, interesting solutions can indeed be proposed for human action recognition in video sequences and object matching in scenes, among other areas. In the context of human action recognition, graphs provide an intuitive way to model the human body. Here, body joints (e.g., elbows, knees, shoulders) are represented as nodes, while the connections between them (e.g., bones) serve as edges. This creates a graph that encodes the spatial relationships and hierarchical structure of the human body (as shown on the right-hand side of Figure 6.4).Therefore, such graphs can be studied using flexible techniques such as GCN, which can capture both local and global patterns in the data. Notice also that temporal relationships can be exploited (which are critical for understanding actions) by creating spatio-temporal graphs where multiple body pose graphs are connected over time. These approaches enable effective recognition of complex human activities by leveraging both spatial and temporal dynamics. We will learn more about temporal graphs in Chapter 11, Temporal Graph Machine Learning.
Summary
Section titled “Summary”In this chapter, we have learned how graph-based ML techniques can be used to solve many different problems. In particular, we have seen that the same algorithm (or a slightly modified version) can be adapted to solve apparently very different tasks such as link prediction, community detection, and graph similarity learning. We have also seen that each problem has its own peculiarities, which have been exploited by researchers in order to design more sophisticated solutions.
In the next chapter, we will explore real-world problems related to social networking that can be solved using graph-based ML.