Skip to content

Instantly share code, notes, and snippets.

@Chris-hughes10
Created December 9, 2021 07:39
Show Gist options
  • Save Chris-hughes10/dc2a77d7e78699bda07fe78dfdd1f0dc to your computer and use it in GitHub Desktop.
Save Chris-hughes10/dc2a77d7e78699bda07fe78dfdd1f0dc to your computer and use it in GitHub Desktop.
Recommender blog: matrix factorization model
import torch
from torch import nn
class MfDotBias(nn.Module):
def __init__(
self, n_factors, n_users, n_items, ratings_range=None, use_biases=True
):
super().__init__()
self.bias = use_biases
self.y_range = ratings_range
self.user_embedding = nn.Embedding(n_users+1, n_factors, padding_idx=0)
self.item_embedding = nn.Embedding(n_items+1, n_factors, padding_idx=0)
if use_biases:
self.user_bias = nn.Embedding(n_users+1, 1, padding_idx=0)
self.item_bias = nn.Embedding(n_items+1, 1, padding_idx=0)
def forward(self, inputs):
users, items = inputs
dot = self.user_embedding(users) * self.item_embedding(items)
result = dot.sum(1)
if self.bias:
result = (
result + self.user_bias(users).squeeze() + self.item_bias(items).squeeze()
)
if self.y_range is None:
return result
else:
return (
torch.sigmoid(result) * (self.y_range[1] - self.y_range[0])
+ self.y_range[0]
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment