Skip to content

Repository files navigation

Link Prediction for Movie Recommendations

A Graph Neural Network (GNN) based movie recommendation system that uses link prediction to suggest movies to users. This project implements two state-of-the-art GNN architectures (GraphSAGE and GAT) on the MovieLens dataset to predict user-movie connections in a heterogeneous graph.

Overview

This project addresses the link prediction problem in recommendation systems: given a heterogeneous graph of users and movies connected by rating relationships, can we predict new user-movie connections? The system learns from existing user ratings to recommend movies that users are likely to enjoy.

Features

  • Two GNN Architectures: Compare GraphSAGE and Graph Attention Networks (GAT) for link prediction
  • Heterogeneous Graph Support: Handles different node types (users and movies) with distinct feature spaces
  • Scalable Training: Mini-batch training with neighborhood sampling for large graphs
  • Multiple Dataset Sizes: Implementations for both small (ml-latest-small) and large (ml-latest) MovieLens datasets
  • High Performance: Achieves 90% precision/recall (GraphSAGE) and 97.6% AUC (GAT)
  • Full Recommendation Pipeline: From data loading to generating top-k movie recommendations

Project Structure

Link-prediction/
├── Link-prediction.ipynb       # GraphSAGE implementation (ml-latest-small)
├── Link-prediction-GAT.ipynb   # GAT implementation (ml-latest)
├── requirements.txt            # Python dependencies
├── README.md                   # Project documentation
├── .gitignore                  # Git ignore configuration
└── ml-latest-small.zip         # MovieLens small dataset (956 KB)

Installation

Prerequisites

  • Python 3.8+
  • CUDA-capable GPU (recommended for large datasets)

Setup

  1. Clone the repository:
git clone <repository-url>
cd Link-prediction
  1. Install required packages:
pip install -r requirements.txt
  1. Install PyTorch Geometric dependencies:
pip install torch-scatter torch-sparse pyg-lib -f https://data.pyg.org/whl/torch-$(python -c "import torch; print(torch.__version__)").html

Requirements

  • torch>=2.4.0 - Deep learning framework
  • torch_geometric>=2.5.3 - Graph neural network library
  • numpy>=2.2.1 - Numerical computing
  • pandas>=2.1.4 - Data manipulation
  • scikit-learn>=1.6.1 - Evaluation metrics
  • tqdm>=4.66.4 - Progress bars

Usage

GraphSAGE Model (Small Dataset)

Open and run Link-prediction.ipynb:

# The notebook will:
# 1. Download and process the ml-latest-small dataset
# 2. Train a 2-layer GraphSAGE model
# 3. Evaluate with Precision@10 and Recall@10
# 4. Generate movie recommendations for all users

Training Configuration:

  • Dataset: ml-latest-small (609 users, 9,742 movies)
  • Epochs: 9
  • Batch size: 10,240
  • Hidden dimensions: 256

GAT Model (Large Dataset)

Open and run Link-prediction-GAT.ipynb:

# The notebook will:
# 1. Download and process the ml-latest dataset
# 2. Train a 2-layer Graph Attention Network
# 3. Evaluate with AUC-ROC metric
# 4. Generate top-10 recommendations with movie metadata

Training Configuration:

  • Dataset: ml-latest (330,975 users, 86,537 movies)
  • Epochs: 30
  • Batch size: 262,144
  • Hidden dimensions: 64

Models and Architectures

1. GraphSAGE-Based Link Predictor

Architecture:

  • Node Embeddings: Users (256-dim), Movies (genre features → 256-dim)
  • GNN Layers: 2-layer SAGEConv with ReLU activation
  • Edge Classifier: Dot-product between user and movie embeddings
  • Loss Function: Bayesian Personalized Ranking (BPR)

Key Features:

  • Mean-pooling aggregation for neighborhood information
  • Heterogeneous graph support with separate layers per edge type
  • Efficient sampling: 20 and 10 neighbors per layer

2. Graph Attention Network (GAT)-Based Link Predictor

Architecture:

  • Node Embeddings: Users (64-dim), Movies (genre features → 64-dim)
  • GNN Layers: 2-layer GATConv with attention mechanism
  • Edge Scorer: MLP on concatenated embeddings (128 → 1)
  • Loss Function: Bayesian Personalized Ranking (BPR)

