Skip to content
ImagineWorld

Unsupervised Graph Learning

node_idnode-book_graph-machine-learning_chapter-04-unsupervised-graph-learning
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num4
chapter_titleUnsupervised Graph Learning
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Unsupervised machine learning refers to the subset of machine learning algorithms that do not exploit any target information during training. Instead, they work on their own to find clusters, discover patterns, detect anomalies, and solve many other problems for which there is no teacher and no correct answer known a priori.

As per many other machine learning algorithms, unsupervised models have found large applications in the graph representation learning domain. Indeed, they represent an extremely useful tool for solving various downstream tasks, such as node classification and community detection, among others.

In this chapter, an overview of recent unsupervised graph embedding methods will be provided. When given a graph, the goal of these techniques is to automatically learn a latent representation of it, in which the key structural components are somehow preserved.

The following topics will be covered in this chapter:

  • The unsupervised graph embedding roadmap
  • Shallow embedding methods
  • Autoencoders
  • Graph neural networks

All code files relevant to this chapter are available at https://github.com/PacktPublishing/Graph-Machine-Learning/tree/main/Chapter04. Please refer to the Practical exercises section of Chapter 1, Getting Started with Graphs, for guidance on how to set up the environment to run the examples in this chapter, using either Poetry, pip, or docker.

For the more complex data visualization tasks provided in this chapter, Gephi (https://gephi.org/) may also be required. The installation manual is available here: https://gephi.org/users/install/.

Unsupervised machine learning involves algorithms that can be trained without the need for manually annotated data, making them especially valuable for identifying hidden structures and relationships in complex graph networks. Most of these models rely only on information in the adjacency matrix and the node features, without any knowledge of the downstream machine learning task.

How can this be done? One of the most common approaches is to learn embeddings that preserve the graph structure. The learned representation is usually optimized so that it can be used to reconstruct the pair-wise node similarity, for example, the adjacency matrix. These techniques bring an important feature: the learned representation can encode latent relationships among nodes or graphs, allowing us to discover hidden and complex novel patterns.

Many algorithms have been developed in relation to unsupervised graph machine learning techniques. However, as previously reported by different scientific papers (https://arxiv.org/abs/2005.03675), those algorithms can be grouped into three macro-groups: shallow embedding methods, autoencoders, and Graph Neural Networks (GNNs), as described in the following chart:

Figure 4.1: The hierarchical structure of the different unsupervised embedding algorithms described in this book

Figure 4.1: The hierarchical structure of the different unsupervised embedding algorithms described in this book

In the following sections, you will learn about the main principles behind each group of algorithms. We will try to provide the idea behind the most well-known algorithms in the field as well as how they can be used to solve real problems.

As already introduced in Chapter 2, Graph Machine Learning, with shallow embedding methods, we identify a set of algorithms that are able to learn and return only the embedding values for the learned input data.

In this section, we will explore two main categories of these methods: matrix factorization-based approaches and skip-gram-based approaches. Matrix factorization methods decompose the adjacency matrix to capture latent patterns in the graph, while skip-gram methods, inspired by natural language processing, learn embeddings by predicting the likelihood of node co-occurrences. We will dive into these techniques in detail and provide Python examples for each, using libraries such as Graph Embedding Methods (GEM), Node to Vector (Node2Vec), and karateclub.

Matrix factorization is a general decomposition technique widely used in different domains. The technique has become very popular, especially in the context of recommendation engines (e.g., see Zhou et al., 2008), where the matrix to be decomposed is the so-called user-product matrix, having users, , along the rows and products, , along the columns, and the values in each cell, , representing a score. Depending on the context, the score may have different forms: it may be a binary score representing whether the user bought a particular product, or it may also be a positive number representing how many times a user listened to a particular song. Interestingly, as we have seen in Chapter 1, Getting Started with Graphs, the user-product matrix could also be seen as the adjacency matrix of bipartite graphs, composed of two kinds of nodes: the users and the products/songs, and links (weighted) between them depending on whether the users bought a given product or listened to a given song. By re-mapping users and products into a Cartesian space (embeddings), matrix factorization techniques will provide a measure to quantify how similar users and/or products are, therefore providing the basis for a recommendation.

More generally, matrix factorization can be applied to graph structures to compute the various embeddings of a graph, and indeed a significant number of widely used graph embedding algorithms rely on this technique.

We will start by providing a general introduction to the matrix factorization problem. After the introduction of the basic principles, we will describe two algorithms, namely graph factorization (GF) and High-Order Proximity Preserved Embedding (HOPE), which use matrix factorization to build the node embedding of a graph.

Let be the input data. Matrix factorization decomposes , with and called the source matrix and the abundance matrix, respectively, and d is the number of dimensions of the generated embedding space. The matrix factorization algorithm learns the V and H matrices by minimizing a loss function that can change according to the specific problem we want to solve. In its general formulation, the loss function is defined by computing the reconstruction error using the Frobenius norm as .

Generally speaking, all the unsupervised embedding algorithms based on matrix factorization use the same principle. They all factorize an input graph expressed as a matrix in different components. The main difference between each method lies in the loss function used during the optimization process and the constraints/formulations posed for the V and H matrices. Indeed, different loss functions allow the creation of an embedding space that emphasizes specific properties of the input graph.

In the following sections, we will compare the different embedding algorithms using the same simple barbell network shown in Figure 4.2, to show the main similarities and differences. The graph can be generated with the following code snippet:

import networkx as nx
G = nx.barbell_graph(m1=10, m2=4)

When applied to this graph, all algorithms will output pairs of coordinates that will be plotted in an xy scatter plot. To help understand the results, we will color the points based on the color scheme depicted in the following figure:

Figure 4.2: Color scheme used when comparing the different algorithms

Figure 4.2: Color scheme used when comparing the different algorithms

The GF algorithm was one of the first models to reach good computational performance in order to perform the node embedding of a given graph. By following the principle of matrix factorization that we previously described, the GF algorithm factorizes the adjacency matrix of a given graph.

Formally, let G = (V, E) be the graph for which we want to compute the node embedding and let be its adjacency matrix. The loss function (L) used in this matrix factorization problem is as follows:

In the preceding equation, represents one of the edges in G while is the matrix containing the d-dimensional embedding. Each row of the matrix represents the embedding of a given node. Moreover, a regularization term of the embedding matrix is used to ensure that the problem remains well posed even in the absence of sufficient data.

The loss function used in this method was mainly designed to improve GF performance and scalability. Indeed, the solution generated by this method could be noisy. Moreover, it should be noted, by looking at its matrix factorization formulation, that GF performs a strong symmetric factorization. This property is particularly suitable for undirected graphs, where the adjacency matrix is symmetric, but could be a potential limitation for directed graphs.

In the following code, we will show how to perform the node embedding for the barbell graph in Figure 4.2 using Python and the GEM library:

from gem.embedding.gf import GraphFactorization
gf = GraphFactorization(d=2, data_set=None, max_iter=10000, eta=1*10**-4, regu=1.0)
gf.learn_embedding(G)
embeddings = gf.get_embedding()

In the preceding example, the following have been done:

  1. The GraphFactorization class is used to generate a d=2-dimensional embedding space.
  2. The computation of the node embeddings of the input graph is performed using gf.learn_embedding(G).
  3. The computed embeddings are extracted by calling the gf.get_embedding() method.

The results of the previous code are shown in the following graph:

Figure 4.3: Application of the GF algorithm to generate the embedding vectors for the nodes of the barbell graph shown in Figure 4.2. The color scheme depicted in Figure 4.2 has been used. Axes represent the first two latent directions of the embedding algorithm.

From Figure 4.3, it is possible to see how nodes belonging to groups 1 and 3 are mapped together in the same region of space. Those points are separated by the nodes belonging to group 2. This mapping allows us to separate groups 1 and 3 from group 2 quite well. Unfortunately, there is no clear separation between groups 1 and 3.

Higher-order proximity preserved embedding

Section titled “Higher-order proximity preserved embedding”

HOPE is another graph embedding technique based on the matrix factorization principle. This method allows for the preservation of higher-order proximity and does not force its embeddings to have any symmetric properties. Before starting to describe the method, let’s understand what first-order proximity and high-order proximity mean:

  • First-order proximity: Given a graph, G = (V,E), where the edges have a weight, wij, for each vertex pair (vi,vj), we say they have a first-order proximity equal to wij if the edge . Otherwise, the first-order proximity between the two nodes is 0.
  • Second- and high-order proximity: With the second-order proximity, we can capture the two-step relations between each pair of vertices. For each vertex pair (vi,vj), we can see the second-order proximity as a two-step transition from vi to vj. High-order proximity generalizes this concept and allows us to capture a more global structure. As a consequence, high-order proximity can be viewed as a k-step (k ≥ 3) transition from vi to vj.

Given the definition of proximity, we can now describe the HOPE method. Formally, let G = (V, E) be the graph we want to compute the embedding for. The loss function (L) used by this problem is as follows:

In the preceding equation, is a similarity matrix generated from graph G and its adjacency matrix , and and are two embedding matrices representing a d-dimensional embedding space. In more detail, YS represents the source embedding and Yt represents the target embedding.

HOPE uses those two matrices in order to capture asymmetric proximity in directed networks where the direction from a source node and a target node is present. The final embedding matrix, Y, is obtained by simply concatenating, column-wise, the YS and Yt matrices. Due to this operation, the final embedding space generated by HOPE will have 2 x d dimensions.

As we already stated, the S matrix is a similarity matrix obtained from the original graph, G. The goal of S is to obtain high-order proximity information. Formally, it is computed as S = Mg . Ml, where Mg and Ml are both polynomials of matrices.

In its original formulation, the authors of HOPE suggested different ways of computing Mg and Ml. Here, we report a common and easy method of computing those matrices, Adamic-Adar (AA). In this formulation, Mg = I (the identity matrix) while Ml = ADA, where D is a diagonal matrix (inverted) computed as . Other formulations to compute Mg and Ml are the Katz index, Rooted PageRank (RPR), and Common Neighbors (CN).

In the following code, we will show you how to perform the node embedding for the barbell graph in Figure 4.2 using Python and the GEM library:

from gem.embedding.hope import HOPE
gf = HOPE(d=4, beta=0.01)
gf.learn_embedding(G)
embeddings = gf.get_embedding()

The preceding code is similar to the one used for GF. The only difference is in the class initialization since here we use HOPE. According to the implementation provided by GEM, the d parameter, representing the dimension of the embedding space, will define the number of columns of the final embedding matrix, Y, obtained after the column-wise concatenation of Ys and Yt.

As a consequence, the number of columns of Ys and Yt is defined by the floor division (the // operator in Python) of the value assigned to d. The results of the code are shown in the following graph:

Figure 4.4: Application of the HOPE algorithm to generate the embedding vector for the nodes of the barbell graph shown in Figure 4.2. The color scheme depicted in Figure 4.2 has been used. Axes represent the first two latent directions of the embedding algorithm.

Figure 4.4: Application of the HOPE algorithm to generate the embedding vector for the nodes of the barbell graph shown in Figure 4.2. The color scheme depicted in Figure 4.2 has been used. Axes represent the first two latent directions of the embedding algorithm.

In this case, the graph is undirected and thus there is no difference between the source and target nodes. Figure 4.4 shows the first two dimensions of the embeddings matrix representing Ys. It is possible to see how the embedding space generated by HOPE provides, in this case, a better separation of the different nodes.

Graph representation with global structure information

Section titled “Graph representation with global structure information”

Graph representation with global structure information (GraphRep), such as HOPE, allows us to preserve higher-order proximity without forcing its embeddings to have symmetric properties. Formally, let G = (V, E) be the graph for which we want to compute the node embeddings and be its adjacency matrix. The loss function (L) used by this problem is as follows:

In the preceding equation, is a matrix generated from graph G in order to get the kth order of proximity between nodes.

and are two embedding matrices representing a d-dimensional embedding space of the kth order of proximity for the source and target nodes, respectively.

The Xk matrix is computed according to the following equation: . Here, D is a diagonal matrix known as the degree matrix computed using the following equation:

represents the (one-step) probability transition matrix, where is the probability of a transition from vi to vertex vj within one step. In general, for a generic value of k, represents the probability of a transition from vi to vertex vj within k steps.

For each order of proximity, k, an independent optimization problem is fitted. All the k embedding matrices generated are then column-wise concatenated to get the final source embedding matrices.

In the following code, we will show how to perform the node embedding for the barbell graph in Figure 4.2 using Python and the karateclub library:

from karateclub.node_embedding.neighbourhood.grarep import GraRep
gr = GraRep(dimensions=2, order=3)
gr.fit(G)
embeddings = gr.get_embedding()

We initialize the GraRep class from the karateclub library. In this implementation, the dimensions parameter represents the dimension of the embedding space, while the order parameter defines the maximum number of orders of proximity between nodes. The number of columns of the final embedding matrix (stored, in the example, in the embeddings variable) is dimension*order, since, as we said, for each proximity order an embedding is computed and concatenated in the final embedding matrix.

Since two dimensions are computed in the example, embeddings[:,:2] represents the embedding obtained for k=1, embeddings[:,2:4] for k=2, and embeddings[:,4:] for k=3. The results of the code are shown in the following graphs:

Figure 4.5: Application of the GraphRep algorithm to generate the embedding vectors for different values of k for the nodes of the barbell graph shown in Figure 4.2. The color scheme depicted in Figure 4.2 has been used. Axes represent the first two latent directions of the embedding algorithm.

Figure 4.5: Application of the GraphRep algorithm to generate the embedding vectors for different values of k for the nodes of the barbell graph shown in Figure 4.2. The color scheme depicted in Figure 4.2 has been used. Axes represent the first two latent directions of the embedding algorithm.

From the preceding graphs, it is easy to see how different orders of proximity allow us to get different embeddings. Since the input graph is quite simple, in this case, already with k=1, a well-separated embedding space is obtained. The nodes belonging to groups 1 and 3 in all the proximity orders have the same embedding values (they are overlapping in the scatter plot).

Notice that the superior performance of k=1 can be attributed to the differences in how proximity is captured. While GF uses a regularization term to control the complexity of the model, this may oversimplify the representation in some cases, leading to less distinct embeddings. In contrast, the k=1 embedding focuses on local relationships, which might be sufficient to capture the necessary structure in this simple graph.

In this section, we have described some matrix factorization methods for unsupervised graph embedding. In the next section, we will introduce a different way of performing unsupervised graph embedding using skip-gram models.

In this section, we will provide a quick description of the skip-gram model. Since it is widely used by different embedding algorithms, a high-level description is needed to better understand the different methods. Before going deep into a detailed description, let’s look at a brief overview.

The skip-gram model is a simple neural network with one hidden layer trained in order to predict the probability of a given word being present when one or more input words are present. The neural network is trained by building the training data using a text corpus as a reference. This process is described in the following chart:

Figure 4.6: Example of the generation of training data from a given corpus. In the colored boxes are the target words. In the white boxes are the context words identified by a window size of length 2

Figure 4.6: Example of the generation of training data from a given corpus. In the colored boxes are the target words. In the white boxes are the context words identified by a window size of length 2

The example described in Figure 4.6 shows how the algorithm to generate the training data works. A target word is selected and a rolling window of fixed size w is built around that word. The words inside the rolling windows are known as context words. Multiple pairs of (target word, context word) are then built according to the words inside the rolling window.

Once the training data is generated from the whole corpus, the skip-gram model is trained to predict the probability of a word being a context word for the given target. During its training, the neural network learns a compact representation of the input words. This is why the skip-gram model is also known as Word to Vector (Word2Vec).

The structure of the neural network representing the skip-gram model is described in the following chart:

Figure 4.7: Structure of the neural network of the skip-gram model. The number of d neurons in the hidden layer represents the final size of the embedding space

Figure 4.7: Structure of the neural network of the skip-gram model. The number of d neurons in the hidden layer represents the final size of the embedding space

The input of the neural network is a binary vector of size m. Each element of the vector represents a word in the dictionary of the language we want to embed the words in. When, during the training process, a (target word, context word) pair is given, the input array will have 0 in all its entries with the exception of the entry representing the target word, which will be equal to 1. The hidden layer has d neurons. The hidden layer will learn the embedding representation of each word, creating a d-dimensional embedding space.

Finally, the output layer of the neural network is a dense layer of m neurons (the same size as the input vector) with a softmax activation function. Each neuron represents a word in the dictionary. The value assigned by the neuron corresponds to the probability of that word being “related” to the input word. Since softmax can be hard to compute when the size of m increases, a hierarchical softmax approach is always used.

The final goal of the skip-gram model is not to actually learn the task we previously described but to build a compact d-dimensional representation of the input words. Thanks to this representation, it is possible to easily extract an embedding space for the words using the weight of the hidden layer. Another common approach to creating a skip-gram model, which will not be described here, is context-based: Continuous Bag-of-Words (CBOW).

Since the basic concepts behind the skip-gram model have been introduced, we can start to describe a series of unsupervised graph embedding algorithms built upon this model. Generally speaking, all the unsupervised embedding algorithms based on the skip-gram model use the same principle.

Starting from an input graph, they extract from it a set of walks. Those walks can be seen as a text corpus where each node represents a word. Two words (representing nodes) are near each other in the text if they are connected by an edge in a walk. The main difference between each method lies in the way those walks are computed. Indeed, as we will see, different walk generation algorithms can emphasize particular local or global structures of the graph.

The DeepWalk algorithm generates the node embedding of a given graph using the skip-gram model. In order to provide a better explanation of this model, we need to introduce the concept of random walks.

Let G be a graph and vi be a vertex selected as the starting point. We select a neighbor of vi at random and move toward it. From this point, we randomly select another point to move toward. This process is repeated t times. The random sequence of t vertices selected in this way is a random walk of length t. It is worth mentioning that the algorithm used to generate the random walks does not impose any constraint on how they are built. As a consequence, there is no guarantee that the local neighborhood of the node is well preserved.

Using the notion of random walks, the DeepWalk algorithm generates a random walk of a size of at most t for each node. Those random walks will be given as input to the skip-gram model. The embedding generated using skip-gram will be used as the final node embedding. In the following figure (Figure 4.8), we can see a step-by-step graphical representation of the algorithm:

Figure 4.8: All the steps used by the DeepWalk algorithm to generate the node embedding of a given graph

Figure 4.8: All the steps used by the DeepWalk algorithm to generate the node embedding of a given graph

Here is a step-by-step explanation of the algorithm graphically described in the preceding chart:

  1. Random walk generation: For each node of input graph G, a set of random walks with a fixed maximum length (t) is computed. It should be noted that the length t is an upper bound. There are no constraints forcing all the paths to have the same length, especially in direct graphs where the random walks may end up on dead ends, i.e., nodes with no out-going edges.
  2. Skip-gram training: Using all the random walks generated in the previous step, a skip-gram model is trained. As we described earlier, the skip-gram model works on words and sentences. When a graph is given as input to the skip-gram model, as visible in Figure 4.8, a graph can be seen as an input text corpus, while a single node of the graph can be seen as a word of the corpus.
  3. A random walk can be seen as a sequence of words (a sentence). The skip-gram is then trained using the “fake” sentences generated by the nodes in the random walk. The parameters for the skip-gram model previously described (window size, w, and embed size, d) are used in this step.
  4. Embedding generation: The information contained in the hidden layers of the trained skip-gram model is used in order to extract the embedding of each node.

In the following code, we will show how to perform the node embedding for the barbell graph in Figure 4.2 using Python and the karateclub library:

from karateclub.node_embedding.neighbourhood.deepwalk import DeepWalk
dw = DeepWalk(dimensions=2)
dw.fit(G)
embeddings = dw.get_embedding()

The code is quite simple. We initialize the DeepWalk class from the karateclub library. In this implementation, the dimensions parameter represents the dimension of the embedding space. Other parameters worth mentioning that the DeepWalk class accepts are as follows:

  • walk_number: The number of random walks to generate for each node
  • walk_length: The length of the generated random walks
  • window_size: The window size parameter of the skip-gram model

Finally, the model is fitted on graph G using dw.fit(G) and the embeddings are extracted using dw.get_embedding().

The results of the code are shown in the following figure:

Figure 4.9: Application of the DeepWalk algorithm to generate the embedding vectors for the nodes of the barbell graph shown in Figure 4.2. The color scheme depicted in Figure 4.2 has been used. Axes represent the first two latent directions of the embedding algorithm.

Figure 4.9: Application of the DeepWalk algorithm to generate the embedding vectors for the nodes of the barbell graph shown in Figure 4.2. The color scheme depicted in Figure 4.2 has been used. Axes represent the first two latent directions of the embedding algorithm.

From the previous graph, we can see how DeepWalk is able to separate region 1 from region 3. Those two groups are contaminated by the nodes belonging to region 2. Indeed, for those nodes, a clear distinction is not visible in the embedding space.

The Node2Vec algorithm can be seen as an extension of DeepWalk. Indeed, as with DeepWalk, Node2Vec also generates a set of random walks used as input to a skip-gram model. Once trained, the hidden layers of the skip-gram model are used to generate the embedding of the node in the graph. The main difference between the two algorithms lies in the way the random walks are generated.

Indeed, if DeepWalk generates random walks without using any bias, in Node2Vec a new technique to generate biased random walks on the graph is introduced. The algorithm to generate the random walks combines graph exploration by merging Breadth-First Search (BFS) and Depth-First Search (DFS). The way those two algorithms are combined in the random walk’s generation is regularized by two parameters, p and q. p defines the probability of a random walk getting back to the previous node, while q defines the probability that a random walk can pass through a previously unseen part of the graph.

Due to this combination, Node2Vec can preserve high-order proximities by preserving local structures in the graph as well as global community structures. This new method of random walk generation allows solving the limitation of DeepWalk preserving the local neighborhood properties of the node.

In the following code, we will show how to perform the node embedding for the barbell graph in Figure 4.2 using Python and the node2vec library:

from node2vec import Node2Vec
draw_graph(G)
node2vec = Node2Vec(G, dimensions=2)
model = node2vec.fit(window=10)
embeddings = model.wv

For Node2Vec, the code is straightforward. We initialize the Node2Vec class from the node2vec library. In this implementation, the dimensions parameter represents the dimension of the embedding space. The model is then fitted using node2vec.fit(window=10). Finally, the embeddings are obtained using model.wv.

It should be noted that model.wv is an object of the Word2VecKeyedVectors class. In order to get the embedding vector of a specific node with node as the ID, we can use the trained model, as follows: model.wv[str(Node)]. Other parameters worth mentioning that the Node2Vec class accepts are as follows:

  • num_walks: The number of random walks to generate for each node
  • walk_length: The length of the generated random walks
  • p, q: The p and q parameters of the random walk’s generation algorithm

The results of the code are shown in Figure 4.10:

Figure 4.10: Application of the Node2Vec algorithm to generate the embedding vectors for the nodes of the barbell graph shown in Figure 4.2. The color scheme depicted in Figure 4.2 has been used. Axes represent the first two latent directions of the embedding algorithm.

Figure 4.10: Application of the Node2Vec algorithm to generate the embedding vectors for the nodes of the barbell graph shown in Figure 4.2. The color scheme depicted in Figure 4.2 has been used. Axes represent the first two latent directions of the embedding algorithm.

As is visible from Figure 4.10, Node2Vec allows us to obtain a better separation between nodes in the embedding space compared to DeepWalk. Regions 1 and 3 are well clustered in two regions of space. Region 2 instead is well placed in the middle of the two groups without any overlap.

Contrary to the other embedding function, the Edge to Vector (Edge2Vec) algorithm generates the embedding space on edges, instead of nodes. This algorithm is a simple side effect of the embedding generated by using Node2Vec. The main idea is to use the node embedding of two adjacent nodes to perform some basic mathematical operations in order to extract the embedding of the edge connecting them.

Formally, let vi and vj be two adjacent nodes and let f(vi) and f(vj) be their embeddings computed with Node2Vec. The operators described in Table 4.1 can be used in order to compute the embedding of their edge:

Table 4.1: Edge embedding operators with their equation and class name in the Node2Vec library

Table 4.1: Edge embedding operators with their equation and class name in the Node2Vec library

In the following code, we will show how to perform the edge embedding using the Node2Vec embedding of the barbell graph shown in Figure 4.2 using Python:

from node2vec.edges import HadamardEmbedder
embedding = HadamardEmbedder(keyed_vectors=model.wv)

The code is quite simple. The HadamardEmbedder class is instantiated with only the keyed_vectors parameter. The value of this parameter is the embedding model generated by Node2Vec. In order to use other techniques to generate the edge embedding, we just need to change the class and select one from those listed in Table 4.1. An example of the application of this algorithm is shown in the following figure, where each label represents the corresponding source and target IDs, and the fill and stroke colors are inherited from the source and target nodes, respectively.

Figure 4.11: Application of the Edge2Vec algorithm to the Node2Vec embeddings of the barbell graph shown in Figure 4.2. Each node label presents the corresponding source and target IDs in the source-target format, and the color coding refers to the one shown in Figure 4.2, where the fill and stroke colors are based on the source and target, respectively. Axes represent the first two latent directions of the embedding algorithm.

Figure 4.11: Application of the Edge2Vec algorithm to the Node2Vec embeddings of the barbell graph shown in Figure 4.2. Each node label presents the corresponding source and target IDs in the source-target format, and the color coding refers to the one shown in Figure 4.2, where the fill and stroke colors are based on the source and target, respectively. Axes represent the first two latent directions of the embedding algorithm.

From Figure 4.11, we can see how different embedding methods generate completely different embedding spaces. AverageEmbedder and HadamardEmbedder, in this example, generate well-separated embeddings for regions 1, 2, and 3.

For WeightedL1Embedder and WeightedL2Embedder, however, the embedding space is less well separated: the embedding is only able to differentiate the terminal edges attached to the cliques, whereas all the other nodes fall approximately on the same region.

The methods we previously described generated the embedding space for each node or edge on a given graph. Graph to Vector (Graph2Vec) generalizes this concept and generates embeddings for the whole graph.

Given a set of graphs, the Graph2Vec algorithms generate an embedding space where each point represents a graph. This algorithm generates its embedding using an evolution of the Word2Vec skip-gram model known as Document to Vector (Doc2Vec). We can graphically see a simplification of this model in Figure 4.12:

Figure 4.12: Simplified graphical representation of the Doc2Vec skip-gram model. The number of d neurons in the hidden layer represents the final size of the embedding space

Figure 4.12: Simplified graphical representation of the Doc2Vec skip-gram model. The number of d neurons in the hidden layer represents the final size of the embedding space

Compared to the simple Word2Vec, Doc2Vec also accepts another binary array representing the document containing the input word. Given a “target” document and a “target” word, the model then tries to predict the most probable “context” word with respect to the input “target” word and document.

With the introduction of the Doc2Vec model, we can now describe the Graph2Vec algorithm. The main idea behind this method is to view an entire graph as a document and each of its subgraphs, generated as an ego graph (see Chapter 1, Getting Started with Graphs) of each node, as words that comprise the document.

In other words, a graph is composed of subgraphs as a document is composed of sentences. According to this description, the algorithm can be summarized into the following steps:

  1. Subgraph generation: A set of rooted subgraphs is generated around every node.
  2. Doc2Vec training: The Doc2Vec skip-gram is trained using the subgraphs generated by the previous step.
  3. Embedding generation: The information contained in the hidden layers of the trained Doc2Vec model is used in order to extract the embedding of each node and graph.

In the following code, as we already did in Chapter 2, Graph Machine Learning, we will show how to perform the node embedding of a set of networkx graphs using Python and the karateclub library:

import matplotlib.pyplot as plt
from karateclub import Graph2Vec
n_graphs = 20
def generate_random():
n = random.randint(6, 20)
k = random.randint(5, n)
p = random.uniform(0, 1)
return nx.watts_strogatz_graph(n,k,p)
Gs = [generate_random() for x in range(n_graphs)]
model = Graph2Vec(dimensions=2)
model.fit(Gs)
embeddings = model.get_embedding()

In this example, the following have been done:

  1. 20 Watts-Strogatz graphs have been generated with random parameters.
  2. We then initialize the Graph2Vec class from the karateclub library with two dimensions. In this implementation, the dimensions parameter represents the dimension of the embedding space.
  3. The model is then fitted on the input data using model.fit(Gs).
  4. The vector containing the embeddings is extracted using model.get_embedding().

The results of the code are shown in the following figure:

Figure 4.13: Application of the Graph2Vec algorithm to a graph (left) to generate the embedding vector of its nodes (right) using different methods

Figure 4.13: Application of the Graph2Vec algorithm to a graph (left) to generate the embedding vector of its nodes (right) using different methods

From Figure 4.13, it is possible to see the embedding space generated for the different graphs.

In this section, we described different shallow embedding methods based on matrix factorization and the skip-gram model. However, in the scientific literature, a lot of unsupervised embedding algorithms exist, such as Laplacian methods. We refer those of you who are interested in exploring those methods to look at the paper Machine Learning on Graphs: A Model and Comprehensive Taxonomy, available at https://arxiv.org/pdf/2005.03675.pdf.

We will continue our description of the unsupervised graph embedding method in the next sections. We will describe more complex graph embedding algorithms based on autoencoders.

Autoencoders are an extremely powerful tool that can effectively help data scientists to deal with high-dimensional datasets. Although first presented around 30 years ago, in recent years, autoencoders have become more and more widespread in conjunction with the general rise of neural network-based algorithms. Besides allowing us to compact sparse representations, they can also be at the base of generative models, representing the first inception of the famous Generative Adversarial Network (GAN), which is, using the words of Geoffrey Hinton:

“The most interesting idea in the last 10 years in machine learning”

Indeed, Generative AI has become very popular in recent years, thanks to the astonishing results provided by generative models, especially in image generation (such as DALL-E) and text generation (such as ChatGPT).

An autoencoder is a neural network where the inputs and outputs are basically the same, but that is characterized by a small number of units in the hidden layer. Loosely described, it is a neural network that is trained to reconstruct its inputs using a significantly lower number of variables and/or degree of freedom.

Since an autoencoder does not need a labeled dataset, it can be seen as an example of unsupervised learning and a dimensionality-reduction technique. However, different from other techniques such as Principal Component Analysis (PCA) and matrix factorization, which we discussed in the previous section, autoencoders can learn non-linear transformation thanks to the non-linear activation functions of their neurons:

Figure 4.14: Diagram of the autoencoder structure

Figure 4.14: Diagram of the autoencoder structure

Figure 4.14 shows a simple example of an autoencoder. You can see how the autoencoder can generally be seen as composed of two parts:

  • An encoder network that processes the input through one or more units and maps it into an encoded representation that reduces the dimension of the inputs (under-complete autoencoders) and/or constrains its sparsity (over-complete regularized autoencoders)
  • A decoder network that reconstructs the input signal from the encoded representation of the middle layer

The encoder-decoder structure is then trained to minimize the ability of the full network to reconstruct the input. In order to completely specify an autoencoder, we need a loss function. The error between the inputs and the outputs can be computed using different metrics, and indeed the choice of the correct form for the “reconstruction” error is a critical point when building an autoencoder. Some common choices for the loss functions that measure the reconstruction error are mean square error, mean absolute error, cross-entropy, and KL divergence.

In the following sections, we will show you how to build an autoencoder, starting with some basic concepts, and then apply those concepts to graph structures.

Let’s start by implementing an autoencoder in its simplest form, that is, a simple feed-forward network trained to reconstruct its input (notice in autoencoders the image label is not used; we only aim to compress and decompress the input). We’ll apply this to the Fashion-MNIST dataset already presented in Chapter 3, Neural Networks and Graphs.

First, let’s load the dataset. We will be using the Keras library for our example:

from tensorflow.keras.datasets import fashion_mnist
(x_train, y_train), (x_test, y_test) = fashion_mnist.load_data()

And let’s rescale the inputs:

x_train = x_train.astype('float32') / 255.
x_test = x_test.astype('float32') / 255.

Now that we have imported the inputs, we can build our autoencoder network by creating the encoder and the decoder. We will be doing this using the Keras functional API, which provides more generality and flexibility compared to the so-called Sequential API. We start by defining the encoder network:

from tensorflow.keras.layers import Conv2D, Dropout, MaxPooling2D, UpSampling2D, Input
input_img = Input(shape=(28, 28, 1))
x = Conv2D(16, (3, 3), activation='relu', padding='same')(input_img)
x = MaxPooling2D((2, 2), padding='same')(x)
x = Conv2D(8, (3, 3), activation='relu', padding='same')(x)
x = MaxPooling2D((2, 2), padding='same')(x)
x = Conv2D(8, (3, 3), activation='relu', padding='same')(x)
encoded = MaxPooling2D((2, 2), padding='same')(x)

Our network is composed of a stack of three levels of the same pattern composed of the same two-layer building block:

  • Conv2D, a two-dimensional convolutional kernel that is applied to the input and effectively corresponds to having weights shared across all the input neurons. After applying the convolutional kernel, the output is transformed using the ReLU activation function. This structure is replicated for n hidden manifolds, with n being 16 in the first stacked layer and 8 in the second and third stacked layers.
  • MaxPooling2D, which down-samples the inputs by taking the maximum value over the specified window (2x2 in this case).

Using the Keras API, we can also have an overview of how the layers transformed the inputs using the Model class, which converts the tensors into a user-friendly model ready to be used and explored:

Model(input_img, encoded).summary()

This provides a summary of the encoder network:

Model: "model_1"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
input_1 (InputLayer) [(None, 28, 28, 1)] 0
_________________________________________________________________
conv2d (Conv2D) (None, 28, 28, 16) 160
_________________________________________________________________
max_pooling2d (MaxPooling2D) (None, 14, 14, 16) 0
_________________________________________________________________
conv2d_1 (Conv2D) (None, 14, 14, 8) 1160
_________________________________________________________________
max_pooling2d_1 (MaxPooling2 (None, 7, 7, 8) 0
_________________________________________________________________
conv2d_2 (Conv2D) (None, 7, 7, 8) 584
_________________________________________________________________
max_pooling2d_2 (MaxPooling2 (None, 4, 4, 8) 0
=================================================================
Total params: 1,904
Trainable params: 1,904
Non-trainable params: 0
_________________________________________________________________

As can be seen, at the end of the encoding phase, we have a (4, 4, 8) tensor, which is more than six times smaller than our original initial inputs (28x28). We can now build the decoder network. Note that the encoder and decoder do not need to have the same structure and/or shared weights:

x = Conv2D(8, (3, 3), activation='relu', padding='same')(encoded)
x = UpSampling2D((2, 2))(x)
x = Conv2D(8, (3, 3), activation='relu', padding='same')(x)
x = UpSampling2D((2, 2))(x)
x = Conv2D(16, (3, 3), activation='relu')(x)
x = UpSampling2D((2, 2))(x)
decoded = Conv2D(1, (3, 3), activation='sigmoid', padding='same')(x)

In this case, the decoder network resembles the encoder structure where the down-sampling of the input achieved using the MaxPooling2D layer has been replaced by the UpSampling2D layer, which basically repeats the input over a specified window (2x2 in this case, effectively doubling the tensor in each direction).

We have now fully defined the network structure with the encoder and decoder layers. In order to completely specify our autoencoder, we also need to specify a loss function. Moreover, to build the computational graph, Keras also needs to know which algorithms should be used in order to optimize the network weights. Both are provided to Keras when compiling the model:

autoencoder = Model(input_img, decoded)
autoencoder.compile(optimizer='adam', loss='binary_crossentropy')

We can now finally train our autoencoder. Keras Model classes provide APIs that are similar to scikit-learn, with a fit method to be used to train the neural network. Note that, owing to the nature of the autoencoder, we are using the same information as the input and output of our network:

autoencoder.fit(x_train, x_train,
epochs=50,
batch_size=128,
shuffle=True,
validation_data=(x_test, x_test))

Once the training is finished, we can examine the ability of the network to reconstruct the inputs by comparing input images with their reconstructed version, which can be easily computed using the predict method of the Keras Model class as follows:

decoded_imgs = autoencoder.predict(x_test)

In Figure 4.15, we show the reconstructed images. As you can see, the network is quite good at reconstructing unseen images, especially when considering the large-scale features. Details might have been lost in the compression (see, for instance, the logos on the T-shirts), but the overall relevant information has indeed been captured by our network:

Figure 4.15: Examples of the reconstruction done on the test set by the trained autoencoder

Figure 4.15: Examples of the reconstruction done on the test set by the trained autoencoder

It can also be very interesting to represent the encoded version of the images in a two-dimensional plane using T-SNE:

from tensorflow.keras.layers import Flatten
embed_layer = Flatten()(encoded)
embeddings = Model(input_img, embed_layer).predict(x_test)
tsne = TSNE(n_components=2)
emb2d = tsne.fit_transform(embeddings)
x, y = np.squeeze(emb2d[:, 0]), np.squeeze(emb2d[:, 1])

The coordinates provided by T-SNE are shown in Figure 4.16, colored by the class the sample belongs to. The clustering of the different clothing can clearly be seen, particularly for some classes that are very well separated from the rest:

Figure 4.16: T-SNE transformation of the embeddings extracted from the test set, colored by the class that the sample belongs to

Figure 4.16: T-SNE transformation of the embeddings extracted from the test set, colored by the class that the sample belongs to

Autoencoders are, however, rather prone to overfitting, as they tend to re-create exactly the images of the training and not generalize well. In the following subsection, we will see how overfitting can be prevented in order to build more robust and reliable dense representations.

Besides allowing us to compress a sparse representation into a denser vector, autoencoders are also widely used to process a signal in order to filter out noise and extract only a relevant (characteristic) signal. This can be very useful in many applications, especially when identifying anomalies and outliers.

Denoising autoencoders are a small variation of what has already been implemented. As described in the previous section, basic autoencoders are trained using the same image as input and output. Denoising autoencoders corrupt the input using some noise of various intensity, while keeping the same noise-free target. This could be achieved by simply adding some Gaussian noise to the inputs:

noise_factor = 0.1
x_train_noisy = x_train + noise_factor * np.random.normal(loc=0.0, scale=1.0, size=x_train.shape)
x_test_noisy = x_test + noise_factor * np.random.normal(loc=0.0, scale=1.0, size=x_test.shape)
x_train_noisy = np.clip(x_train_noisy, 0., 1.)
x_test_noisy = np.clip(x_test_noisy, 0., 1.)

The network can then be trained using the corrupted input, while for the output, the noise-free image is used:

noisy_autoencoder.fit(x_train_noisy, x_train,
epochs=50,
batch_size=128,
shuffle=True,
validation_data=(x_test_noisy, x_test))

Such an approach is generally valid when datasets are large and when the risk of overfitting the noise is rather limited. When datasets are smaller, an alternative to avoid the network “learning” the noise as well (thus learning the mapping between a static noisy image to its noise-free version) is to add training stochastic noise using a GaussianNoise layer.

Note that in this way, the noise may change between epochs and prevent the network from learning a static corruption superimposed onto our training set. In order to do so, we change the first layers of our network in the following way:

input_img = Input(shape=(28, 28, 1))
noisy_input = GaussianNoise(0.1)(input_img)
x = Conv2D(16, (3, 3), activation='relu', padding='same')(noisy_input)

The difference is that instead of having statically corrupted samples (that do not change in time), the noisy inputs now keep changing between epochs, thus avoiding the network learning the noise as well.

The GaussianNoise layer is an example of a regularization layer, that is, a layer that helps reduce the overfitting of a neural network by inserting a random part in the network. GaussianNoise layers make models more robust and able to generalize better, avoiding autoencoders learning the identity function.

Another common example of a regularization layer is the dropout layers that effectively set to 0 some of the inputs (at random with a probability, ) and rescale the other inputs by a factor in order to (statistically) keep the sum over all the units constant, with and without dropout.

Dropout corresponds to randomly killing some of the connections between layers in order to reduce output dependency to specific neurons. Always keep in mind that regularization layers are only active during training, while at test time they simply correspond to identity layers.

In Figure 4.17, we compare the network reconstruction of a noisy input (input) for the previous unregularized trained network and the network with a GaussianNoise layer. As can be seen (compare, for instance, the images of trousers), the model with regularization tends to develop stronger robustness and reconstructs the noise-free outputs:

Figure 4.17: Comparison with reconstruction for noisy samples. Top row: noisy input; middle row: reconstructed output using a vanilla autoencoder; bottom row: reconstructed output using a denoising autoencoder

Figure 4.17: Comparison with reconstruction for noisy samples. Top row: noisy input; middle row: reconstructed output using a vanilla autoencoder; bottom row: reconstructed output using a denoising autoencoder

Regularization layers are often used when dealing with deep neural networks that tend to overfit and are able to learn identity functions for autoencoders. Often, dropout or GaussianNoise layers are introduced, repeating a similar pattern composed of regularization and learnable layers that we usually refer to as stacked denoising layers.

Once the basic concepts of autoencoders are understood, we can turn to apply this framework to graph structures. If, on one hand, the network structure, decomposed into an encoder-decoder structure with a low-dimensional representation in between, still applies, the definition of the loss function to be optimized needs a bit of caution when dealing with networks. First, we need to adapt the reconstruction error to a meaningful formulation that can adapt to the peculiarities of graph structures.

When applying autoencoders to graph structures, the input and output of the network should be a graph representation, for instance, the adjacency matrix. The reconstruction loss could then be defined as the Frobenius norm of the difference between the input and output matrices. However, when applying autoencoders to such graph structures and adjacency matrices, two critical issues arise:

  • Whereas the presence of links indicates a relation or similarity between two vertices, their absence does not generally indicate a dissimilarity between vertices.
  • The adjacency matrix is extremely sparse and therefore the model will naturally tend to predict a 0 rather than a positive value.

To address such peculiarities of graph structures, when defining the reconstruction loss, we need to penalize more errors for the non-zero elements than for zero elements. This can be done using the following loss function:

Here, represents the reconstructed adjacency matrix produced by the autoencoder, and represents the original adjacency matrix for node i (adjacency vector). is the Hadamard element-wise product, where if there is an edge between nodes i and j, and 0 otherwise. The preceding loss guarantees that vertices that share a neighborhood (that is, their adjacency vectors are similar) will also be close in the embedding space. Thus, the preceding formulation will naturally preserve second-order proximity for the reconstructed graph.

On the other hand, you can also promote first-order proximity in the reconstructed graph, thus enforcing connected nodes to be close in the embedding space. This condition can be enforced by using the following loss:

Here, yi and yj are the two representations of nodes i and j in the embedding space. The term represents the strength of the connection between nodes i and j. Typically, is derived from the adjacency matrix or other similarity measures, where a larger indicates a stronger or more important connection between the two nodes. This loss function forces neighboring nodes to be close in the embedding space. In fact, if two nodes are tightly connected, Sij will be large. As a consequence, their difference in the embedding space, , should be limited (indicating the two nodes are close in the embedding space) to keep the loss function small. The two losses can also be combined into a single loss function, where, in order to prevent overfitting, a regularization loss can be added that is proportional to the norm of the weight coefficients:

In the preceding equation, W represents all the weights used across the network. The preceding formulation was proposed in 2016 by Wang et al., and it is now known as Structural Deep Network Embedding (SDNE).

Although the preceding loss could also be directly implemented with TensorFlow and Keras, you can already find this network integrated in the GEM package we referred to previously. As before, extracting the node embedding can be done similarly in a few lines of code, as follows:

G=nx.karate_club_graph()
sdne=SDNE(d=2, beta=5, alpha=1e-5, nu1=1e-6, nu2=1e-6,
K=3,n_units=[50, 15,], rho=0.3, n_iter=10,
xeta=0.01,n_batch=100,
modelfile=['enc_model.json','dec_model.json'],
weightfile=['enc_weights.hdf5','dec_weights.hdf5'])
sdne.learn_embedding(G)
embeddings = m1.get_embedding()

Although very powerful, these graph autoencoders encounter some issues when dealing with large graphs. For these cases, the input of our autoencoder is one row of the adjacency matrix that has as many elements as the nodes in the network. In large networks, this size can easily be of the order of millions or tens of millions.

In the next section, we describe a different strategy for encoding the network information that in some cases may iteratively aggregate embeddings only over local neighborhoods, making it scalable to large graphs.

We introduced in Chapter 3, Neural Networks and Graphs, the concept of GNNs, a deep learning method that works on graph-structured data. It is now time to go into the details of how GNNs can be used for unsupervised learning. Similar to other techniques seen in this chapter (e.g., matrix factorization), GNNs will also allow us to obtain embeddings of our graph elements (nodes, edges, and graphs). However, it is worth noting that different from shallow embeddings, some of the GNN techniques are inductive, and therefore allow the embeddings to also be applied to unseen data.

As shown in the previous chapter, Convolutional Neural Networks (CNNs) are widely used in images to extract multi-scale localized spatial features that are exploited by deeper layers to construct more complex and highly expressive representations.

In recent years, it has been observed that concepts such as multi-layer and locality are also useful for processing graph-structured data. However, graphs are defined over a non-Euclidean space.

The original formulation of GNNs was proposed by Scarselli et al., back in 2009. It relies on the fact that each node can be described by its features and its neighborhood. Information coming from the neighborhood (which represents the concept of locality in the graph domain) can be aggregated and used to compute more complex and high-level features.

At the beginning, each node, vi, is associated with a state. Let’s start with a random embedding, (ignoring node attributes for simplicity). At each iteration of the algorithm, nodes accumulate input from their neighbors using a simple neural network layer:

Here, and are trainable parameters (where d is the dimension of the embedding), is a non-linear function, and t represents the tth iteration of the algorithm. The equation is applied recursively until a particular objective is reached. Note that, at each iteration, the previous state (computed at the previous iteration) of neighbors is exploited in order to compute the new state, similar to recurrent neural networks.

Starting from this first idea, several attempts have been made in recent years to re-address the problem of learning from graph data. In particular, variants of the previously described GNN have been proposed, with the aim of improving its representation learning capability. Some of them are specifically designed to process specific types of graphs, such as direct, indirect, weighted, unweighted, static, and dynamic.

Several modifications have been proposed for the propagation step (convolution, gate mechanisms, attention mechanisms, and skip connections, among others), with the aim of improving the representation at different levels. Also, different training methods have been proposed to improve learning.

There are essentially two types of convolutional operations for graph data, namely spectral approaches and non-spectral (spatial) approaches. The first, as the name suggests, defines convolution in the spectral domain (that is, decomposing graphs in a combination of simpler elements). Spatial convolution, on the other hand, formulates the convolution as aggregating feature information from neighbors.

Spectral approaches are related to spectral graph theory, the study of the characteristics of a graph in relation to the characteristic polynomial, eigenvalues, and eigenvectors of the matrices associated with the graph. The convolution operation is defined as the multiplication of a signal (node features) by a kernel. In more detail, it is defined in the Fourier domain by determining the eigendecomposition of the graph Laplacian (think about the graph Laplacian as an adjacency matrix normalized in a special way).

While this definition of spectral convolution has a strong mathematical foundation, the operation is computationally expensive. For this reason, several works have been done to approximate it in an efficient way. ChebNet by Defferrard et al., for instance, is one of the first seminal works on spectral graph convolution. Here, the operation is approximated by using the concept of the Chebyshev polynomial of order K (a special kind of polynomial used to efficiently approximate functions).

Here, K is a very useful parameter because it determines the locality of the filter. Intuitively, for K = 1, only the node features are fed into the network. With K = 2, we average over two-hop neighbors (neighbors of neighbors) and so on.

Let be the matrix of node features, where N is the number of nodes. In classical neural network processing, this signal would be composed of layers of the following form:

Here, is the layer weights and represents some non-linear activation function. The drawback of this operation is that it processes each node signal independently without taking into account connections between nodes. To overcome this limitation, a simple (yet effective) modification can be done, as follows:

By introducing the adjacency matrix, , a new linear combination between each node and its corresponding neighbors is added. This way, the information depends only on the neighborhood and parameters are applied to all the nodes, simultaneously.

It is worth noting that this operation can be repeated in sequence several times, thus creating a deep network. At each layer, the node descriptors, X, will be replaced with the output of the previous layer, Hl-1, feeding the computation of Hl.

The preceding presented equation, however, has some limitations and cannot be applied as it stands. The first limitation is that by multiplying by A, we consider all the neighbors of the node but not the node itself. This problem can be easily overcome by adding self-loops in the graph, that is, adding the identity matrix.

The second limitation is related to the adjacency matrix itself. Since it is typically not normalized, we will observe large values in the feature representation of high-degree nodes and small values in the feature representation of low-degree nodes. This will lead to several problems during training since optimization algorithms are often sensitive to feature scale. Several methods have been proposed for normalizing A.

In Kipf and Welling, 2017 (one of the well-known GCN models), for example, the normalization is performed by multiplying A by the diagonal node degree matrix D, such that all the rows sum to 1: D-1A. More specifically, they used symmetric normalization (D-1/2AD-1/2), such that the proposed propagation rule becomes as follows:

Here, is the diagonal node degree matrix of .

In the following example, we will create a GCN as defined in Kipf and Welling and apply this propagation rule for embedding a simple graph:

  1. To begin, it is necessary to import all the Python modules. We will use networkx to load the barbell graph:
    import networkx as nx
    import numpy as np
    G = nx.barbell_graph(m1=10,m2=4)
  2. To implement the GC propagation rule, we need an adjacency matrix representing G. Since this network does not have node features, we will use the identity matrix as the node descriptor:
    A = nx.to_numpy_matrix(G)
    I = np.eye(G.number_of_nodes())
  3. We now add the self-loop and prepare the diagonal node degree matrix:
    from scipy.linalg import sqrtm
    A_hat = A + I
    D_hat = np.array(np.sum(A_hat, axis=0))[0]
    D_hat = np.array(np.diag(D_hat))
    D_hat = np.linalg.inv(sqrtm(D_hat))
    A_norm = D_hat @ A_hat @ D_hat
  4. Our GCN will be composed of two layers. Let’s define the layers’ weights and the propagation rule. Layer weights, W, will be initialized using Glorot uniform initialization (even if other initialization methods can be also used, for example, by sampling from a Gaussian or uniform distribution):
    def glorot_init(nin, nout):
    sd = np.sqrt(6.0 / (nin + nout))
    return np.random.uniform(-sd, sd, size=(nin, nout))
    class GCNLayer():
    def __init__(self, n_inputs, n_outputs):
    self.n_inputs = n_inputs
    self.n_outputs = n_outputs
    self.W = glorot_init(self.n_outputs, self.n_inputs)
    self.activation = np.tanh
    def forward(self, A, X):
    self._X = (A @ X).T
    H = self.W @ self._X
    H = self.activation(H)
    return H.T # (n_outputs, N)
  5. Finally, let’s create our network and compute the forward pass, that is, propagate the signal through the network:
    gcn1 = GCNLayer(G.number_of_nodes(), 8)
    gcn2 = GCNLayer(8, 4)
    gcn3 = GCNLayer(4, 2)
    H1 = gcn1.forward(A_norm, I)
    H2 = gcn2.forward(A_norm, H1)
    H3 = gcn3.forward(A_norm, H2)

H3 now contains the embedding computed using the GCN propagation rule. Note that we chose 2 as the number of outputs, meaning that the embedding is bi-dimensional and can be easily visualized. In Figure 4.18, you can see the output:

Figure 4.18: Application of the graph convolutional layer to a graph (left) to generate the embedding vector of its nodes (right)

Figure 4.18: Application of the graph convolutional layer to a graph (left) to generate the embedding vector of its nodes (right)

You can observe the presence of two quite well-separated communities. This is a nice result, considering that we have not trained the network yet!

Spectral graph convolution methods have achieved noteworthy results in many domains. However, they present some drawbacks. Consider, for example, a very big graph with billions of nodes: a spectral approach requires the graph to be processed simultaneously, which can be impractical from a computational point of view.

Furthermore, spectral convolution often assumes a fixed graph, leading to poor generalization capabilities on new, unseen samples. To overcome these issues, spatial graph convolution represents an interesting alternative.

Spatial graph convolutional networks perform the operations directly on the graph by aggregating information from spatially close neighbors. Spatial convolution has many advantages: weights can be easily shared across different locations of the graph, leading to a good generalization capability on different graphs. Furthermore, the computation can be done by considering subsets of nodes instead of the entire graph, potentially improving computational efficiency.

GraphSAGE is one of the algorithms that implement spatial convolution. One of its main characteristics is its ability to scale over various types of networks. We can think of GraphSAGE as composed of three steps:

  1. Neighborhood sampling: For each node in a graph, the first step is to find its k-neighborhood, where k is defined by the user for determining how many hops to consider (neighbors of neighbors).
  2. Aggregation: The second step is to aggregate, for each node, the node features describing the respective neighborhood. Various types of aggregation can be performed, including average, pooling (for example, taking the best feature according to certain criteria), or an even more complicated operation, such as using recurrent units (such as LSTM).
  3. Prediction: Each node is equipped with a simple neural network that learns how to perform predictions based on the aggregated features from the neighbors.

GraphSAGE is often used in supervised learning tasks, as explored in Chapter 5, Supervised Graph Learning. However, it is also suitable for unsupervised learning. In unsupervised settings, GraphSAGE employs a loss function based on node similarity, which is derived from random walks. Specifically, as outlined in the original paper by Hamilton, Ying, and Leskovec (2018), fixed-length random walks are used to identify pairs of nodes that are likely to share similar representations. The learned embeddings are optimized to ensure that nodes close in these random-walk neighborhoods have similar embeddings, using a loss function that measures similarity (a dot product, for example) between these embeddings. This approach enables GraphSAGE to learn effective node embeddings even without explicit labels.

In practice, GNNs have been implemented in many machine learning and deep learning frameworks, such as StellarGraph, PyG, and DGL. For the next example, we will be using StellarGraph. A similar example using other frameworks can be found in the GitHub repository. We will learn about embedding vectors in an unsupervised manner, without a target variable. The method is inspired by Bai et al., 2019 and is based on the simultaneous embedding of pairs of graphs. This embedding should match a ground-truth distance between graphs:

  1. First, let’s load the required Python modules:
    import numpy as np
    import stellargraph as sg
    from stellargraph.mapper import FullBatchNodeGenerator
    from stellargraph.layer import GCN
    import tensorflow as tf
    from tensorflow.keras import layers, optimizers, losses, metrics, Model
  2. We will be using the PROTEINS dataset for this example, which is available in StellarGraph and consists of 1,114 graphs with 39 nodes and 73 edges on average for each graph. Each node is described by four attributes and belongs to one of two classes:
    dataset = sg.datasets.PROTEINS()
    graphs, graph_labels = dataset.load()
  3. The next step is to create the model. It will be composed of two GC layers with 64 and 32 output dimensions followed by ReLU activation, respectively. The output will be computed as the Euclidean distance of the two embeddings:
    generator = sg.mapper.PaddedGraphGenerator(graphs)
    # define a GCN model containing 2 layers of size 64 and 32,
    # respectively.ReLU activation function is used to add
    # non-linearity between layers
    gc_model = sg.layer.GCNSupervisedGraphClassification(
    [64, 32], ["relu", "relu"], generator, pool_all_layers=True)
    # retrieve the input and the output tensor of the GC layer
    # such that they can be connected to the next layer
    inp1, out1 = gc_model.in_out_tensors()
    inp2, out2 = gc_model.in_out_tensors()
    vec_distance = tf.norm(out1 - out2, axis=1)
    # create the model. It is also useful to create a specular model in
    # order to easily retrieve the embeddings
    pair_model = Model(inp1 + inp2, vec_distance)
    embedding_model = Model(inp1, out1)
  4. It is now time to prepare the dataset for training. To each pair of input graphs, we will assign a similarity score. Notice that any notion of graph similarity can be used in this case, including graph edit distances. For simplicity, we will be using the distance between the spectrum of the Laplacian of the graphs:
    def graph_distance(graph1, graph2):
    spec1 = nx.laplacian_spectrum(graph1.to_networkx(feature_attr=None))
    spec2 = nx.laplacian_spectrum(graph2.to_networkx(feature_attr=None))
    k = min(len(spec1), len(spec2))
    return np.linalg.norm(spec1[:k] - spec2[:k])
    graph_idx = np.random.RandomState(0).randint(len(graphs), size=(100, 2))
    targets = [graph_distance(graphs[left], graphs[right]) for left, right in graph_idx]
    train_gen = generator.flow(graph_idx, batch_size=10, targets=targets)
  5. Finally, let’s compile and train the model. We will be using the Adaptive Moment Estimation (Adam) optimizer with the learning rate parameter set to 1e-2. The loss function we will be using is defined as the minimum squared error between the prediction and the ground-truth distance computed as previously. The model will be trained for 500 epochs:
    pair_model.compile(optimizers.Adam(1e-2), loss="mse")
    pair_model.fit(train_gen, epochs=500, verbose=0)

After training, we are now ready to inspect and visualize the learned representation. Since the output is 32-dimensional, we need a way to qualitatively evaluate the embeddings, for example, by plotting them in a bi-dimensional space. We will use T-SNE for this purpose:

# retrieve the embeddings
embeddings = embedding_model.predict(generator.flow(graphs))
# TSNE is used for dimensionality reduction
from sklearn.manifold import TSNE
tsne = TSNE(2)
two_d = tsne.fit_transform(embeddings)

Let’s plot the embeddings. In the plot, each point (embedded graph) is colored according to the corresponding label (blue=0, red=1). The results are visible in Figure 4.19:

Figure 4.19: The PROTEINS dataset embedding using GCNs. Axes represent the first two latent directions of the embedding algorithm.

Figure 4.19: The PROTEINS dataset embedding using GCNs. Axes represent the first two latent directions of the embedding algorithm.

As you can see, the obtained embeddings seem not to be related to the actual label distribution. Since this is an unsupervised method, this may happen because the network is learning patterns it thinks are useful. However, this is not necessarily a bad thing! By studying these “new” clusters, we may discover something new or unexpected in our data.

Moreover, this is just one of the possible methods for learning embeddings for graphs. More advanced solutions can be experimented with to better fit the problem of interest.

In this chapter, we have learned how unsupervised machine learning can be effectively applied to graphs to solve real problems, such as node and graph representation learning. In particular, we first analyzed shallow embedding methods, a set of algorithms that are able to learn and return only the embedding values for the learned input data.

We then learned how autoencoder algorithms can be used to encode the input by preserving important information in a lower-dimensional space. We have also seen how this idea can be adapted to graphs, by learning about embeddings that allow us to reconstruct the pair-wise node/graph similarity. Finally, we introduced the main concepts behind GNNs. We have seen how well-known concepts, such as convolution, can be applied to graphs.

In the next chapter, we will revise these concepts in a supervised setting. There, a target label is provided and the objective is to learn a mapping between the input and the output.