Skip to content
ImagineWorld

Building Recommendation Systems Using Graph Deep Learning

node_idnode-book_applied-deep-learning-on-graphs_chapter-09-building-recommendation-systems-using-graph-deep-learning
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num9
chapter_titleBuilding Recommendation Systems Using Graph Deep Learning
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 9 — Building Recommendation Systems Using Graph Deep Learning

Section titled “Chapter 9 — Building Recommendation Systems Using Graph Deep Learning”

Recommendation systems have become an integral part of our digital landscape, profoundly shaping how we interact with content, products, and services across various industries. From e-commerce giants such as Amazon to streaming platforms such as Netflix, and social media networks such as Facebook, these systems play a crucial role in enhancing user experience, driving engagement, and boosting business outcomes. As we delve into the world of building recommendation systems using graph deep learning, it’s essential to understand the evolution of these systems and the transformative potential of graph-based approaches.

Traditionally, recommendation systems have relied on techniques such as collaborative filtering (CF), content-based filtering, and hybrid approaches. While these methods have been successful to a certain extent, they often fall short in capturing the complex, interconnected nature of user-item interactions and the rich contextual information surrounding these interactions. This is where graph deep learning enters the picture, offering a paradigm shift in how we approach recommendation tasks.

Graph-based methods in recommendation systems offer numerous advantages, including providing a rich multi-modal representation of diverse information types, the ability to capture higher-order relationships beyond direct user-item interactions, handle data sparsity effectively through information propagation, inductive learning capabilities for addressing cold start problems, enhanced interpretability through graph structure analysis, and flexibility in incorporating various types of side information and heterogeneous data. Collectively, these features enable graph-based approaches to provide more comprehensive, accurate, and adaptable recommendations by leveraging the complex relationships and structures inherent in user-item interaction data and associated contextual information.

As we progress through this chapter, we’ll explore the following topics:

  • Fundamentals of recommendation systems
  • Graph structures in recommendation systems
  • Graph-based recommendation models
  • Training graph deep learning models
  • Explainability in graph-based recommendations
  • The cold start problem

Recommendation systems, also known as recommender systems, are intelligent algorithms that are designed to predict and suggest items or content that users might find interesting or relevant. These systems analyze patterns in user behavior, preferences, and item characteristics to generate personalized recommendations. The primary purpose of recommendation systems is to enhance the user experience by providing relevant content, increasing user engagement and retention, driving sales and conversions in e-commerce platforms, facilitating content discovery in large item catalogs, and personalizing services across various domains. Recommendation systems play a crucial role in addressing the information overload problem by filtering and prioritizing content based on user preferences and behavior.

Recommendation systems have become an integral part of our digital experiences, influencing our choices in various domains, such as e-commerce, entertainment, social media, and more. This section delves into the core concepts, types, and evaluation metrics of recommendation systems, providing a solid foundation for understanding their role in modern applications.

Let’s consider a streaming service that’s trying to build a recommendation system for its users. The company has user-movie interaction data as well as metadata for every single movie available. We’ll look at how we can leverage this data to provide better recommendations and increase the net promoter scores and watch times of the users effectively.

There are three main types of recommendation systems, each with its unique approach to generating recommendations:

  • CF is based on the premise that users with similar preferences in the past will have similar preferences in the future. It utilizes user-item interaction data to identify patterns and make predictions. There are two main approaches: user-based CF, which recommends items liked by similar users, and item-based CF, which recommends items similar to those the user has liked in the past. CF has the advantage of capturing complex user preferences and working well with sparse data. However, it faces challenges such as the cold start problem for new users or items and scalability issues with large datasets. In our movie recommendation system, let’s consider a user, Alice, who has rated several movies highly, including The Shawshank Redemption (5 stars), Pulp Fiction (4 stars), and The Godfather (5 stars). User-based CF would find users with similar rating patterns to Alice, such as Bob, who has rated these same movies similarly and gave a high rating to Inception. So, the system might recommend Inception to Alice based on Bob’s high rating. Item-based CF, on the other hand, would find movies similar to those Alice rated highly. It might determine that users who liked The Shawshank Redemption also enjoyed The Green Mile, leading to a recommendation for Alice.
  • Content-based filtering recommends items based on their features and the user’s past preferences. It builds a profile for each user and item based on their characteristics and uses similarity measures between user profiles and item features to generate recommendations. This approach has the advantage of providing explanations for recommendations and working well for niche items. However, it has limitations in expanding a user’s interests and requires rich item metadata. In our movie example, we’d analyze the features of movies Alice likes, such as The Shawshank Redemption (drama, directed by Frank Darabont, starring Tim Robbins and Morgan Freeman, released in 1994) and The Godfather (crime/drama, directed by Francis Ford Coppola, starring Marlon Brando and Al Pacino, released in 1972). In this case, the system might recommend other drama movies from the 1970s or 1990s, or films featuring Morgan Freeman or Al Pacino.
  • Hybrid systems combine multiple recommendation approaches to leverage their strengths and mitigate weaknesses. Common hybrid strategies include weighted approaches that combine scores from different recommenders, switching methods that choose between different recommenders based on the context, and feature combination techniques that use features from different sources as input to a single recommender. Hybrid systems often provide better performance but come with increased complexity in terms of their design and implementation. In our example, a hybrid approach might combine CF and content-based filtering. It could use CF to find similar users to Alice and then filter those recommendations based on content features she prefers, such as favoring dramas or movies from certain decades.

