プリンキピア

第21章推薦システム

21.2.3. Splitting the dataset21.2.3 データセットを分割する

We split the dataset into training and test sets. The following function provides two split modes including random and seq-aware. In the random mode, the function splits the 100k interactions randomly without considering timestamp and uses the 90% of the data as training samples and the rest 10% as test samples by default. In the seq-aware mode, we leave out the item that a user rated most recently for test, and users’ historical interactions as training set. User historical interactions are sorted from oldest to newest based on timestamp. This mode will be used in the sequence-aware recommendation section.
英語のヒント
データセットを訓練集合とテスト集合に分割する。次の関数は、randomとseq-awareの二つの分割モードを用意している。randomモードでは、この関数はタイムスタンプを考えずに100kのやりとりをランダムに分割し、既定ではデータの90%を訓練の標本、残りの10%をテストの標本として使う。seq-awareモードでは、利用者が最も最近評価したアイテムをテスト用に取り分け、利用者の過去のやりとりを訓練集合とする。利用者の過去のやりとりは、タイムスタンプにもとづいて古いものから新しいものへ並べられる。このモードは、系列を考慮した推薦の節で使う。
#@save
def split_data_ml100k(data, num_users, num_items,
                      split_mode='random', test_ratio=0.1):
    """Split the dataset in random mode or seq-aware mode."""
    if split_mode == 'seq-aware':
        train_items, test_items, train_list = {}, {}, []
        for line in data.itertuples():
            u, i, rating, time = line[1], line[2], line[3], line[4]
            train_items.setdefault(u, []).append((u, i, rating, time))
            if u not in test_items or test_items[u][-1] < time:
                test_items[u] = (i, rating, time)
        for u in range(1, num_users + 1):
            train_list.extend(sorted(train_items[u], key=lambda k: k[3]))
        test_data = [(key, *value) for key, value in test_items.items()]
        train_data = [item for item in train_list if item not in test_data]
        train_data = pd.DataFrame(train_data)
        test_data = pd.DataFrame(test_data)
    else:
        mask = [True if x == 1 else False for x in np.random.uniform(
            0, 1, (len(data))) < 1 - test_ratio]
        neg_mask = [not x for x in mask]
        train_data, test_data = data[mask], data[neg_mask]
    return train_data, test_data
Note that it is good practice to use a validation set in practice, apart from only a test set. However, we omit that for the sake of brevity. In this case, our test set can be regarded as our held-out validation set.
英語のヒント
実際には、テスト集合だけでなく検証集合も使うのがよいやり方であることに注意しよう。しかし、簡潔にするため、ここではそれを省く。この場合、テスト集合は取り置いた検証集合とみなせる。