Skip to content

Random recommender implementation #5

@paraschakis

Description

@paraschakis

Just reporting that the Random recommender has the same issue as in #4.

As an alternative, I want to share my implementation of the Random recommender, which I found to be faster and more concise.
It replaces parameter 'K' with parameter 'density'.

from collections import Counter
import random
import sys

import numpy as np
from scipy.sparse import csr_matrix, random as random_matrix


from recpack.algorithms.base import Algorithm


class Random(Algorithm):
    """Uniform random algorithm, each item has an equal chance of getting recommended.

    Simple baseline, recommendations are sampled uniformly without replacement
    from the items that were interacted with in the matrix provided to fit.
    Scores are given based on sampling rank, such that the items first
    in the sample has the highest score

    :param density: The density of a random matrix, defaults to 1.0 (fully dense)
    :type density: float, optional
    :param seed: Seed for the random number generator used, defaults to None
    :type seed: int, optional
    :param use_only_interacted_items: Should only items visited in the training
        matrix be used to recommend from. If False all items will be recommended
        uniformly at random.
        Defaults to True.
    :type use_only_interacted_items: boolean, optional
    """

    def __init__(self, density=1.0, seed=None, use_only_interacted_items=True):
        super().__init__()
        self.density = density
        self.use_only_interacted_items = use_only_interacted_items

        if seed is None:
            seed = random.randrange(sys.maxsize)
        random.seed(seed)
        self.seed = seed

    def _fit(self, X: csr_matrix):
        self.random_matrix_ = random_matrix(*X.shape, self.density, format='csr')
        if self.use_only_interacted_items:
            I = list(set(X.nonzero()[1]))
            X_mask = np.zeros(X.shape, dtype=bool)
            X_mask[:, I] = True
            self.random_matrix_ = self.random_matrix_.multiply(X_mask).tocsr()

    def _predict(self, X: csr_matrix):
        """Predicts random scores for items per user.

        Returns numpy array of the same shape as X,
        with random scores for items.
        """

        return self.random_matrix_

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions