Skip to content
ImagineWorld

Graph Deep Learning in Practice

node_idnode-book_applied-deep-learning-on-graphs_chapter-07-graph-deep-learning-in-practice
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num7
chapter_titleGraph Deep Learning in Practice
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 7 — Graph Deep Learning in Practice

Section titled “Chapter 7 — Graph Deep Learning in Practice”

Having explored the theoretical aspects of graph deep learning in the previous chapters, now is a good time to get our hands dirty by diving into its practical applications.

Social networks have become an integral part of our digital lives, generating vast amounts of data that can provide valuable insights into human behavior, relationships, and social dynamics. Graph deep learning offers powerful tools to analyze and extract meaningful information from these complex networks. In this chapter, we will explore practical applications of graph deep learning techniques to social network analysis using PyTorch Geometric (PyG).

Here, we will focus on a hypothetical dataset representing a social network of university students. This example will demonstrate how graph-based machine learning can be applied to real-world scenarios, such as predicting user interests, recommending new connections, and identifying community structures.

Our dataset consists of the following elements:

  • Nodes: Each node represents a student in the university.
  • Edges: Edges between nodes represent friendships or connections between students.
  • Node features: Each student (node) has associated features, including the following:
    • Age
    • Year of study
    • Academic major (encoded as a one-hot vector)
  • Node labels: Each student is assigned to one of five interest groups, which we’ll use for our node classification task.

Throughout this chapter, we will tackle two main tasks:

  • Node classification: We’ll predict student interests based on their features and connections within the network. This task demonstrates how graph neural networks (GNNs) can leverage both node attributes and network structure to make predictions about individual nodes.
  • Link prediction: We’ll develop a model to recommend new friendships by predicting potential edges in the graph. This showcases how graph deep learning can be used for recommendation systems and network growth prediction.

We’ll implement these tasks using state-of-the-art GNN architectures. Additionally, we’ll visualize our results to gain intuitive insights into the network structure and our model’s performance.

By the end of this chapter, you’ll have a practical understanding of how to apply graph deep learning techniques to social network data, interpret the results, and adapt these methods to your own projects. While we use a synthetic dataset for demonstration, the techniques covered here can be readily applied to real-world social network data.

Let’s begin our journey into the practical world of graph deep learning for social network analysis! We will be exploring the following topics at length:

  • Setting up the environment
  • Creating the graph dataset
  • Node classification – predicting student interests
  • Link prediction – recommending new friendships

Before we dive into the implementation of our graph deep learning models, it’s crucial to set up our development environment with the necessary libraries and tools. In this section, we’ll cover the essential imports and explain their roles in our project.

First, let’s start by importing the required libraries:

import torch
import torch_geometric
from torch_geometric.data import Data
from torch_geometric.nn import GCNConv, GAE
from torch_geometric.utils import train_test_split_edges
from torch_geometric.transforms import RandomLinkSplit
from sklearn.manifold import TSNE
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
import networkx as nx
from sklearn.metrics import roc_auc_score

Let’s break down these imports and their purposes:

  • torch: The core PyTorch library used for tensor operations and building neural networks
  • torch_geometric: PyG, an extension library to PyTorch for deep learning on graphs and other irregular structures
  • torch_geometric.data.Data: A class used to create graph data objects in PyG that hold node features, edge indices, and labels
  • torch_geometric.nn.GCNConv: The graph convolutional network (GCN) layer, used for node classification
  • torch_geometric.nn.GAE: The graph autoencoder (GAE), used for link prediction
  • torch_geometric.utils.train_test_split_edges: A utility function that helps split the graph data for link prediction tasks
  • torch_geometric.transforms.RandomLinkSplit: A transform used to prepare the data for link prediction by splitting it into train, validation, and test sets
  • sklearn.manifold.TSNE: t-Distributed Stochastic Neighbor Embedding (t-SNE), used for dimensionality reduction when visualizing node embeddings
  • sklearn.cluster.KMeans: Used for clustering node embeddings to identify social groups
  • matplotlib.pyplot: A library used for creating visualizations of graphs and results
  • networkx: A library providing additional tools for working with graphs, used for some visualizations

Make sure you have all these libraries installed in your Python environment. You can install them using pip:

Terminal window
pip install torch torch_geometric scikit-learn matplotlib networkx

Note that the installation of PyG (torch_geometric) might require additional steps depending on your system and CUDA version. Please refer to the official documentation for detailed installation instructions: https://pytorch-geometric.readthedocs.io/en/latest/.

With these libraries imported, we’re now ready to start working with our social network data and implementing our graph deep learning models.

The next step is to create a synthetic social network dataset to demonstrate our graph deep learning techniques. While real-world data would be ideal, using synthetic data allows us to focus on the implementation and understanding of the algorithms without the complexities of data acquisition and preprocessing.

Here, we will create a social network dataset representing university students. The complete code can be found at https://github.com/PacktPublishing/Applied-Deep-Learning-on-Graphs.

Let’s break down this code and explain each part.

  1. We set a random seed for reproducibility:

    torch.manual_seed(42)

    This ensures that we generate the same “random” data each time we run the code.

  2. We define our dataset parameters:

    num_nodes = 1000
    num_features = 10
    num_classes = 5
    • num_nodes is the number of students (nodes) in our network.
    • num_features is the number of features for each student. We’re using 10 features to represent age, year of study, and 8 possible academic majors.
    • num_classes is the number of different interest groups, which will be our target for node classification.
  3. We create node features (x) using torch.randn():

    x = torch.randn((num_nodes, num_features))

    This generates a tensor of size (num_nodes, num_features) filled with random values from a standard normal distribution. In a real dataset, these features would be actual attributes of the students.

  4. We create edges (edge_index) using torch.randint():

    edge_index = torch.randint(0, num_nodes, (2, 5000))

    This generates 5,000 random edges between nodes. The edge_index tensor has the shape (2, 5000), where each column represents an edge with [``source_node, target_node].

  5. We create node labels (y) using torch.randint():

    y = torch.randint(0, num_classes, (num_nodes,))

    This assigns each node (student) to one of the five interest groups randomly.

  6. We create a PyG Data object, which efficiently holds our graph data. We pass in our node features (x), edge indices (edge_index), and node labels (y):

    data = Data(x=x, edge_index=edge_index, y=y)
    data.num_classes = num_classes
  7. Finally, we print some information about our dataset to verify its structure:

    print(f"Number of nodes: {data.num_nodes}")
    print(f"Number of edges: {data.num_edges}")
    print(f"Number of node features: {data.num_node_features}")
    print(f"Number of classes: {data.num_classes}")

This synthetic dataset now represents a social network:

  • Each node is a student with 10 features (representing attributes such as age, year, and major).
  • Edges represent friendships between students.
  • Each student belongs to one of five interest groups.

The output of the code will be as follows:

Number of nodes: 1000
Number of edges: 5000
Number of node features: 10
Number of classes: 5

In a real-world scenario, you would typically load your data from files or databases and preprocess it to fit this structure. The Data object we’ve created is now ready to be used with PyG’s GNN models.

In the next sections, we’ll use this dataset to perform node classification, link prediction, and graph clustering tasks.

Node classification – predicting student interests

Section titled “Node classification – predicting student interests”

In this section, we’ll implement a GCN to predict student interests based on their features and connections in the social network. This task demonstrates how GNNs can leverage both node attributes and network structure to make predictions about individual nodes.

Let’s start by defining our GCN model:

class GCN(torch.nn.Module):
def __init__(self, in_channels, hidden_channels, out_channels):
super().__init__()
self.conv1 = GCNConv(in_channels, hidden_channels)
self.conv2 = GCNConv(hidden_channels, out_channels)
def forward(self, x, edge_index):
x = self.conv1(x, edge_index).relu()
x = self.conv2(x, edge_index)
return x
# Initialize the model
model = GCN(in_channels=num_features,
hidden_channels=16,
out_channels=num_classes)

As you can see, our GCN model consists of two graph convolutional layers. The first layer takes the input features and produces hidden representations, while the second layer produces the final class predictions.

Now, let’s train the model. You can view the complete code at https://github.com/PacktPublishing/Applied-Deep-Learning-on-Graphs. Let’s break down the training process here:

  1. We define an optimizer (Adam) and a loss function (CrossEntropyLoss) for training our model:

    optimizer = torch.optim.Adam(model.parameters(), lr=0.01)
    criterion = torch.nn.CrossEntropyLoss()
  2. The train() function performs one step of training:

    def train():
    model.train()
    optimizer.zero_grad()
    out = model(data.x, data.edge_index)
    loss = criterion(out, data.y)
    loss.backward()
    optimizer.step()
    return loss
    • It sets the model to training mode.
    • It computes the forward pass of the model.
    • It calculates the loss between predictions and true labels.
    • It performs backpropagation and updates the model parameters.
  3. The test() function evaluates the model’s performance:

    def test():
    model.eval()
    out = model(data.x, data.edge_index)
    pred = out.argmax(dim=1)
    correct = (pred == data.y).sum()
    acc = int(correct) / int(data.num_nodes)
    return acc
    • It sets the model to evaluation mode.
    • It computes the forward pass.
    • It calculates the accuracy of predictions.
  4. We train the model for 200 epochs, printing the loss and accuracy every 10 epochs:

    for epoch in range(200):
    loss = train()
    if epoch % 10 == 0:
    acc = test()
    print(f'Epoch: {epoch:03d}, Loss: {loss:.4f}, \\
    Accuracy: {acc:.4f}')
  5. Finally, we evaluate the model one last time to get the final accuracy:

    final_acc = test()
    print(f"Final Accuracy: {final_acc:.4f}")

To visualize how well our model is performing, let’s create a function to plot the predicted versus true interest groups:

def visualize_predictions(model, data):
model.eval()
out = model(data.x, data.edge_index)
pred = out.argmax(dim=1)
plt.figure(figsize=(10, 5))
plt.subplot(121)
plt.title("True Interests")
plt.scatter(
data.x[:, 0], data.x[:, 1], c=data.y, cmap='viridis')
plt.colorbar()
plt.subplot(122)
plt.title("Predicted Interests")
plt.scatter(
data.x[:, 0], data.x[:, 1], c=pred, cmap='viridis')
plt.colorbar()
plt.tight_layout()
plt.show()
visualize_predictions(model, data)

This function creates two scatter plots: one showing the true interest groups and another showing the predicted interest groups.

Figure 7.1: Model performance: true versus predicted interests

Figure 7.1: Model performance: true versus predicted interests

In Figure 7*.1*, each point represents a student, positioned based on their first two features. The visualization consists of two scatter plots labeled True Interests and Predicted Interests. Each point in these plots represents one of the students. The colors in both plots, ranging from purple (0.0) to yellow (4.0), indicate different interest groups. The left plot shows the actual or “true” interest groups of the students, while the right plot displays the model’s predictions of these interest groups. The similarity between the distributions conveys the effectiveness of graph learning techniques in such predictions.

In a real-world application, this node classification task could be used to predict student interests based on their profile information and social connections. This could be valuable for personalized content recommendations, targeted advertising, or improving student engagement in university activities.

Remember that while our synthetic dataset provides a clean example, real-world data often requires more preprocessing, handling of missing values, and careful consideration of privacy and ethical concerns when working with personal data.

Another aspect of graph learning is the task of link prediction. This comes up in a lot of real-world scenarios, especially ones where we are trying to predict certain connections.

Link prediction – recommending new friendships

Section titled “Link prediction – recommending new friendships”

In this section, we’ll implement a GAE for link prediction. This task aims to predict potential new connections in the network, which can be used to recommend new friendships among students.

First, let’s define our GAE model:

class LinkPredictor(torch.nn.Module):
def __init__(self, in_channels, hidden_channels):
super().__init__()
self.encoder = GCNConv(in_channels, hidden_channels)
def encode(self, x, edge_index):
return self.encoder(x, edge_index).relu()
def decode(self, z, edge_label_index):
return (
z[edge_label_index[0]] * z[edge_label_index[1]]
).sum(dim=-1)
def forward(self, x, edge_index, edge_label_index):
z = self.encode(x, edge_index)
return self.decode(z, edge_label_index)
# Initialize the model
model = LinkPredictor(in_channels=num_features, hidden_channels=64)

Our LinkPredictor model uses a GCN layer for encoding node features into embeddings, and a simple dot product operation for decoding (predicting links).

Now, let’s prepare our data for link prediction using the following code:

from torch_geometric.transforms import RandomLinkSplit
# Prepare data for link prediction
transform = RandomLinkSplit(
num_val=0.1, num_test=0.1, is_undirected=True,
add_negative_train_samples=False
)
train_data, val_data, test_data = transform(data)
# Define optimizer
optimizer = torch.optim.Adam(model.parameters(), lr=0.01)

The RandomLinkSplit transform splits our graph into training, validation, and test sets for link prediction. It removes some edges for validation and testing and generates negative samples (non-existent edges).

Now, let’s define our training and evaluation functions:

  1. Initialize the training process, prepare the optimizer, and encode the input data:

    def train_link_predictor():
    model.train()
    optimizer.zero_grad()
    z = model.encode(train_data.x, train_data.edge_index)
  2. Now, we define positive edges and generate negative edges for training:

    pos_edge_index = train_data.edge_index
    neg_edge_index = torch_geometric.utils.negative_sampling(
    edge_index=pos_edge_index,
    num_nodes=train_data.num_nodes,
    num_neg_samples=pos_edge_index.size(1),
    )
  3. Combine positive and negative edges and create corresponding labels:

    edge_label_index = torch.cat([
    pos_edge_index, neg_edge_index], dim=-1)
    edge_label = torch.cat([
    torch.ones(pos_edge_index.size(1)),
    torch.zeros(neg_edge_index.size(1))
    ], dim=0)
  4. The model makes predictions, calculates the loss, performs backpropagation, and updates the model parameters:

    out = model.decode(z, edge_label_index)
    loss = torch.nn.BCEWithLogitsLoss()(out, edge_label)
    loss.backward()
    optimizer.step()
    return loss
  5. This begins the testing function, setting the model to evaluation mode and making predictions without gradient calculation:

    def test_link_predictor(data):
    model.eval()
    with torch.no_grad():
    z = model.encode(data.x, data.edge_index)
    out = model.decode(z, data.edge_label_index)
  6. Finally, we convert the predictions to NumPy arrays and calculate the Area Under the Receiver Operating Characteristic Curve (ROC AUC) score to evaluate the model’s performance:

    y_true = data.edge_label.cpu().numpy()
    y_pred = out.cpu().numpy()
    return roc_auc_score(y_true, y_pred)

Now, let’s write the training and prediction modules:

  1. We train the model for 100 epochs, printing the loss and validation AUC every 10 epochs:

    for epoch in range(100):
    loss = train_link_predictor()
    if epoch % 10 == 0:

    The train_link_predictor() function encodes the node features, predicts links for both positive and negative samples, and computes the binary cross-entropy loss.

  2. The test_link_predictor() function evaluates the model’s performance using the AUC metric:

    val_auc = test_link_predictor(val_data)
    print(f'Epoch: {epoch:03d}, Loss: {loss:.4f}, \\
    Val AUC: {val_auc:.4f}')
  3. Finally, we evaluate the model on the test set to get the final AUC score:

    test_auc = test_link_predictor(test_data)
    print(f"Test AUC: {test_auc:.4f}")

    Here is the code output: Epoch: 000, Loss: 0.6911, Val AUC: 0.5528 Epoch: 010, Loss: 0.6779, Val AUC: 0.5297 Epoch: 020, Loss: 0.6732, Val AUC: 0.5068 Epoch: 030, Loss: 0.6696, Val AUC: 0.5156 Epoch: 040, Loss: 0.6666, Val AUC: 0.5172 Epoch: 050, Loss: 0.6668, Val AUC: 0.5139 Epoch: 060, Loss: 0.6642, Val AUC: 0.5142 Epoch: 070, Loss: 0.6631, Val AUC: 0.5132 Epoch: 080, Loss: 0.6611, Val AUC: 0.5130 Epoch: 090, Loss: 0.6600, Val AUC: 0.5135 Test AUC: 0.4843

To demonstrate how we can use this model to recommend new friendships, let’s create a function that predicts the most likely new connections for a given student:

  1. Define the function, set the model to evaluation mode, and encode the graph data:

    def recommend_friends(student_id, top_k=5):
    model.eval()
    with torch.no_grad():
    z = model.encode(data.x, data.edge_index)
  2. Here, we create an edge index for all possible connections between the given student and other students:

    other_students = torch.arange(data.num_nodes)
    other_students = other_students[
    other_students != student_id]
    edge_index = torch.stack([
    torch.full_like(other_students, student_id),
    other_students
    ])
  3. This code predicts scores for all possible connections and selects the top k recommendations based on these scores:

    scores = model.decode(z, edge_index)
    top_scores, top_indices = scores.topk(top_k)
    recommended_friends = other_students[top_indices]
  4. Finally, the function returns the recommended friends and their corresponding scores, as you can see in the following example:

    return recommended_friends, top_scores
    # Example usage
    student_id = 42 # Example student ID
    recommended_friends, scores = recommend_friends(student_id)
    print(f"Top 5 friend recommendations for student {student_id}:")
    for friend, score in zip(recommended_friends, scores):
    print(f"Student {friend.item()}: Score {score:.4f}")

    The code output is as follows: Top 5 friend recommendations for student 42: Student 381: Score 1.8088 Student 91: Score 1.6567 Student 662: Score 1.5878 Student 467: Score 1.5143 Student 870: Score 1.4449

This recommend_friends function takes a student ID and returns the top k recommended new connections based on the link prediction model.

In a real-world application, this link prediction model could be used to power a friend recommendation system in a university’s social network platform. It could help students expand their social circles based on shared characteristics and network structure.

The link prediction model’s applications extend far beyond just university social networks, encompassing diverse domains such as professional networking platforms such as LinkedIn for career connections and business collaborations, academic research networks for finding potential co-authors and research partners, business applications for supply chain partner matching and B2B networking, healthcare networks for patient referrals and provider collaborations, community building through interest-based group recommendations and event participant matching, and content recommendation systems for discovering similar resources and expert-content matching. These applications demonstrate the model’s versatility in enhancing connectivity and collaboration opportunities across various sectors and use cases.

Remember that when implementing such systems with real user data, it’s crucial to consider privacy implications and potentially incorporate additional factors (such as user preferences or mutual friends) into the recommendation algorithm.

In this chapter, we covered the practical applications of graph deep learning in social network analysis using PyG. We focused on a hypothetical dataset representing a university student social network, demonstrating how graph-based machine learning can be applied to real-world scenarios.

Together, we achieved two main tasks: node classification for predicting user interests and link prediction for recommending new connections. By following step-by-step instructions, you learned how to create a synthetic dataset, implement GCNs for node classification, and use GAEs for link prediction. We broke down our code into snippets in relation to data preparation, model training, evaluation, and visualization, allowing you to understand the practical aspects of applying graph deep learning techniques to social network data.

In the upcoming chapters, we will explore how graph deep learning is being applied to various domains, starting with natural language processing.