DSSM

class rectools.models.dssm.DSSM(n_factors_user: int, n_factors_item: int, dim_input_user: int, dim_input_item: int, dim_interactions: int, activation: ~typing.Callable[[~torch.Tensor], ~torch.Tensor] = <function elu>, lr: float = 0.01, triplet_loss_margin: float = 0.4, weight_decay: float = 1e-06, log_to_prog_bar: bool = True)[source]

Bases: LightningModule

DSSM module for item to item or user to item recommendations. This implementation uses triplet loss (see https://en.wikipedia.org/wiki/Triplet_loss) as it’s objective function. As an input it expects one-hot encoded item features, one-hot encoded user features and one-hot encoded interactions. Those as easily extracted via rectools.dataset.Dataset. During the training cycle item features are propagated through fully connected item network, user features and interactions are propagated through fully connected user network.

Parameters
  • n_factors_user (int) – How many hidden units to use in user network.

  • n_factors_item (int) – How many hidden units to use in item network.

  • dim_input_user (int) – User features dimensionality.

  • dim_input_item (int) – Item features dimensionality.

  • dim_interactions (int) – Interactions dimensionality.

  • activation (Callable, default torch.nn.functional.elu) – Which activation function to use. This function must take a tensor and return a tensor

  • lr (float, default 0.01) – Learning rate.

  • triplet_loss_margin (float, default 0.4) – A nonnegative margin representing the minimum difference between the positive and negative distances required for the loss to be 0. Larger margins penalize cases where the negative examples are not distant enough from the anchors, relative to the positives.

  • weight_decay (float, default 1e-6) – weight decay (L2 penalty).

  • log_to_prog_bar (bool, default True) – Whether to enable logging train and validation losses to progress bar.

Methods

configure_optimizers()

Choose what optimizers and learning-rate schedulers to use in optimization

forward(item_features_pos, ...)

Same as torch.nn.Module.forward().

inference_items(dataloader)

inference_users(dataloader)

training_step(batch, batch_idx)

Compute and return the training loss

validation_step(batch, batch_idx)

Operates on a single batch of data from the validation set.

Attributes

configure_optimizers() Adam[source]

Choose what optimizers and learning-rate schedulers to use in optimization

Return type

Adam

forward(item_features_pos: Tensor, item_features_neg: Tensor, user_features: Tensor, interactions: Tensor) Tuple[Tensor, Tensor, Tensor][source]

Same as torch.nn.Module.forward().

Parameters
  • *args – Whatever you decide to pass into the forward method.

  • **kwargs – Keyword arguments are also possible.

  • item_features_pos (Tensor) –

  • item_features_neg (Tensor) –

  • user_features (Tensor) –

  • interactions (Tensor) –

Returns

Your model’s output

Return type

Tuple[Tensor, Tensor, Tensor]

training_step(batch: Sequence[Tensor], batch_idx: int) Tensor[source]

Compute and return the training loss

Parameters
  • batch (Sequence[Tensor]) –

  • batch_idx (int) –

Return type

Tensor

validation_step(batch: Sequence[Tensor], batch_idx: int) Tensor[source]

Operates on a single batch of data from the validation set. In this step you’d might generate examples or calculate anything of interest like accuracy.

Parameters
  • batch (Sequence[Tensor]) – The output of your data iterable, normally a DataLoader.

  • batch_idx (int) – The index of this batch.

  • dataloader_idx – The index of the dataloader that produced this batch. (only if multiple dataloaders used)

Returns

  • Tensor - The loss tensor

  • dict - A dictionary. Can include any keys, but must include the key 'loss'.

  • None - Skip to the next batch.

Return type

Tensor

# if you have one val dataloader:
def validation_step(self, batch, batch_idx): ...


# if you have multiple val dataloaders:
def validation_step(self, batch, batch_idx, dataloader_idx=0): ...

Examples:

# CASE 1: A single validation dataset
def validation_step(self, batch, batch_idx):
    x, y = batch

    # implement your own
    out = self(x)
    loss = self.loss(out, y)

    # log 6 example images
    # or generated text... or whatever
    sample_imgs = x[:6]
    grid = torchvision.utils.make_grid(sample_imgs)
    self.logger.experiment.add_image('example_images', grid, 0)

    # calculate acc
    labels_hat = torch.argmax(out, dim=1)
    val_acc = torch.sum(y == labels_hat).item() / (len(y) * 1.0)

    # log the outputs!
    self.log_dict({'val_loss': loss, 'val_acc': val_acc})

If you pass in multiple val dataloaders, validation_step() will have an additional argument. We recommend setting the default value of 0 so that you can quickly switch between single and multiple dataloaders.

# CASE 2: multiple validation dataloaders
def validation_step(self, batch, batch_idx, dataloader_idx=0):
    # dataloader_idx tells you which dataset this is.
    ...

Note

If you don’t need to validate you don’t need to implement this method.

Note

When the validation_step() is called, the model has been put in eval mode and PyTorch gradients have been disabled. At the end of validation, the model goes back to training mode and gradients are enabled.