プリンキピア

第21章推薦システム

21.6.3. Customized Dataset with Negative Sampling21.6.3 負例サンプリングを行うカスタムデータセット

For pairwise ranking loss, an important step is negative sampling. For each user, the items that a user has not interacted with are candidate items (unobserved entries). The following function takes users identity and candidate items as input, and samples negative items randomly for each user from the candidate set of that user. During the training stage, the model ensures that the items that a user likes to be ranked higher than items he dislikes or has not interacted with.
英語のヒント
ペアワイズのランキング損失では、重要な手順の一つが負例サンプリングである。各利用者について、その利用者がやりとりしたことのないアイテムが候補アイテム(観測されていない成分)である。次の関数は、利用者のIDと候補アイテムを入力として受け取り、各利用者について、その利用者の候補集合から負例のアイテムをランダムに抽出する。訓練の段階では、モデルは、利用者が好むアイテムが、利用者が嫌う、あるいはやりとりしたことのないアイテムより上位に順位づけされるようにする。
class PRDataset(gluon.data.Dataset):
    def __init__(self, users, items, candidates, num_items):
        self.users = users
        self.items = items
        self.cand = candidates
        self.all = set([i for i in range(num_items)])

    def __len__(self):
        return len(self.users)

    def __getitem__(self, idx):
        neg_items = list(self.all - set(self.cand[int(self.users[idx])]))
        indices = random.randint(0, len(neg_items) - 1)
        return self.users[idx], self.items[idx], neg_items[indices]