Table 9.1 provides a comparison of the different types, highlighting their key characteristics, advantages, and limitations:

FeatureCFContent-based filteringHybrid systems
Data requiredUser-item interactionsItem features and user preferencesBoth types of data
Strengths- Captures user preferences well - Discovers new interests - Works with minimal item information- No cold start problem for items - Can explain recommendations - Good for niche items- Better accuracy - Overcomes limitations of individual methods - More robust
Weaknesses- Cold start problem - Sparsity issues - Limited for new items- Limited serendipity - Requires detailed item features - Over-specialization- Complex implementation - Computationally expensive - Requires more data
Best use casesE-commerce, social mediaNews articles, specialized contentLarge-scale platforms, streaming services

Table 9.1 – Comparing different recommendation system types

Evaluating the performance of recommendation systems is crucial for understanding their effectiveness and guiding improvements. Several metrics and evaluation techniques are commonly used.

This is how we define these commonly used metrics:

  • Precision measures the proportion of relevant items among the recommended items:
    • Precision = (Number of relevant recommendations) / (Total number of recommendations)
  • Recall measures the proportion of relevant items that were successfully recommended:
    • Recall = (Number of relevant recommendations) / (Total number of relevant items)
  • F1 score is the harmonic mean of precision and recall, providing a balanced measure:
    • F1 = 2 × (Precision × Recall) / (Precision + Recall)
  • The mean average precision (MAP) calculates the mean of the average precision scores for each user:
    • MAP=(1∣U∣⋅Σ(AP(u)))MAP=(\frac{1}{|U|}\cdot Σ(AP(u))) , where we have the following:
    • ∣U∣|U|is the number of users.
    • AP(u)AP(u) is the average precision of the user, uu.
    • AP=Σ(P(k)×rel(k))AP=Σ(P(k)\times rel(k)) / number of relevant items
    • P(k)P(k) is the precision at the cutoff, kk.
    • rel(k)rel(k) is the indicator function (1 if item kkis relevant, 0 otherwise).
  • The normalized discounted cumulative gain (NDCG) measures the quality of ranking while taking into account the position of relevant items in the recommendation list:
    • NDCG=DCG / IDCGNDCG=DCG\,/\,IDCG, where we have the following:
    • DCG(DiscountedCumulativeGain)=Σ(reli/log⁡2⁡(i+1))DCG(DiscountedCumulativeGain)=Σ(rel_{i}/\log _{2}⁡(i+1))
    • IDCGIDCGis the ideal DCGDCG(max possible DCGDCG).
    • relirel_{i} is the relevance score of the item at position i.i.
    • ii is the position in the ranked list.

Assuming we recommend five movies to Alice, and she ends up liking three of them, the precision would be 3/5 = 0.6 or 60%. If there were 10 movies in total that Alice would have liked, the recall would be 3/10 = 0.3 or 30%. The F1 score, which provides a balanced measure, would be approximately 0.4 or 40% in this case.

Error metrics often measure the average difference between predicted and actual ratings, such as the following:

  • The mean absolute error (MAE) measures the average absolute difference between predicted and actual ratings:
    • MAE=Σ∣actual−predicted∣/nMAE=Σ|actual-predicted|/n, where nn is the number of predictions
  • The root mean squared error (RMSE) is similar to MAE but penalizes large errors more heavily:
    • RMSE=√(Σ(actual−predicted)2/n)RMSE=\surd (Σ(actual-predicted)^{2}/n)

For example, if we predicted ratings for five movies and the average difference between our predictions and Alice’s actual ratings was 0.42 stars, this would be our MAE. This suggests that, on average, our predictions are off by about 0.42 stars.

Coverage metrics assess the system’s ability to recommend a wide range of items. Item coverage measures the percentage of items in the catalog that the system can recommend, while user coverage indicates the percentage of users for whom the system can generate recommendations. In our movie system, we might measure what percentage of the 3,000 movies in our catalog we’re able to recommend (item coverage) and what percentage of our 1,000 users receive recommendations (user coverage).

