|
| 1 | +# Copyright (c) 2018, deepakn94, codyaustun, robieta. All rights reserved. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | +# |
| 15 | +# ----------------------------------------------------------------------- |
| 16 | +# |
| 17 | +# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. |
| 18 | +# |
| 19 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 20 | +# you may not use this file except in compliance with the License. |
| 21 | +# You may obtain a copy of the License at |
| 22 | +# |
| 23 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 24 | +# |
| 25 | +# Unless required by applicable law or agreed to in writing, software |
| 26 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 27 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 28 | +# See the License for the specific language governing permissions and |
| 29 | +# limitations under the License. |
| 30 | + |
| 31 | +from argparse import ArgumentParser |
| 32 | +import pandas as pd |
| 33 | +import numpy as np |
| 34 | +from load import implicit_load |
| 35 | +from convert import save_feature_spec, _TestNegSampler, TEST_0, TEST_1, TRAIN_0, TRAIN_1 |
| 36 | +import torch |
| 37 | +import os |
| 38 | + |
| 39 | +USER_COLUMN = 'user_id' |
| 40 | +ITEM_COLUMN = 'item_id' |
| 41 | + |
| 42 | + |
| 43 | +def parse_args(): |
| 44 | + parser = ArgumentParser() |
| 45 | + parser.add_argument('--path', type=str, default='/data/ml-20m/ratings.csv', |
| 46 | + help='Path to reviews CSV file from MovieLens') |
| 47 | + parser.add_argument('--output', type=str, default='/data', |
| 48 | + help='Output directory for train and test files') |
| 49 | + parser.add_argument('--valid_negative', type=int, default=100, |
| 50 | + help='Number of negative samples for each positive test example') |
| 51 | + parser.add_argument('--seed', '-s', type=int, default=1, |
| 52 | + help='Manually set random seed for torch') |
| 53 | + parser.add_argument('--test', type=str, help='select modification to be applied to the set') |
| 54 | + return parser.parse_args() |
| 55 | + |
| 56 | + |
| 57 | +def main(): |
| 58 | + args = parse_args() |
| 59 | + |
| 60 | + if args.seed is not None: |
| 61 | + torch.manual_seed(args.seed) |
| 62 | + |
| 63 | + print("Loading raw data from {}".format(args.path)) |
| 64 | + df = implicit_load(args.path, sort=False) |
| 65 | + |
| 66 | + if args.test == 'less_user': |
| 67 | + to_drop = set(list(df[USER_COLUMN].unique())[-100:]) |
| 68 | + df = df[~df[USER_COLUMN].isin(to_drop)] |
| 69 | + if args.test == 'less_item': |
| 70 | + to_drop = set(list(df[ITEM_COLUMN].unique())[-100:]) |
| 71 | + df = df[~df[ITEM_COLUMN].isin(to_drop)] |
| 72 | + if args.test == 'more_user': |
| 73 | + sample = df.sample(frac=0.2).copy() |
| 74 | + sample[USER_COLUMN] = sample[USER_COLUMN] + 10000000 |
| 75 | + df = df.append(sample) |
| 76 | + users = df[USER_COLUMN] |
| 77 | + df = df[users.isin(users[users.duplicated(keep=False)])] # make sure something remains in the train set |
| 78 | + if args.test == 'more_item': |
| 79 | + sample = df.sample(frac=0.2).copy() |
| 80 | + sample[ITEM_COLUMN] = sample[ITEM_COLUMN] + 10000000 |
| 81 | + df = df.append(sample) |
| 82 | + |
| 83 | + print("Mapping original user and item IDs to new sequential IDs") |
| 84 | + df[USER_COLUMN] = pd.factorize(df[USER_COLUMN])[0] |
| 85 | + df[ITEM_COLUMN] = pd.factorize(df[ITEM_COLUMN])[0] |
| 86 | + |
| 87 | + user_cardinality = df[USER_COLUMN].max() + 1 |
| 88 | + item_cardinality = df[ITEM_COLUMN].max() + 1 |
| 89 | + |
| 90 | + # Need to sort before popping to get last item |
| 91 | + df.sort_values(by='timestamp', inplace=True) |
| 92 | + |
| 93 | + # clean up data |
| 94 | + del df['rating'], df['timestamp'] |
| 95 | + df = df.drop_duplicates() # assuming it keeps order |
| 96 | + |
| 97 | + # Test set is the last interaction for a given user |
| 98 | + grouped_sorted = df.groupby(USER_COLUMN, group_keys=False) |
| 99 | + test_data = grouped_sorted.tail(1).sort_values(by=USER_COLUMN) |
| 100 | + # Train set is all interactions but the last one |
| 101 | + train_data = grouped_sorted.apply(lambda x: x.iloc[:-1]) |
| 102 | + |
| 103 | + sampler = _TestNegSampler(train_data.values, args.valid_negative) |
| 104 | + test_negs = sampler.generate().cuda() |
| 105 | + if args.valid_negative > 0: |
| 106 | + test_negs = test_negs.reshape(-1, args.valid_negative) |
| 107 | + else: |
| 108 | + test_negs = test_negs.reshape(test_data.shape[0], 0) |
| 109 | + |
| 110 | + if args.test == 'more_pos': |
| 111 | + mask = np.random.rand(len(test_data)) < 0.5 |
| 112 | + sample = test_data[mask].copy() |
| 113 | + sample[ITEM_COLUMN] = sample[ITEM_COLUMN] + 5 |
| 114 | + test_data = test_data.append(sample) |
| 115 | + test_negs_copy = test_negs[mask] |
| 116 | + test_negs = torch.cat((test_negs, test_negs_copy), dim=0) |
| 117 | + if args.test == 'less_pos': |
| 118 | + mask = np.random.rand(len(test_data)) < 0.5 |
| 119 | + test_data = test_data[mask] |
| 120 | + test_negs = test_negs[mask] |
| 121 | + |
| 122 | + # Reshape train set into user,item,label tabular and save |
| 123 | + train_ratings = torch.from_numpy(train_data.values).cuda() |
| 124 | + train_labels = torch.ones_like(train_ratings[:, 0:1], dtype=torch.float32) |
| 125 | + torch.save(train_ratings, os.path.join(args.output, TRAIN_0)) |
| 126 | + torch.save(train_labels, os.path.join(args.output, TRAIN_1)) |
| 127 | + |
| 128 | + # Reshape test set into user,item,label tabular and save |
| 129 | + # All users have the same number of items, items for a given user appear consecutively |
| 130 | + test_ratings = torch.from_numpy(test_data.values).cuda() |
| 131 | + test_users_pos = test_ratings[:, 0:1] # slicing instead of indexing to keep dimensions |
| 132 | + test_items_pos = test_ratings[:, 1:2] |
| 133 | + test_users = test_users_pos.repeat_interleave(args.valid_negative + 1, dim=0) |
| 134 | + test_items = torch.cat((test_items_pos.reshape(-1, 1), test_negs), dim=1).reshape(-1, 1) |
| 135 | + positive_labels = torch.ones_like(test_users_pos, dtype=torch.float32) |
| 136 | + negative_labels = torch.zeros_like(test_users_pos, dtype=torch.float32).repeat(1, args.valid_negative) |
| 137 | + test_labels = torch.cat((positive_labels, negative_labels), dim=1).reshape(-1, 1) |
| 138 | + dtypes = {'user': str(test_users.dtype), 'item': str(test_items.dtype), 'label': str(test_labels.dtype)} |
| 139 | + test_tensor = torch.cat((test_users, test_items), dim=1) |
| 140 | + torch.save(test_tensor, os.path.join(args.output, TEST_0)) |
| 141 | + torch.save(test_labels, os.path.join(args.output, TEST_1)) |
| 142 | + |
| 143 | + if args.test == 'other_names': |
| 144 | + dtypes = {'user_2': str(test_users.dtype), |
| 145 | + 'item_2': str(test_items.dtype), |
| 146 | + 'label_2': str(test_labels.dtype)} |
| 147 | + save_feature_spec(user_cardinality=user_cardinality, item_cardinality=item_cardinality, dtypes=dtypes, |
| 148 | + test_negative_samples=args.valid_negative, output_path=args.output + '/feature_spec.yaml', |
| 149 | + user_feature_name='user_2', |
| 150 | + item_feature_name='item_2', |
| 151 | + label_feature_name='label_2') |
| 152 | + else: |
| 153 | + save_feature_spec(user_cardinality=user_cardinality, item_cardinality=item_cardinality, dtypes=dtypes, |
| 154 | + test_negative_samples=args.valid_negative, output_path=args.output + '/feature_spec.yaml') |
| 155 | + |
| 156 | + |
| 157 | +if __name__ == '__main__': |
| 158 | + main() |
0 commit comments