Skip to content

Unpersonalized - API Reference

Auto-generated documentation for unpersonalized recommender model classes.

warprec.recommenders.unpersonalized_recommender.pop.Pop

Bases: Recommender

Definition of Popularity unpersonalized model.

This model will recommend items based on their popularity, ensuring that previously seen items are not recommended again.

Parameters:

Name Type Description Default
params dict

The dictionary with the model params.

required
info dict

The dictionary containing dataset information.

required
interactions Interactions

The training interactions.

required
*args Any

Argument for PyTorch nn.Module.

()
seed int

The seed to use for reproducibility.

42
**kwargs Any

Keyword argument for PyTorch nn.Module.

{}
Source code in warprec/recommenders/unpersonalized_recommender/pop.py
@model_registry.register(name="Pop")
class Pop(Recommender):
    """Definition of Popularity unpersonalized model.

    This model will recommend items based on their popularity,
    ensuring that previously seen items are not recommended again.

    Args:
        params (dict): The dictionary with the model params.
        info (dict): The dictionary containing dataset information.
        interactions (Interactions): The training interactions.
        *args (Any): Argument for PyTorch nn.Module.
        seed (int): The seed to use for reproducibility.
        **kwargs (Any): Keyword argument for PyTorch nn.Module.
    """

    def __init__(
        self,
        params: dict,
        info: dict,
        interactions: Interactions,
        *args: Any,
        seed: int = 42,
        **kwargs: Any,
    ):
        super().__init__(params, info, *args, seed=seed, **kwargs)

        X = interactions.get_sparse()

        # Count the number of items to define the popularity
        popularity = torch.tensor(X.sum(axis=0).A1, dtype=torch.float32)
        # Count the total number of interactions
        item_count = torch.tensor(X.sum(), dtype=torch.float32)

        # Normalize popularity by the total number of interactions
        # Add epsilon to avoid division by zero if there are no interactions
        norm_pop = popularity / (item_count + 1e-6)
        self.register_buffer("normalized_popularity", norm_pop)

    @classmethod
    def estimate_space(
        cls,
        params: dict,
        info: dict,
        interactions: Optional[Interactions] = None,
        **kwargs: Any,
    ) -> dict:
        interactions = cls._require_interactions_for_estimate(
            interactions, cls.__name__
        )
        X = interactions.get_sparse()
        train_ram_mb = cls._sparse_size_mb(X)
        train_ram_mb += cls._dense_size_mb((info["n_items"],), np.float32)
        train_ram_mb += cls._dense_size_mb((1,), np.float32)
        return {
            "train_ram_mb": train_ram_mb,
            "notes": "Pop analytical train-space estimate",
        }

    def predict(
        self,
        user_indices: Tensor,
        *args: Any,
        item_indices: Optional[Tensor] = None,
        **kwargs: Any,
    ) -> Tensor:
        """Prediction using a normalized popularity value.

        Args:
            user_indices (Tensor): The batch of user indices.
            *args (Any): List of arguments.
            item_indices (Optional[Tensor]): The batch of item indices. If None,
                full prediction will be produced.
            **kwargs (Any): The dictionary of keyword arguments.

        Returns:
            Tensor: The score matrix {user x item}.
        """
        if item_indices is None:
            # Case 'full': prediction on all items
            batch_size = user_indices.size(0)

            # Expand the popularity scores for each user in the batch
            return self.normalized_popularity.expand(batch_size, -1).clone()  # type: ignore[operator]

        # Case 'sampled': prediction on a sampled set of items
        return self.normalized_popularity[item_indices.clamp(max=self.n_items - 1)]  # type: ignore[index, operator]

predict(user_indices, *args, item_indices=None, **kwargs)

Prediction using a normalized popularity value.

Parameters:

Name Type Description Default
user_indices Tensor

The batch of user indices.

required
*args Any

List of arguments.

()
item_indices Optional[Tensor]

The batch of item indices. If None, full prediction will be produced.

None
**kwargs Any

The dictionary of keyword arguments.

{}

Returns:

Name Type Description
Tensor Tensor

