プリンキピア

第21章推薦システム

21.3.2. Model Implementation21.3.2 モデルの実装

First, we implement the matrix factorization model described above. The user and item latent factors can be created with the nn.Embedding. The input_dim is the number of items/users and the output_dim is the dimension of the latent factors k. We can also use nn.Embedding to create the user/item biases by setting the output_dim to one. In the forward function, user and item ids are used to look up the embeddings.
英語のヒント
まず、上で述べた行列分解のモデルを実装する。利用者とアイテムの潜在因子は、nn.Embeddingで作れる。input_dimはアイテムや利用者の数で、output_dimは潜在因子の次元kである。output_dimを1に設定すれば、nn.Embeddingで利用者やアイテムのバイアスを作ることもできる。forward関数では、利用者とアイテムのIDを使って埋め込みを引く。
class MF(nn.Block):
    def __init__(self, num_factors, num_users, num_items, **kwargs):
        super(MF, self).__init__(**kwargs)
        self.P = nn.Embedding(input_dim=num_users, output_dim=num_factors)
        self.Q = nn.Embedding(input_dim=num_items, output_dim=num_factors)
        self.user_bias = nn.Embedding(num_users, 1)
        self.item_bias = nn.Embedding(num_items, 1)

    def forward(self, user_id, item_id):
        P_u = self.P(user_id)
        Q_i = self.Q(item_id)
        b_u = self.user_bias(user_id)
        b_i = self.item_bias(item_id)
        outputs = (P_u * Q_i).sum(axis=1) + np.squeeze(b_u) + np.squeeze(b_i)
        return outputs.flatten()