File size: 6,121 Bytes
e89a301 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 | import copy
import torch
import random
from utils import neg_sample, nCr
from torch.utils.data import Dataset
from data_augmentation import Crop, Mask, Reorder, Random
class RecWithContrastiveLearningDataset(Dataset):
def __init__(self, args, user_seq, test_neg_items=None, data_type="train"):
self.args = args
self.user_seq = user_seq
self.test_neg_items = test_neg_items
self.data_type = data_type
self.max_len = args.max_seq_length
self.augmentations = {
"crop": Crop(tao=args.tao),
"mask": Mask(gamma=args.gamma),
"reorder": Reorder(beta=args.beta),
"random": Random(tao=args.tao, gamma=args.gamma, beta=args.beta),
}
if self.args.augment_type not in self.augmentations:
raise ValueError(f"augmentation type: '{self.args.augment_type}' is invalided")
print(f"Creating Contrastive Learning Dataset using '{self.args.augment_type}' data augmentation")
self.base_transform = self.augmentations[self.args.augment_type]
self.n_views = self.args.n_views
def _one_pair_data_augmentation(self, input_ids):
augmented_seqs = []
for i in range(2):
augmented_input_ids = self.base_transform(input_ids)
pad_len = self.max_len - len(augmented_input_ids)
augmented_input_ids = [0] * pad_len + augmented_input_ids
augmented_input_ids = augmented_input_ids[-self.max_len :]
assert len(augmented_input_ids) == self.max_len
cur_tensors = torch.tensor(augmented_input_ids, dtype=torch.long)
augmented_seqs.append(cur_tensors)
return augmented_seqs
def _process_sequence_label_signal(self, seq_label_signal):
seq_class_label = torch.tensor(seq_label_signal, dtype=torch.long)
return seq_class_label
def _data_sample_rec_task(self, user_id, items, input_ids, target_pos, answer):
copied_input_ids = copy.deepcopy(input_ids)
target_neg = []
seq_set = set(items)
for _ in copied_input_ids:
target_neg.append(neg_sample(seq_set, self.args.item_size))
pad_len = self.max_len - len(copied_input_ids)
copied_input_ids = [0] * pad_len + copied_input_ids
target_pos = [0] * pad_len + target_pos
target_neg = [0] * pad_len + target_neg
copied_input_ids = copied_input_ids[-self.max_len :]
target_pos = target_pos[-self.max_len :]
target_neg = target_neg[-self.max_len :]
assert len(copied_input_ids) == self.max_len
assert len(target_pos) == self.max_len
assert len(target_neg) == self.max_len
if self.test_neg_items is not None:
test_samples = self.test_neg_items[index]
cur_rec_tensors = (
torch.tensor(user_id, dtype=torch.long), # user_id for testing
torch.tensor(copied_input_ids, dtype=torch.long),
torch.tensor(target_pos, dtype=torch.long),
torch.tensor(target_neg, dtype=torch.long),
torch.tensor(answer, dtype=torch.long),
torch.tensor(test_samples, dtype=torch.long),
)
else:
cur_rec_tensors = (
torch.tensor(user_id, dtype=torch.long), # user_id for testing
torch.tensor(copied_input_ids, dtype=torch.long),
torch.tensor(target_pos, dtype=torch.long),
torch.tensor(target_neg, dtype=torch.long),
torch.tensor(answer, dtype=torch.long),
)
return cur_rec_tensors
def _add_noise_interactions(self, items):
copied_sequence = copy.deepcopy(items)
insert_nums = max(int(self.args.noise_ratio * len(copied_sequence)), 0)
if insert_nums == 0:
return copied_sequence
insert_idx = random.choices([i for i in range(len(copied_sequence))], k=insert_nums)
inserted_sequence = []
for index, item in enumerate(copied_sequence):
if index in insert_idx:
item_id = random.randint(1, self.args.item_size - 2)
while item_id in copied_sequence:
item_id = random.randint(1, self.args.item_size - 2)
inserted_sequence += [item_id]
inserted_sequence += [item]
return inserted_sequence
def __getitem__(self, index):
user_id = index
items = self.user_seq[index]
assert self.data_type in {"train", "valid", "test"}
if self.data_type == "train":
input_ids = items[:-3]
target_pos = items[1:-2]
seq_label_signal = items[-2]
answer = [0] # no use
elif self.data_type == "valid":
input_ids = items[:-2]
target_pos = items[1:-1]
answer = [items[-2]]
else:
items_with_noise = self._add_noise_interactions(items)
input_ids = items_with_noise[:-1]
target_pos = items_with_noise[1:]
answer = [items_with_noise[-1]]
if self.data_type == "train":
cur_rec_tensors = self._data_sample_rec_task(user_id, items, input_ids, target_pos, answer)
cf_tensors_list = []
total_augmentaion_pairs = nCr(self.n_views, 2)
for i in range(total_augmentaion_pairs):
cf_tensors_list.append(self._one_pair_data_augmentation(input_ids))
seq_class_label = self._process_sequence_label_signal(seq_label_signal)
return (cur_rec_tensors, cf_tensors_list, seq_class_label)
elif self.data_type == "valid":
cur_rec_tensors = self._data_sample_rec_task(user_id, items, input_ids, target_pos, answer)
return cur_rec_tensors
else:
cur_rec_tensors = self._data_sample_rec_task(user_id, items_with_noise, input_ids, target_pos, answer)
return cur_rec_tensors
def __len__(self):
"""
consider n_view of a single sequence as one sample
"""
return len(self.user_seq)
|