Key Features:

  • Attention-based aggregation for weighted neighbor importance
  • MLP-based edge scoring for flexible prediction
  • Scalable to large graphs (330K+ users)

Datasets

MovieLens ml-latest-small

  • Source: GroupLens
  • Statistics: 609 users, 9,742 movies
  • Ratings Filtered: Only 4.0, 4.5, and 5.0 stars (48,580 ratings)
  • Features: 20 movie genres as binary indicators

MovieLens ml-latest

  • Source: GroupLens
  • Statistics: 330,975 users, 86,537 movies
  • Ratings: 33,832,162 ratings (all ratings included)
  • Features: 20 movie genres as binary indicators

Genres: Action, Adventure, Animation, Children, Comedy, Crime, Documentary, Drama, Fantasy, Film-Noir, Horror, IMAX, Musical, Mystery, Romance, Sci-Fi, Thriller, War, Western

Results

Model Dataset Metric Score
GraphSAGE ml-latest-small Precision@10 0.9000
GraphSAGE ml-latest-small Recall@10 0.9000
GAT ml-latest AUC-ROC 0.9760

How It Works

1. Data Processing

  • Load MovieLens ratings and movie metadata
  • Extract genre features as 20-dimensional binary vectors
  • Map IDs to consecutive integers for graph representation

2. Graph Construction

  • Create heterogeneous graph with User and Movie nodes
  • Add edges from user-movie ratings
  • Apply bidirectional edge transformation for message passing

3. Train-Val-Test Split

  • 70% training, 10% validation, 10% test
  • Disjoint training: 30% of edges removed from graph during training
  • Negative sampling: 2:1 ratio for contrastive learning

4. Mini-Batch Training

  • LinkNeighborLoader samples local neighborhoods
  • Neighborhood sampling: 20 neighbors (layer 1), 10 neighbors (layer 2)
  • BPR loss maximizes ranking of positive edges over negative edges

5. Recommendation Generation

  • Perform inference on all user-movie pairs
  • Rank movies by predicted edge scores
  • Return top-k recommendations with movie metadata

Graph Neural Network Pipeline

Input Graph (Users + Movies)
         ↓
Node Feature Extraction
  - Users: Learned embeddings
  - Movies: Genre features + embeddings
         ↓
GNN Message Passing (2 layers)
  - GraphSAGE: Mean aggregation
  - GAT: Attention-weighted aggregation
         ↓
Edge-Level Prediction
  - Dot-product (GraphSAGE)
  - MLP scorer (GAT)
         ↓
BPR Loss Optimization
         ↓
Top-K Recommendations

Key Concepts

Link Prediction

Predicting missing or future edges in a graph. In this context, predicting which movies a user will rate highly.

Heterogeneous Graph

A graph with multiple node types (users and movies) and edge types (ratings), where different types may have different feature spaces.

Bayesian Personalized Ranking (BPR)

A pairwise ranking loss that maximizes the score difference between positive (observed) and negative (unobserved) edges:

Loss = -log(σ(score_positive - score_negative))

Neighborhood Sampling

Instead of using the full graph, sample a fixed number of neighbors per node to create mini-batches for scalable training.

Differences Between Models

Aspect GraphSAGE GAT
Aggregation Mean pooling Attention-weighted
Edge Scoring Dot-product MLP (concatenation)
Dataset Small (609 users) Large (330K users)
Hidden Dim 256 64
Batch Size 10,240 262,144
Metric Precision/Recall AUC-ROC

Future Improvements

  • Implement temporal dynamics for evolving user preferences
  • Add content-based features (movie plots, actors, directors)
  • Incorporate implicit feedback (views, clicks)
  • Experiment with deeper architectures (3+ layers)
  • Add explainability for recommendations
  • Deploy as REST API service

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

Acknowledgments

License

This project is available for educational and research purposes.

Citation

If you use this code in your research, please cite:

@software{link_prediction_gnn,
  title={Link Prediction for Movie Recommendations using Graph Neural Networks},
  author={Your Name},
  year={2025},
  url={https://github.com/yourusername/Link-prediction}
}

Contact: For questions or feedback, please open an issue in the repository.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages