Implementation:Recommenders team Recommenders Cornac BPR
| Knowledge Sources | |
|---|---|
| Domains | Recommendation Systems, Collaborative Filtering |
| Last Updated | 2026-02-10 00:00 GMT |
Overview
Extends the Cornac library's BPR (Bayesian Personalized Ranking) model with an efficient vectorized top-k recommendation method that returns results as a pandas DataFrame.
Description
The BPR class inherits from cornac.models.BPR and adds a recommend_k_items method for generating top-k item recommendations per user. Instead of scoring user-item pairs one at a time, the method computes all predictions simultaneously by multiplying user latent factor matrices (U) with item latent factor matrices (V) plus item biases (B) using the formula preds_matrix = U @ V.T + B. For efficient top-k selection, it uses np.argpartition to select the top-k items per user without fully sorting the entire prediction matrix. The method optionally removes previously seen user-item pairs from the training data by performing a left merge against the seen interactions.
Usage
Use this class when you need to generate top-k recommendations from a trained BPR model for evaluation with ranking metrics such as NDCG, MAP, or Precision@K. It bridges the Cornac BPR model with the recommenders library's pandas DataFrame-based evaluation pipeline.
Code Reference
Source Location
- Repository: Recommenders
- File: recommenders/models/cornac/bpr.py
- Lines: 1-83
Signature
class BPR(CBPR):
def __init__(self, *args, **kwargs)
def recommend_k_items(
self,
data,
top_k=None,
remove_seen=False,
col_user=DEFAULT_USER_COL,
col_item=DEFAULT_ITEM_COL,
col_prediction=DEFAULT_PREDICTION_COL,
)
Import
from recommenders.models.cornac.bpr import BPR
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| data | pandas.DataFrame | Yes | DataFrame containing user and item columns from which to derive the recommendation scope |
| top_k | int | No | Number of items to recommend per user; defaults to all items if None |
| remove_seen | bool | No | If True, removes (user, item) pairs already seen in training data from results |
| col_user | str | No | Name of the user column; defaults to DEFAULT_USER_COL |
| col_item | str | No | Name of the item column; defaults to DEFAULT_ITEM_COL |
| col_prediction | str | No | Name of the prediction score column; defaults to DEFAULT_PREDICTION_COL |
Outputs
| Name | Type | Description |
|---|---|---|
| return | pandas.DataFrame | DataFrame with columns (col_user, col_item, col_prediction) containing top-k predicted items per user sorted by score |
Usage Examples
Basic Usage
from recommenders.models.cornac.bpr import BPR
import cornac
# Train the BPR model
bpr_model = BPR(k=50, max_iter=100, learning_rate=0.001)
train_set = cornac.data.Dataset.from_uir(train_data.itertuples(index=False))
bpr_model.fit(train_set)
# Generate top-10 recommendations for all users
top_k_predictions = bpr_model.recommend_k_items(test_data, top_k=10, remove_seen=True)