The score matrix {user x item}.

Source code in warprec/recommenders/unpersonalized_recommender/pop.py
def predict(
    self,
    user_indices: Tensor,
    *args: Any,
    item_indices: Optional[Tensor] = None,
    **kwargs: Any,
) -> Tensor:
    """Prediction using a normalized popularity value.

    Args:
        user_indices (Tensor): The batch of user indices.
        *args (Any): List of arguments.
        item_indices (Optional[Tensor]): The batch of item indices. If None,
            full prediction will be produced.
        **kwargs (Any): The dictionary of keyword arguments.

    Returns:
        Tensor: The score matrix {user x item}.
    """
    if item_indices is None:
        # Case 'full': prediction on all items
        batch_size = user_indices.size(0)

        # Expand the popularity scores for each user in the batch
        return self.normalized_popularity.expand(batch_size, -1).clone()  # type: ignore[operator]

    # Case 'sampled': prediction on a sampled set of items
    return self.normalized_popularity[item_indices.clamp(max=self.n_items - 1)]  # type: ignore[index, operator]

warprec.recommenders.unpersonalized_recommender.random.Random

Bases: Recommender

Definition of Random unpersonalized model. This model will recommend items based on a random number generator.

Source code in warprec/recommenders/unpersonalized_recommender/random.py
@model_registry.register(name="Random")
class Random(Recommender):
    """Definition of Random unpersonalized model.
    This model will recommend items based on a random number generator.
    """

    @classmethod
    def estimate_space(
        cls,
        params: dict,
        info: dict,
        interactions: Optional[Interactions] = None,
        **kwargs: Any,
    ) -> dict:
        return {
            "train_ram_mb": 0.0,
            "notes": "Random analytical train-space estimate",
        }

    def predict(
        self,
        user_indices: Tensor,
        *args: Any,
        item_indices: Optional[Tensor] = None,
        **kwargs: Any,
    ) -> Tensor:
        """Prediction using a normalized popularity value.

        Args:
            user_indices (Tensor): The batch of user indices.
            *args (Any): List of arguments.
            item_indices (Optional[Tensor]): The batch of item indices. If None,
                full prediction will be produced.
            **kwargs (Any): The dictionary of keyword arguments.

        Returns:
            Tensor: The score matrix {user x item}.
        """
        if item_indices is None:
            # Case 'full': prediction on all items
            batch_size = user_indices.size(0)
            shape = (batch_size, self.n_items)

            # Generate random scores
            return torch.rand(shape)  # [batch_size, n_items]

        # Case 'sampled': prediction on a sampled set of items
        return torch.rand(item_indices.size())  # [batch_size, pad_seq]

predict(user_indices, *args, item_indices=None, **kwargs)

Prediction using a normalized popularity value.

Parameters:

Name Type Description Default
user_indices Tensor

The batch of user indices.

required
*args Any

List of arguments.

()
item_indices Optional[Tensor]

The batch of item indices. If None, full prediction will be produced.

None
**kwargs Any

The dictionary of keyword arguments.

{}

Returns:

Name Type Description
Tensor Tensor

The score matrix {user x item}.

Source code in warprec/recommenders/unpersonalized_recommender/random.py
def predict(
    self,
    user_indices: Tensor,
    *args: Any,
    item_indices: Optional[Tensor] = None,
    **kwargs: Any,
) -> Tensor:
    """Prediction using a normalized popularity value.

    Args:
        user_indices (Tensor): The batch of user indices.
        *args (Any): List of arguments.
        item_indices (Optional[Tensor]): The batch of item indices. If None,
            full prediction will be produced.
        **kwargs (Any): The dictionary of keyword arguments.

    Returns:
        Tensor: The score matrix {user x item}.
    """
    if item_indices is None:
        # Case 'full': prediction on all items
        batch_size = user_indices.size(0)
        shape = (batch_size, self.n_items)

        # Generate random scores
        return torch.rand(shape)  # [batch_size, n_items]

    # Case 'sampled': prediction on a sampled set of items
    return torch.rand(item_indices.size())  # [batch_size, pad_seq]