LibRecommender Documentation

repository·master·Indexed 19 days ago

https://github.com/massquantity/librecommender

A versatile end-to-end recommender system library (version 1.5.2) designed for easy training and deployment. It provides a unified API for collaborative filtering and hybrid content-based approaches, supporting algorithms such as LightGCN and YouTubeRanking. The library includes tools for data preparation via DatasetPure and DatasetFeat, a wide range of supported algorithms across TensorFlow1 and PyTorch backends, and a serving module (libserving) with Redis and Faiss integration.

Tokens
51.4K
Snippets
185
Records
225
Agent score
66%

What's inside LibRecommender

  1. Overview of LibRecommender features

    master

    LibRecommender is an end-to-end recommendation system framework consisting of two main modules:

    1. libreco: The training module used for data preprocessing, model training, evaluation, and model persistence.
    2. libserving: The serving module used for deploying trained models.

    Key Capabilities:

    • Algorithm Support: Implements popular algorithms like FM, DIN, LightGCN, and YouTubeRanking.
    • Hybrid Recommendation: Supports both collaborative-filtering and content-based features. Features can be added dynamically.
    • Efficient Data Handling: Automatically converts categorical and multi-value categorical features to sparse representations to minimize memory usage.
    • Dataset Flexibility: Supports explicit and implicit datasets, including negative sampling for implicit data.
    • Advanced Scenarios: Supports cold-start prediction/recommendation, dynamic feature recommendation, and sequence recommendation.
    • Workflow: Provides a unified API for the full lifecycle: Data Handling $\rightarrow$ Training $\rightarrow$ Evaluation $\rightarrow$ Save/Load $\rightarrow$ Serving.
  2. Overview of the Python Model Serving Workflow

    master

    To serve a trained model in LibRecommender using the libserving module, follow these four steps:

    1. Serialize the trained model to disk (typically in JSON format).
    2. Load the model from disk and save it to a Redis instance.
    3. Run the Sanic web server.
    4. Make HTTP requests to the server to obtain recommendations.

    Important Notes:

    • Redis Requirement: You must start a Redis server (redis-server) before running the serving workflow.
    • Data Isolation: When switching between different model types (e.g., from a feat model like DeepFM to a pure model like NCF), ensure you clear previous feature information from Redis to avoid loading stale data and causing errors.
    • Directory Context: Most libserving commands assume you are working within the LibRecommender/libserving directory of the cloned repository.
    # 1. Clone and enter the serving directory
    $ git clone https://github.com/massquantity/LibRecommender.git
    $ cd LibRecommender/libserving
    
    # 2. Start Redis
    $ redis-server
  3. Understand the DataInfo object

    master

    The DataInfo object is a central data structure in LibRecommender that stores essential information about the dataset, including unique features for users and items.

    Key behaviors:

    • Feature Storage: For feat models, it stores unique feature values. If a user/item has multiple values in the training data, only the last one (based on temporal sorting) is kept.
    • Model Integration: Most models contain a data_info property used during recommendation.
    • Persistence: When saving or loading a model, you must also save and load the corresponding DataInfo object to ensure consistency.
    • Immutability during Prediction: Calling predict or recommend_user with specific features does not modify the DataInfo object.
  4. Choose between rating and ranking tasks

    master

    LibRecommender supports two primary task types based on the nature of your data:

    1. rating task: Used for explicit data (e.g., MovieLens, Netflix) where users provide direct feedback like scores.
    2. ranking task: Used for implicit data (e.g., Last.FM) where feedback is inferred from behaviors (e.g., clicks, views). This often involves only positive samples, requiring negative sampling for effective training.

    Key differences in implementation:

    • You must specify the task parameter when building a model.
    • Evaluation metrics differ by task type.

    Available Metrics:

    • For rating tasks: rmse, mae, r2.
    • For ranking tasks: loss, balanced_accuracy, roc_auc, pr_auc, precision, recall, map, ndcg.

    Note that certain models (e.g., BPR, YouTubeRetrieval, YouTubeRanking, Item2Vec, DeepWalk, LightGCN) are designed exclusively for ranking tasks.

    # Example: Using SVD for a rating task
    model = SVD(task="rating", ...)
    model.fit(..., metrics=["rmse", "mae", "r2"])
  5. Extend LibRecommender by implementing base classes

    master

    LibRecommender provides several base classes in libreco.bases that serve as templates for implementing custom recommendation algorithms. Depending on your goal, you should inherit from one of the following specialized base classes:

    • Base: The fundamental base class for all algorithms.
    • EmbedBase: For algorithms based on embedding representations.
    • TfBase: For algorithms based on Tensor Factorization.
    • CfBase: For Collaborative Filtering algorithms.
    • RsCfBase: For Recommender System Collaborative Filtering algorithms.
    • GensimBase: For algorithms utilizing the Gensim library (often for NLP/sequence-based tasks).
    • SageBase: For algorithms utilizing SageMaker or similar frameworks.
    • DynEmbedBase: For dynamic embedding-based algorithms.

    When implementing a new algorithm, inherit from the class that most closely matches your mathematical approach to ensure compatibility with the LibRecommender ecosystem.

  6. Understand the role of DataInfo in LibRecommender

    master

    The DataInfo object is a central container that stores metadata and state extracted from the original dataset. Most models in LibRecommender possess a data_info attribute, which is essential for making recommendations.

    Key responsibilities of DataInfo include:

    • Feature Storage: For feat models, it stores the unique features of all users and items. Note that if a user/item has multiple feature values in the training data, only the last one encountered is stored (this assumes data is sorted chronologically).
    • Interaction History: It stores the items consumed by users, which is critical for sequence-based models and the unconsumed sampler.
    • Model Persistence: When saving or loading a model, you must also save and load the corresponding DataInfo object to ensure the model has access to the necessary metadata for prediction.
  7. Handle cold-start users and items

    master

    When encountering new users or items not present in the training data (the "cold-start" problem), LibRecommender provides two strategies via the cold_start parameter in recommend_user():

    1. popular: Returns the most popular items from the training data.
    2. average: Uses the average of all user/item embeddings as the representation for the cold-start entity. This treats the new entity's behavior as the "average" behavior of known entities.

    New feature categories are also handled by using the average embedding of known categories for that feature.

    # Example of using the popular strategy for cold-start
    model.recommend_user(user=1, n_rec=7, cold_start="popular")
  8. Understand Sparse and Dense feature handling

    master

    LibRecommender distinguishes between sparse and dense features to optimize how they are projected into embeddings:

    • Sparse features: Categorical features (e.g., sex, location, year). These are projected into low-dimensional vectors via an embedding layer where each unique category gets its own embedding vector.
    • Dense features: Numerical features (e.g., age, price, length). These are handled using the AutoInt method: every dense feature is projected into a low-dimensional vector via an embedding layer, and that vector is then multiplied by the actual dense feature value. This allows dense and sparse features to interact in models like FM, DeepFM, and AutoInt.

    To build a model, you must provide four types of column identifiers: sparse_col, dense_col, user_col, and item_col.

  9. Distinguish between Pure and Feat models

    master

    LibRecommender models are categorized based on whether they use auxiliary features (like age, sex, or name) or only user behavior data.

    Pure Models

    These models only use user behaviors. Examples include UserCF, ItemCF, SVD, SVD++, ALS, NCF, BPR, RNN4Rec, Item2Vec, Caser, WaveNet, DeepWalk, NGCF, and LightGCN.

    • Data Requirement: Must use libreco.data.dataset.DatasetPure for data processing.

    Feat Models

    These models can incorporate additional features. Examples include WideDeep, FM, DeepFM, YouTubeRetrieval, YouTubeRanking, AutoInt, DIN, GraphSage, PinSage, and TwoTower.

    • Data Requirement: Must use libreco.data.dataset.DatasetFeat for data processing.
    • Required Parameters: When initializing a feat model, you must provide four specific parameters so the model can map the features: sparse_col, dense_col, user_col, and item_col.
  10. Perform temporal splits with chrono split functions

    master

    When working with time-series or sequential data where the order of interactions matters, use the 'chrono' variants of the split functions to ensure that training data precedes testing data in time. This prevents data leakage from the future into the past.

    Available functions:

    • libreco.data.split_by_ratio_chrono: Splits data by ratio while respecting temporal order.
    • libreco.data.split_by_num_chrono: Splits data by a fixed number of samples while respecting temporal order.
  11. Enable Online Computing Serving

    master

    Starting from version 1.2.0, LibRecommender supports online computing serving. Unlike offline precomputation, this allows recommendations to be generated in real-time based on dynamic user features or behavior sequences provided during the request.

    Model Compatibility

    Not all models support online computing. Use the following guide to choose a compatible model:

    • Supporting user features only: WideDeep, FM, DeepFM, AutoInt, TwoTower.
    • Supporting sequences only: RNN4Rec, Caser, WaveNet.
    • Supporting both features and sequences: YouTubeRetrieval, YouTubeRanking, DIN.
  12. Retrain deep learning models with new users or items

    master

    In deep learning models (like those using TensorFlow or PyTorch), embedding shapes are fixed after training. When new data arrives containing new users, items, or features, you cannot simply load the old model because the variable shapes will not match.

    LibRecommender solves this by extracting model variables as numpy.ndarray objects, allowing you to build a new model with expanded shapes and then map the old weights to the corresponding indices of the new variables. This preserves previous training progress while accommodating new entities.