Algorithm Interfaces

LKPY’s batch routines and utility support for managing algorithms expect algorithms to implement consistent interfaces. This page describes those interfaces.

The interfaces are realized as abstract base classes with the Python abc module. Implementations must be registered with their interfaces, either by subclassing the interface or by calling abc.ABCMeta.register().

Rating Prediction

class lenskit.algorithms.Predictor

Predicts user ratings of items. Predictions are really estimates of the user’s like or dislike, and the Predictor interface makes no guarantees about their scale or granularity.

predict(model, user, items, ratings=None)

Compute predictions for a user and items.

  • model – the trained model to use. Either None or the ratings matrix if the algorithm has no concept of training.
  • user – the user ID
  • items (array-like) – the items to predict
  • ratings (pandas.Series) – the user’s ratings (indexed by item id); if provided, they may be used to override or augment the model’s notion of a user’s preferences.

scores for the items, indexed by item id.

Return type:


Model Training

Most algorithms have some concept of a trained model. The Trainable interface captures the ability of a model to be trained and saved to disk.

class lenskit.algorithms.Trainable

Models that can be trained and have their models saved.


Train the model on rating/consumption data. Training methods that require additional data may accept it as additional parameters or via class members.

Parameters:ratings (pandas.DataFrame) – rating data, as a matrix with columns ‘user’, ‘item’, and ‘rating’. The user and item identifiers may be of any type.
Returns:the trained model (of an implementation-defined type).
save_model(model, file)

Save a trained model to a file. The default implementation pickles the model.

Algorithms are allowed to use any format for saving their models, including directories.

  • model – the trained model.
  • file (str) – the file in which to save the model.

Save a trained model to a file.

Parameters:file (str) – the path to file from which to load the model.
Returns:the re-loaded model (of an implementation-defined type).