|
| 1 | +import torch |
| 2 | +from torch import nn |
| 3 | + |
| 4 | + |
| 5 | +class BaseLoss(nn.Module): |
| 6 | + """Class of abstract loss module for pairwise loss like matrix factorization.""" |
| 7 | + |
| 8 | + def __init__(self, regularizers: list = []): |
| 9 | + super().__init__() |
| 10 | + self.regularizers = regularizers |
| 11 | + |
| 12 | + def forward( |
| 13 | + self, embeddings_dict: dict, batch: torch.Tensor, column_names: dict |
| 14 | + ) -> torch.Tensor: |
| 15 | + loss = self.main(embeddings_dict, batch, column_names) |
| 16 | + loss += self.regularize(embeddings_dict) |
| 17 | + return loss |
| 18 | + |
| 19 | + def main( |
| 20 | + self, embeddings_dict: dict, batch: torch.Tensor, column_names: dict |
| 21 | + ) -> torch.Tensor: |
| 22 | + """ |
| 23 | + Args: |
| 24 | + embeddings_dict (dict): A dictionary of embddings. |
| 25 | + (e.g. It has following key and values.) |
| 26 | + user_embedding : embeddings of user, size (n_batch, 1, d) |
| 27 | + pos_item_embedding : embeddings of positive item, size (n_batch, 1, d) |
| 28 | + neg_item_embedding : embeddings of negative item, size (n_batch, n_neg_samples, d) |
| 29 | + user_bias : bias of user, size (n_batch, 1) |
| 30 | + pos_item_bias : bias of positive item, size (n_batch, 1) |
| 31 | + neg_item_bias : bias of negative item, size (n_batch, n_neg_samples) |
| 32 | +
|
| 33 | + batch (torch.Tensor) : A tensor of batch, size (n_batch, *). |
| 34 | + column_names (dict) : A dictionary that maps names to indices of rows of batch. |
| 35 | +
|
| 36 | + Raises: |
| 37 | + NotImplementedError: [description] |
| 38 | +
|
| 39 | + Returns: |
| 40 | + torch.Tensor: [description] |
| 41 | +
|
| 42 | + --- example code --- |
| 43 | +
|
| 44 | + embeddings_dict = { |
| 45 | + "user_embedding": user_embedding, |
| 46 | + "pos_item_embedding": pos_item_embedding, |
| 47 | + "neg_item_embedding": neg_item_embedding, |
| 48 | + "user_bias": user_bias, |
| 49 | + "pos_item_bias": pos_item_bias, |
| 50 | + "neg_item_bias": neg_item_bias, |
| 51 | + } |
| 52 | +
|
| 53 | + loss = loss_function(embeddings_dict, batch, column_names) |
| 54 | +
|
| 55 | + return loss |
| 56 | + """ |
| 57 | + |
| 58 | + raise NotImplementedError |
| 59 | + |
| 60 | + def regularize(self, embeddings_dict: dict): |
| 61 | + reg = 0 |
| 62 | + for regularizer in self.regularizers: |
| 63 | + reg += regularizer(embeddings_dict) |
| 64 | + |
| 65 | + return reg |
0 commit comments