Meanwhile, diversity metrics evaluate the variety (or dissimilarity) among recommended items, ensuring users receive a range of suggestions rather than similar ones. Serendipity, on the other hand, assesses the system’s ability to provide unexpected yet relevant recommendations, creating pleasant surprises for users. It combines elements of unexpectedness and relevance, often measured through unexpectedness scores and relevance evaluations. While related, diversity and serendipity are distinct: diverse recommendations may not always be serendipitous, and serendipitous recommendations often contribute to diversity but not vice versa.

These metrics are essential for creating a balanced recommendation system that offers varied, interesting, and delightfully unexpected suggestions to users (for more on this topic, see https://doi.org/10.1145/2926720).

While offline metrics provide valuable insights, real-world performance is best evaluated through A/B testing and user feedback. A/B testing involves comparing two versions of the recommendation system with real users and measuring key performance indicators such as click-through rate, conversion rate, or user engagement. User feedback, both explicit (through ratings or surveys) and implicit (through clicks or purchase behavior), is crucial for continuously improving and validating the recommendation system. Long-term user satisfaction, which is measured through user retention and engagement metrics, is also essential for assessing the impact of recommendations on user trust and platform loyalty.

Evaluating recommendation systems requires a holistic approach that considers both offline metrics and real-world performance. As recommendation systems become more sophisticated, especially with the integration of graph deep learning techniques, evaluation methods continue to evolve to capture the nuanced aspects of recommendation quality and user satisfaction.

Graph structures in recommendation systems

Section titled “Graph structures in recommendation systems”

Graph structures have emerged as a powerful paradigm for modeling complex relationships in recommendation systems. By representing users, items, and their interactions as nodes and edges in a graph, we can capture rich, multi-dimensional information that traditional matrix-based approaches often miss.

The foundation of graph-based recommendation systems is the user-item interaction graph. In this structure, users and items are represented as nodes, while interactions (such as ratings, views, or purchases) form edges between them.

For a movie recommendation system, the graph might look like this:

  • Nodes: Users (U1, U2, U3…) and movies (M1, M2, M3…)
  • Edges: Ratings or views (for example, U1 -> M1 with a weight of 4 stars)

This simple structure already allows for a more nuanced analysis than a traditional user-item matrix. For example, we can easily identify the following:

  • Popular movies (nodes with many incoming edges)
  • Active users (nodes with many outgoing edges)
  • Similar users or movies (nodes with similar edge patterns)

Consider user U1 who has watched and rated movies M1 (4 stars), M2 (3 stars), and M3 (5 stars). To recommend a new movie to U1, we can traverse the graph to find users with similar rating patterns and suggest movies they’ve enjoyed that U1 hasn’t seen yet.

Real-world recommendation systems often have access to additional information beyond just user-item interactions. Graph structures excel at incorporating this side information seamlessly. For movie recommendations, we might enhance our graph with the following aspects:

  • Movie attributes:
    • Genres (action, comedy, drama, and so on)
    • Directors
    • Actors
    • Release year
  • User attributes:
    • Age
    • Gender
    • Location
  • Social connections:
    • Friend relationships between users

These additional nodes and edges create a heterogeneous graph, where different types of nodes and relationships coexist. This rich structure allows for more sophisticated recommendation algorithms. Let’s expand on our previous example. Now, movie M1 has additional connections:

  • Genre: Action
  • Director: D1
  • Actors: A1, A2

User U1 is connected to the following aspects:

  • Age group: 25-34
  • Location: New York

By traversing this enhanced graph, we can make more nuanced recommendations. For instance, we might suggest an action movie directed by D1 that’s popular among U1’s age group in New York, even if it doesn’t have a direct connection to U1’s previously watched movies.

Time is a crucial factor in recommendation systems, especially for domains such as movies, where preferences can change rapidly. Temporal graphs incorporate time information into the graph structure.

There are several ways to represent time in a graph:

  • Time-stamped edges: Each interaction edge includes a timestamp
  • Time-based node splitting: Create multiple nodes for the same user or item at different time points
  • Dynamic graphs: The graph structure itself evolves, with nodes and edges appearing or disappearing

For movie recommendations, a temporal graph can capture the following:

  • Changes in user preferences over time
  • The life cycle of movie popularity
  • Seasonal trends in viewing habits

Consider a user, U1, who watched mostly comedies in 2020 but shifted toward dramas in 2021. A temporal graph would preserve this information, allowing the recommendation system to prioritize recent preferences while still considering long-term patterns.

We might represent this as follows:

U1_2020 -> M1 (Comedy, watched Jan 2020) U1_2020 -> M2 (Comedy, watched Jun 2020) U1_2021 -> M3 (Drama, watched Jan 2021) U1_2021 -> M4 (Drama, watched May 2021)

This structure enables sequential recommendation, where the system suggests the next movie based on the user’s recent viewing history and overall trends.

In complex domains such as movie recommendations, different types of relationships often coexist. Multi-relational graphs allow us to represent these varied connections explicitly.

For movies, we might have these relationships:

  • User-movie: "rated", "watched", and "added ``to wishlist"
  • User-user: "is friends with" and "has similar ``taste to"
  • Movie-movie: "has same genre", "has same director", and "is ``sequel to"

Each relationship can have its own semantics and importance in the recommendation process. Here’s an example:

U1 —(“rated”, 5)-> M1 U1 —(“is friends with”)-> U2 U2 —(“rated”, 4)-> M2 M1 —(“has same director”)-> M2

This multi-relational structure allows for sophisticated path-based recommendations. For instance, we might recommend M2 to U1 because of the following reasons:

  • U1’s friend, U2, rated it highly.
  • It shares a director with M1, which U1 loved.

By leveraging these complex relationships, multi-relational graphs enable more contextual and explainable recommendations.

Graph structures excel at capturing complex relationships, incorporating diverse information sources, and modeling temporal dynamics. As we’ll see in subsequent sections, these rich graph structures form the foundation for sophisticated deep learning models that can generate highly personalized and accurate recommendations.

Graph-based recommendation models have emerged as powerful tools for capturing complex relationships between users and items in recommendation systems. These models leverage the rich structural information inherent in user-item interaction graphs to generate more accurate and personalized recommendations. In this section, we’ll explore three major categories of graph-based recommendation models, starting with matrix factorization (MF) with graph regularization.

MF is a fundamental technique in CF, and its integration with graph structures has led to significant improvements in recommendation quality. Graph regularization in MF models helps to incorporate the structural information of the user-item interaction graph into the learning process.

The basic idea is to add a regularization term to the traditional MF objective function that encourages connected nodes in the graph to have similar latent representations. This approach helps to capture the local structure of the user-item graph and can lead to more accurate recommendations.

For movie recommendations, consider a scenario where we have a user-item graph with users and movies as nodes, and ratings as edges. The graph regularization term would encourage users who have rated similar movies to have similar latent factors, and movies that have been rated similarly to also have similar latent factors.

A typical objective function for MF with graph regularization might look like this:

L = Σ(u,i) ϵ o(rui − puTqi)2 + λ(∥P∥F2 + ∥Q∥F2) + α Σ(u,v) ϵ ℇu∥pu− pv∥2 + β Σ(i,j) ϵ ℇi ∥qi− qj∥2L\,=\,Σ_{(u,i)\,ϵ\,o}(r_{ui\,}-\,p_{u}^{T}q_{i})^{2}\,+\,λ(\|P\|_{F}^{2}\,+\,\|Q\|_{F}^{2})\,+\,α\,Σ_{(u,v)\,ϵ\,ℇ_{u}}\|p_{u}-\,p_{v}\|^{2}\,+\,β\,Σ_{(i,j)\,ϵ\,ℇ_{i}}\,\|q_{i}-\,q_{j}\|^{2}

Here, pup_{u}and qiq_{i}are the latent factors for the user,uu, and the item,ii, respectively, ℇuℇ_{u} and ℇiℇ_{i} are the sets of edges in the user-user and item-item graphs, and ααand ββare regularization parameters.

This approach has shown improved performance over traditional MF, especially in scenarios with sparse data, as it can leverage the graph structure to make better predictions for users or items with few interactions.

As we saw in Chapter 4, graph neural networks (GNNs) have revolutionized the field of graph-based recommendations by enabling direct learning on graph-structured data. The following models can capture high-order connectivity patterns and learn rich node representations that incorporate both node features and graph structure.

PinSage, developed by Pinterest, is a pioneering GNN model for large-scale recommendation systems. It adapts the GraphSAGE architecture to generate embeddings efficiently for nodes in web-scale graphs.

In a movie recommendation context, PinSage could be used to generate embeddings for both users and movies. The model would aggregate information from a node’s local neighborhood, capturing not just direct interactions but also higher-order relationships. For example, it could identify that two users who haven’t watched the same movies might still have similar tastes if they’ve watched movies that are themselves similar.

The key steps in PinSage are as follows:

  1. Neighborhood sampling: For each node, sample a fixed number of neighbors to make computation feasible on large graphs.
  2. Feature aggregation: Aggregate features from the sampled neighbors using learnable aggregation functions.
  3. Embedding generation: Combine the aggregated neighborhood information with the node’s features to generate the final embedding.

Neural graph collaborative filtering (NGCF) explicitly incorporates the user-item graph structure into the embedding learning process. It propagates embeddings on the user-item interaction graph to capture collaborative signals.

For movie recommendations, NGCF would start with initial embeddings for users and movies and then update these embeddings iteratively by passing messages along the edges of the user-movie interaction graph. This process allows the model to capture high-order connectivity between users and movies.

The embedding update process in NGCF can be described as follows:

eu(k)=σ(W1(k)eu(k−1)+∑iϵNu1∣Nu∣∣Ni∣W2(k)ei(k−1))e_{u}^{(k)}=σ(W_{1}^{(k)}e_{u}^{(k-1)}+\sum _{iϵN_{u}}^{}\frac{1}{\sqrt{|N_{u}||N_{i}|}}W_{2}^{(k)}e_{i}^{(k-1)})

Here, eu(k)e_{u}^{(k)} is the embedding of the user, uu, at the kkth layer. NuN_{u} is the set of items that are interacted with by the user, uu, and W1(K)W_{1}^{(K)}and W2(K)W_{2}^{(K)} are learnable weight matrixes.

LightGCN simplifies the NGCF model by removing feature transformation and nonlinear activation, focusing solely on the most essential component of graph convolutional networks (GCNs) for CF: neighborhood aggregation.

In the context of movie recommendations, LightGCN would represent users and movies as nodes in a bipartite graph. The model then performs multiple layers of neighborhood aggregation to capture high-order connectivity. The final embeddings are a weighted sum of embeddings from all layers.

The embedding propagation rule in LightGCN is as follows:

eu(k=1)=∑iϵNu1∣Nu∣∣Ni∣ei(k)e_{u}^{(k=1)}=\sum _{iϵN_{u}}^{}\frac{1}{\sqrt{|N_{u}||N_{i}|}}e_{i}^{(k)}

The simplicity of LightGCN makes it computationally efficient while still achieving state-of-the-art performance on many recommendation tasks.

Training graph deep learning models for recommendation systems is a complex process that requires various factors to be considered carefully. In this section, we’ll provide a comprehensive guide to training these models.

Effective data preprocessing is crucial for the success of graph-based recommendation models. Let’s dive deeper into the steps involved.

Creating a high-quality interaction graph is the foundation of graph-based recommendation systems. Let’s take a look:

  1. Node creation:
    • Assign unique identifiers to each user and movie.
    • Create node attributes to store relevant information.
  2. Edge creation:
    • Create edges based on user-movie interactions.
    • Consider different types of interactions (for example, ratings, views, and likes).
  3. Edge weighting:
    • Assign weights to edges based on interaction strength.
    • Normalize weights to ensure consistency across different interaction types.
  4. Handling temporal information:
    • Incorporate the timestamps of interactions as edge attributes.
    • Consider creating multiple edges for repeated interactions.

Here’s some example pseudocode for building a more detailed graph:

import networkx as nx
from datetime import datetime
def build_movie_graph(interactions):
G = nx.Graph()
for user_id, movie_id, rating, timestamp in interactions:
# Add user node with type attribute
user_node = f"user_{user_id}"
G.add_node(user_node, type="user",
last_active=timestamp)
# Add movie node with type attribute
movie_node = f"movie_{movie_id}"
G.add_node(movie_node, type="movie")
# Add or update edge
if G.has_edge(user_node, movie_node):
G[user_node][movie_node]['weight'] += 1
G[user_node][movie_node]['last_interaction'] = timestamp
G[user_node][movie_node]['ratings'].append(float(rating))
else:
G.add_edge(user_node, movie_node,
weight=1,
last_interaction=timestamp,
ratings=[float(rating)])
return G

The following function normalizes the edge weights in the graph to provide a relative measure of interaction strength:

def normalize_edge_weights(G):
for edge in G.edges():
ratings = G.edges[edge].get('ratings', [])
if ratings:
avg_rating = np.mean(ratings)
# Store average rating:
G.edges[edge]['rating'] = avg_rating
# Normalize to [0,1]:
G.edges[edge]['weight'] = avg_rating / 5.0
else:
G.edges[edge]['rating'] = 0
G.edges[edge]['weight'] = 0

You can enhance the graph with rich features to improve model performance:

  • User features:
    • Demographic information, such as age, gender, and location
    • Behavioral features, such as average rating, genre preferences, and activity level
    • Derived features, such as user segments based on viewing patterns
  • Movie features:
    • Basic attributes, such as genre, release year, and duration
    • Production details, such as director, actors, budget, and production company
    • Performance metrics, such as box office revenue and critic ratings
    • Derived features, such as popularity score and genre embeddings
  • Temporal features:
    • Time-based user features, such as viewing frequency and time since the last activity
    • Time-based movie features, such as the age of the movie and seasonal popularity
  • Graph-based features:
    • Node degree, such as the number of movies rated by a user or the number of ratings for a movie
    • Centrality measures, such as PageRank and betweenness centrality
    • Community detection – for example, assign community labels to nodes

Here’s an example of advanced feature engineering:

import numpy as np
from sklearn.preprocessing import StandardScaler
def engineer_user_features(G, user_data):
user_features = {}
for node, data in G.nodes(data=True):
if data['type'] == 'user':
user_id = node.split('_')[1]
# Add check if user exists in user_data:
if user_id in user_data:
user_info = user_data[user_id]
# Basic features
features = [
float(user_info['age']), # Convert to float
float(user_info['gender_encoded']),
float(user_info['location_encoded']),
]
# Behavioral features
# Get ratings directly from edges
ratings = [G[node][edge].get(
'rating', 0) for edge in G[node]]
avg_rating = np.mean(ratings) if ratings else 0
rating_count = G.degree(node)
features.extend([avg_rating, float(rating_count)])
# Add genre preferences
genre_preferences = calculate_genre_preferences(
G, node)
features.extend(genre_preferences)
user_features[node] = np.array(
features, dtype=np.float32)
return user_features

The following function calculates genre preferences for a given user. This is used as part of the feature engineering process outlined previously:

def calculate_genre_preferences(G, user_node):
genre_counts = {genre: 0 for genre in GENRE_LIST}
total_ratings = 0
# Iterate through neighboring movie nodes
for neighbor in G[user_node]:
if neighbor.startswith('movie_'):
movie_id = neighbor.split('_')[1]
if movie_id in movie_data:
genres = movie_data[movie_id]['genres']
rating = G[user_node][neighbor]['rating']
for genre in genres:
if genre in genre_counts:
genre_counts[genre] += rating
total_ratings += 1
# Normalize genre preferences
genre_preferences = []
for genre in GENRE_LIST:
if total_ratings > 0:
genre_preferences.append(
genre_counts[genre] / total_ratings)
else:
genre_preferences.append(0)
return genre_preferences

Training graph deep learning models for recommendation systems involves several advanced techniques to improve performance and efficiency.

You can choose and combine appropriate loss functions based on the recommendation task:

  • Binary cross-entropy (BCE) can be used for implicit feedback:

    def bce_loss(predictions, targets):
    return F.binary_cross_entropy_with_logits(
    predictions, targets)
  • Mean squared error (MSE) can be employed for explicit feedback (rating prediction):

    def mse_loss(predictions, targets):
    return F.mse_loss(predictions, targets)
  • Bayesian personalized ranking (BPR) loss can be utilized for pairwise ranking:

    def bpr_loss(pos_scores, neg_scores):
    return -F.logsigmoid(pos_scores - neg_scores).mean()
  • Margin ranking loss is another option for pairwise ranking:

    def margin_ranking_loss(pos_scores, neg_scores, margin=0.5):
    return F.margin_ranking_loss(
    pos_scores, neg_scores,
    torch.ones_like(pos_scores), margin=margin)
  • Combination of losses can combine multiple loss functions for multi-task learning:

    def combined_loss(pred_ratings, true_ratings,
    pos_scores, neg_scores, alpha=0.5):
    # Convert inputs to floating point tensors if they aren't already
    pred_ratings = pred_ratings.float()
    true_ratings = true_ratings.float()
    pos_scores = pos_scores.float()
    neg_scores = neg_scores.float()
    rating_loss = mse_loss(pred_ratings, true_ratings)
    ranking_loss = bpr_loss(pos_scores, neg_scores)
    return alpha * rating_loss + (1 - alpha) * ranking_loss

You can also implement an advanced training loop with various optimization techniques:

  • Gradient accumulation for larger effective batch sizes: This technique allows for larger effective batch sizes by accumulating gradients over multiple batches before performing an optimizer step:

    # Inside the training loop
    for batch_idx, batch in enumerate(generate_batches(train_graph)):
    # ... (model forward pass and loss calculation)
    # Gradient accumulation
    loss = loss / ACCUMULATION_STEPS
    loss.backward()
    if (batch_idx + 1) % ACCUMULATION_STEPS == 0:
    optimizer.step()
    optimizer.zero_grad()
  • Learning rate scheduling: The ReduceLROnPlateau scheduler adjusts the learning rate based on the validation loss, reducing it when the loss plateaus:

    scheduler = ReduceLROnPlateau(
    optimizer, mode='min', factor=0.5, patience=3
    )
    # Inside the training loop
    scheduler.step(val_loss)
  • Early stopping based on validation performance: This technique stops training when the validation loss doesn’t improve for a specified number of epochs, preventing overfitting:

    # Inside the training loop
    if val_loss < best_val_loss:
    best_val_loss = val_loss
    no_improve_count = 0
    torch.save(model.state_dict(), 'best_model.pth')
    else:
    no_improve_count += 1
    if no_improve_count >= patience:
    print(f"Early stopping after {epoch} epochs")
    break
    # After training
    model.load_state_dict(torch.load('best_model.pth'))
  • Gradient clipping to prevent exploding gradients: Gradient clipping prevents gradients from becoming too large, which can cause instability during training:

    # Inside the training loop, before optimizer step
    torch.nn.utils.clip_grad_norm_(
    model.parameters(), max_norm=1.0)

Handling large-scale graphs requires advanced techniques for efficient training and inference. We covered the challenge of scalability in Chapter 5; here, we’ll look at practical examples of techniques that can help us address this issue.

Mini-batch training with neighborhood sampling

Section titled “Mini-batch training with neighborhood sampling”

Instead of processing the entire graph, we can use mini-batch training with neighborhood sampling:

  1. Sample a subset of user nodes:

    def create_mini_batch(G, batch_size, n_pos=5, n_neg=5,
    n_neighbors=10, n_hops=2):
    # Get all user nodes
    all_user_nodes = [n for n in G.nodes() if
    n.startswith('user_')]
    if not all_user_nodes:
    raise ValueError("No user nodes found in graph")
    # Randomly select users
    user_nodes = random.sample(
    all_user_nodes,
    min(batch_size, len(all_user_nodes))
    )
    # Create subgraph
    subgraph = G.subgraph(user_nodes).copy()

    This step randomly selects a subset of user nodes to form the mini-batch.

  2. For each user, sample a fixed number of positive and negative movie interactions. Here, we sample positive movie interactions from the user’s neighbors and negative interactions from movies the user hasn’t interacted with:

    # Sample positive and negative movies
    pos_movies = []
    neg_movies = []
    all_movies = [n for n in G.nodes() if
    n.startswith('movie_')]
    for user in user_nodes:
    user_movies = [n for n in G[user] if
    n.startswith('movie_')]
    pos_sample = random.sample(
    user_movies, min(n_pos, len(user_movies))
    ) if user_movies else []
    available_neg = list(set(all_movies) -
    set(user_movies))
    neg_sample = random.sample(available_neg, min(
    n_neg, len(available_neg))
    ) if available_neg else []
    pos_movies.extend(pos_sample)
    neg_movies.extend(neg_sample)
    return subgraph, user_nodes, pos_movies, neg_movies
  3. Perform multi-hop neighborhood sampling to create a subgraph containing the relevant nodes and their neighbors:

    def sample_neighbors(graph, nodes, n_neighbors, n_hops):
    sampled_nodes = set(nodes)
    for _ in range(n_hops):
    new_nodes = set()
    for node in sampled_nodes:
    neighbors = list(graph.neighbors(node))
    sampled = random.sample(
    neighbors, min(n_neighbors, len(neighbors))
    )
    new_nodes.update(sampled)
    sampled_nodes.update(new_nodes)
    return list(sampled_nodes)
    # Inside create_mini_batch function
    all_nodes = user_nodes + pos_movies + neg_movies
    sampled_nodes = sample_neighbors(
    graph, all_nodes, n_neighbors, n_hops)
  4. Finally, we create the subgraph and conduct message passing within the sampled subgraph:

    subgraph = graph.subgraph(sampled_nodes)
    return subgraph, user_nodes, pos_movies, neg_movies

For extremely large graphs, you can implement distributed training:

  1. Graph partitioning: Divide the graph across multiple machines to enable distributed processing:

    def partition_graph(graph, rank, world_size):
    # Implement graph partitioning logic here
    # This is a placeholder function
    num_nodes = graph.number_of_nodes()
    nodes_per_partition = num_nodes // world_size
    start_node = rank * nodes_per_partition
    end_node = start_node + nodes_per_partition if rank < \\
    world_size - 1 else num_nodes
    local_nodes = list(graph.nodes())[start_node:end_node]
    return graph.subgraph(local_nodes)
    # Usage in distributed_train function
    local_graph = partition_graph(graph, rank, world_size)
  2. Distributed message passing: Implement efficient communication protocols for distributed message passing across machines:

    import torch.distributed as dist
    def distributed_message_passing(local_graph, node_features):
    # Perform local message passing
    local_output = local_message_passing(
    local_graph, node_features)
    # Gather results from all processes
    gathered_outputs = [torch.zeros_like(local_output) for _ in
    range(dist.get_world_size())]
    dist.all_gather(gathered_outputs, local_output)
    # Combine gathered results
    global_output = torch.cat(gathered_outputs, dim=0)
    return global_output
    # Usage in model forward pass
    def forward(self, graph, node_features):
    # ... other layers
    node_features = distributed_message_passing(
    graph, node_features)
    # ... remaining layers
  3. Parameter server architecture: Use DistributedDataParallel (DDP) to centralize model parameter updates across all processes:

    from torch.nn.parallel import DistributedDataParallel as DDP
    def distributed_train(rank, world_size, graph):
    setup(rank, world_size)
    # Create model and move it to GPU with id rank
    model = GraphRecommender(...).to(rank)
    model = DDP(model, device_ids=[rank])
    optimizer = optim.Adam(model.parameters(), lr=0.001)
    # ... training loop
    cleanup()

By implementing all the strategies outlined in this section, such as efficient graph construction, comprehensive feature engineering, sophisticated loss functions, and scalable training methods, you can develop powerful and effective graph-based recommendation systems.

Explainability in graph-based recommendations

Section titled “Explainability in graph-based recommendations”

As recommendation systems become more sophisticated, the need for explainable AI (XAI) in these systems grows. Graph-based models offer unique opportunities for enhancing the explainability of recommendations.

As we saw in Chapter 4, graph attention networks (GATs) can be leveraged to provide insights into which nodes or features contribute most to a recommendation. For movie recommendations, this could reveal which actors, directors, or genres have the most significant influence on a user’s preferences.

Consider a user who frequently watches action movies starring Tom Cruise. The attention mechanism might highlight that the presence of Tom Cruise in a movie’s cast graph node has a higher weight in the recommendation process for this user compared to other factors.

Metapath-based models can offer intuitive explanations by showing the reasoning path that led to a recommendation.

For example, a movie recommendation might be explained as follows: We recommended “Inception” because you enjoyed “The Dark Knight” (same director: Christopher Nolan) and “Interstellar” (similar genre: sci-fi thriller).

One of the major challenges that businesses face is a lack of data. A new product might not have enough customer data to build these sophisticated recommendation models. This challenge is called the cold start problem, and we’re going to look into how we can leverage graph algorithms to solve it.

The cold start problem in recommendation systems refers to the challenge of making accurate recommendations for new users or new items that have little to no interaction data. In movie recommendation systems, this occurs when a new user joins the platform and has no viewing history or when a new movie is released and has no user ratings or interactions.

The cold start problem is particularly challenging in movie recommendation systems, especially for new users or newly released movies.

One solution to the cold start problem is graph embedding transfer, a technique that’s used to initialize representations for new nodes (movies or users) in a recommendation graph when there’s no interaction data available. Here’s a general description:

  • For new items (for example, movies):
    • Identify similar existing items based on metadata or content features.
    • Use the embeddings of these similar items to initialize the embedding of the new item.
    • This gives the new item a starting point in the embedding space that reflects its likely characteristics.
  • For new users:
    • Use available demographic or preference information to find similar existing users.
    • Initialize the new user’s embedding based on these similar users’ embeddings.
    • As the new user interacts with the system, their embedding can be fine-tuned.

For example, when a new superhero movie is released, we can initialize its embedding by averaging the embeddings of other superhero movies in the graph:

def initialize_new_movie(movie_id, similar_movies, movie_embeddings):
if not similar_movies:
return np.zeros(next(iter(movie_embeddings.values())).shape)
similar_embeddings = [
movie_embeddings[m] for m in similar_movies if
m in movie_embeddings
]
if not similar_embeddings:
return np.zeros(next(iter(movie_embeddings.values())).shape)
return np.mean(similar_embeddings, axis=0)

Another effective approach to mitigate cold start issues is to leverage content-based features from available metadata or item descriptions. By integrating multiple content-based features such as text attributes, categorical information, and any available numerical data, a system can generate initial recommendations even for new items or users with no interaction history. This integrated feature representation can be used to compute item similarities or train machine learning models that predict user preferences based on item characteristics.

For instance, when a new user signs up, we can create edges to movies based on their stated preferences (genres, actors, and directors), even before they’ve watched anything:

def create_initial_edges(user_id, preferences, movie_graph):
for pref in preferences:
similar_movies = [
m for m in movie_graph.nodes if
pref in movie_graph.nodes[m]['attributes']]
for movie in similar_movies:
movie_graph.add_edge(
user_id, movie, weight=0.5 # Initial weak connection
)
return movie_graph
# Usage
updated_graph = create_initial_edges(
'new_user_123', ['Sci-Fi', 'Tom Hanks'], movie_graph)

These are just a couple of ways we can approach a cold start problem in a recommendation system that leverages graphs.

In this chapter, we introduced graph deep learning as an advanced approach to recommendation systems. You learned about the fundamental concepts of recommendation systems, including the different types and evaluation metrics.

Then, we delved into graph structures for representing user-item interactions, incorporating side information, and capturing temporal dynamics. Various graph-based recommendation models were explored, from MF with graph regularization to advanced GNN models. You also became familiar with a variety of training techniques, scalability challenges, and advanced topics such as explainability and the cold start problem in graph-based recommendation systems.

In the next chapter, we’re going to investigate the applications of graph learning in computer vision.