Jump to content

Connect SuperML | Leeroopedia MCP: Equip your AI agents with best practices, code verification, and debugging knowledge. Powered by Leeroo — building Organizational Superintelligence. Contact us at founders@leeroo.com.

Implementation:Recommenders team Recommenders LightGCN

From Leeroopedia


Knowledge Sources
Domains Recommender Systems, Deep Learning, Graph Neural Networks, Collaborative Filtering
Last Updated 2026-02-10 00:00 GMT

Overview

Implements the LightGCN model, a simplified graph convolution network for collaborative filtering that achieves strong performance by removing feature transformation and nonlinear activation from standard GCN.

Description

The LightGCN class implements the LightGCN architecture from He et al. (SIGIR 2020). Unlike the DeepRec models that extend BaseModel, LightGCN is a standalone class that manages its own TensorFlow session, training loop, and evaluation pipeline because it operates on graph-structured implicit feedback data rather than sequential feature-based input.

During initialization, user and item embeddings are created using Xavier initialization via _init_weights. The GCN propagation is constructed in _create_lightgcn_embed, which stacks n_layers of sparse matrix multiplications with the normalized adjacency matrix (provided by the ImplicitCF data object). After propagation, embeddings from all layers (including the initial embedding layer) are stacked and averaged to produce the final user and item representations. This layer-averaging is a key design choice that distinguishes LightGCN from other GCN approaches.

Training uses BPR (Bayesian Personalized Ranking) loss computed in _create_bpr_loss, which maximizes the difference between positive and negative item scores using a softplus function. L2 regularization is applied to the original pre-propagation embeddings (not the propagated ones), controlled by the decay hyperparameter. The Adam optimizer is used for training.

The fit method runs the training loop, sampling positive and negative items via the data object's train_loader. Optional periodic evaluation is triggered every eval_epoch epochs using run_eval, which computes top-k recommendation metrics (MAP, NDCG, Precision, Recall).

The score method computes ratings for all items for a batch of users via matrix multiplication of their propagated embeddings. It optionally removes items already seen during training by setting their scores to negative infinity. The recommend_k_items method generates a pandas DataFrame of top-k recommendations using get_top_k_scored_items.

The infer_embedding method exports the learned user and item embeddings to TSV files for external use.

Usage

Instantiate LightGCN with hyperparameters and an ImplicitCF data object that provides the normalized adjacency matrix and train/test splits. Call fit() to train (no file arguments needed since data is provided at initialization). Use recommend_k_items() to generate recommendations and score() to compute raw scores.

Code Reference

Source Location

Signature

class LightGCN(object):
    """LightGCN model"""

    def __init__(self, hparams, data, seed=None):

    def _init_weights(self):
    def _create_lightgcn_embed(self):
    def _create_bpr_loss(self, users, pos_items, neg_items):
    def _convert_sp_mat_to_sp_tensor(self, X):

    def fit(self):
    def load(self, model_path=None):
    def run_eval(self):
    def score(self, user_ids, remove_seen=True):
    def recommend_k_items(self, test, top_k=10, sort_top_k=True,
                          remove_seen=True, use_id=False):
    def output_embeddings(self, idmapper, n, target, user_file):
    def infer_embedding(self, user_file, item_file):

Import

from recommenders.models.deeprec.models.graphrec.lightgcn import LightGCN

I/O Contract

Inputs (__init__)

Name Type Required Description
hparams HParams Yes Hyperparameters object with model configuration
data ImplicitCF Yes A recommenders.models.deeprec.DataModel.ImplicitCF object that loads and processes implicit feedback data, provides the normalized adjacency matrix, and exposes train_loader, n_users, n_items
seed int No Random seed for TensorFlow and NumPy reproducibility

Key Hyperparameters

Name Type Description
epochs int Number of training epochs
learning_rate float Learning rate for the Adam optimizer
embed_size int Dimension of user and item embedding vectors
batch_size int Mini-batch size for training
n_layers int Number of GCN propagation layers
decay float L2 regularization coefficient for BPR loss
eval_epoch int Evaluate every N epochs; set to -1 to disable periodic evaluation
top_k int Number of top items for evaluation metrics
metrics list List of evaluation metrics: "map", "ndcg", "precision", "recall"
save_model bool Whether to save model checkpoints
save_epoch int Save a checkpoint every N epochs
MODEL_DIR str Directory for saving model checkpoints

Inputs (recommend_k_items)

Name Type Required Description
test pandas.DataFrame Yes Test data containing user and item columns
top_k int No Number of top items to recommend. Defaults to 10
sort_top_k bool No Whether to sort top-k results. Defaults to True
remove_seen bool No Whether to remove items seen in training. Defaults to True
use_id bool No Whether user IDs in the test set are internal integer IDs. Defaults to False

Outputs

Name Type Description
score return numpy.ndarray Matrix of predicted scores with shape (n_test_users, n_items)
recommend_k_items return pandas.DataFrame DataFrame with columns for user, item, and prediction score, containing top-k recommendations per user
run_eval return list List of metric values corresponding to the configured self.metrics

Usage Examples

Basic Usage

from recommenders.models.deeprec.models.graphrec.lightgcn import LightGCN
from recommenders.models.deeprec.DataModel.ImplicitCF import ImplicitCF
from recommenders.models.deeprec.deeprec_utils import prepare_hparams

# Load data
data = ImplicitCF(train=train_df, test=test_df)

# Prepare hyperparameters
hparams = prepare_hparams(
    "lightgcn.yaml",
    epochs=50,
    learning_rate=0.005,
    embed_size=64,
    batch_size=1024,
    n_layers=3,
    decay=1e-4,
    eval_epoch=5,
    top_k=10,
    metrics=["ndcg", "recall"],
)

# Initialize and train
model = LightGCN(hparams, data, seed=42)
model.fit()

Generating Recommendations

# Generate top-10 recommendations for test users
topk_scores = model.recommend_k_items(test_df, top_k=10, remove_seen=True)
print(topk_scores.head())
#   userID  itemID  prediction
# 0      1     234    0.95432
# 1      1     567    0.87654
# ...

Exporting Embeddings

# Export learned user and item embeddings
model.infer_embedding(
    user_file="output/user_embeddings.tsv",
    item_file="output/item_embeddings.tsv",
)
# Each line: id<TAB>dim1 dim2 dim3 ...

Related Pages

Requires Environment

Uses Heuristic

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment