RECODE-H / annotations /annotation_39 /BASRec /GRU4Rec /src /data_augmentation.py
mcy98's picture
Upload folder using huggingface_hub
6077218 verified
Raw History Blame Contribute Delete
9.71 kB
import copy
import random
import numpy as np
class Random(object):
"""
Randomly pick and apply one data augmentation operator (either Reorder or Substitute).
This class is designed to diversify the types of augmentation applied to a sequence
on each call, increasing diversity as encouraged in the BASRec framework.
Correspondence to Paper:
- This mechanism is not explicitly mentioned in the BASRec paper, but
it serves the practical goal of sampling diverse augmentations, which
is consistent with the spirit of the paper's focus on balancing relevance and diversity.
Args:
item_similarity_model: Model for computing item similarity (used by Substitute).
rate_min, rate_max: Lower/upper bounds for proportion of sequence to augment (Uniform(a, b) in paper).
"""
def __init__(self, item_similarity_model, rate_min, rate_max):
self.data_augmentation_methods = [Reorder(rate_min, rate_max),
Substitute(item_similarity_model, rate_min, rate_max)]
print("Total augmentation numbers: ", len(self.data_augmentation_methods))
def __call__(self, sequence):
# Randomly select either Reorder or Substitute for augmentation
augment_method_idx = random.randint(0, len(self.data_augmentation_methods) - 1)
augment_method = self.data_augmentation_methods[augment_method_idx]
return augment_method(sequence)
# === Appended from canonical.py ===
# -*- coding: utf-8 -*-
import copy
import random
import numpy as np
from .data_augmentation import Random
################################################################################
# BASRec Data Augmentation Operators - Correspondence with Paper
#
# This file implements the core *single-sequence augmentation* operators
# described in "Augmenting Sequential Recommendation with Balanced Relevance and Diversity" (BASRec).
#
# The two operators below, M-Reorder and M-Substitute, are directly aligned
# with Section "Ours: BASRec" and the "Single-sequence Augmentation" part of the paper.
#
# - M-Reorder: Randomly shuffles a contiguous sub-sequence within a user's item sequence.
# (See Eq. 4, Eq. 5 in the paper.)
#
# - M-Substitute: Randomly substitutes items within a user's sequence with similar items,
# where similarity is determined by an external similarity model.
# (See Eq. 4, Eq. 8 in the paper.)
#
# Both operators select the proportion of items to modify via a rate drawn from
# Uniform(rate_min, rate_max), corresponding to the "a" and "b" parameters
# in the paper (see Algorithm 1 and the hyperparameter analysis).
#
# In the BASRec pipeline, these sequence-level augmentations are later fused at
# the representation level and used for downstream model training.
################################################################################
################################################################################
# Helper function for ensemble similarity models in Substitute
################################################################################
def _ensmeble_sim_models(top_k_one, top_k_two):
"""
Selects the most similar item (by similarity score) from two similarity models' outputs.
Used when ensemble mode is enabled for Substitute.
Implementation Note:
- The ensemble mechanism is not described in the BASRec paper.
- It is an extension for robustness when multiple similarity sources are available.
"""
if top_k_one[0][1] >= top_k_two[0][1]:
return [top_k_one[0][0]]
else:
return [top_k_two[0][0]]
################################################################################
# M-Substitute: Substitute Operator
################################################################################
class Substitute(object):
"""
Substitute randomly selected items in a sequence with similar items, as determined
by an item similarity model.
Correspondence to Paper:
- Implements the "M-Substitute" operator described in the Single-sequence Augmentation section.
- Uses substitute_rate ~ Uniform(a, b), as in Eq. 4 and 8.
Args:
item_similarity_model: Model (or list of models for ensemble) for item similarity.
rate_min, rate_max: Uniform distribution bounds for augmentation proportion (corresponds to a and b).
"""
def __init__(self, item_similarity_model, rate_min, rate_max):
if type(item_similarity_model) is list:
self.item_sim_model_1 = item_similarity_model[0]
self.item_sim_model_2 = item_similarity_model[1]
self.ensemble = True
else:
self.item_similarity_model = item_similarity_model
self.ensemble = False
self.rate_min = rate_min
self.rate_max = rate_max
def __call__(self, sequence):
# Deep copy to avoid in-place modification of original sequence.
copied_sequence = copy.deepcopy(sequence)
# Sample proportion to substitute from Uniform(rate_min, rate_max).
substitute_rate = np.random.uniform(low=self.rate_min, high=self.rate_max)
# Number of items to substitute; at least one.
substitute_nums = max(int(substitute_rate * len(copied_sequence)), 1)
# Randomly select indices to substitute.
substitute_idx = random.sample([i for i in range(len(copied_sequence))], k=substitute_nums)
for index in substitute_idx:
if self.ensemble:
# Use two similarity models and pick the top by score.
top_k_one = self.item_sim_model_1.most_similar(copied_sequence[index], with_score=True)
top_k_two = self.item_sim_model_2.most_similar(copied_sequence[index], with_score=True)
substitute_items = _ensmeble_sim_models(top_k_one, top_k_two)
copied_sequence[index] = substitute_items[0]
else:
# Substitute with top-1 most similar item from single model.
copied_sequence[index] = \
self.item_similarity_model.most_similar(copied_sequence[index])[0]
# Return new sequence and the used substitute rate (for adaptive weighting if needed).
return copied_sequence, substitute_rate
################################################################################
# M-Reorder: Reorder Operator
################################################################################
class Reorder(object):
"""
Randomly shuffle a contiguous sub-sequence within the sequence.
This is the "M-Reorder" operator in the BASRec paper.
Correspondence to Paper:
- Implements the "M-Reorder" operator (Eq. 4-5 in the paper).
- Uses reorder_rate ~ Uniform(a, b) to decide the proportion of items to reorder.
Args:
rate_min, rate_max: Uniform distribution bounds for augmentation proportion (corresponds to a and b).
"""
def __init__(self, rate_min, rate_max):
self.rate_min = rate_min
self.rate_max = rate_max
def __call__(self, sequence):
# Deep copy to avoid in-place modification of the original sequence.
copied_sequence = copy.deepcopy(sequence)
# Sample proportion to reorder from Uniform(rate_min, rate_max).
reorder_rate = np.random.uniform(low=self.rate_min, high=self.rate_max)
sub_seq_length = int(reorder_rate * len(copied_sequence))
# Randomly select the start index for the sub-sequence to shuffle.
start_index = random.randint(0, len(copied_sequence) - sub_seq_length - 1)
sub_seq = copied_sequence[start_index:start_index + sub_seq_length]
# Shuffle the sub-sequence in place.
random.shuffle(sub_seq)
# Reconstruct the sequence with shuffled sub-sequence.
reordered_seq = copied_sequence[:start_index] + sub_seq + \
copied_sequence[start_index + sub_seq_length:]
# Sanity check: ensure sequence length is unchanged.
assert len(copied_sequence) == len(reordered_seq)
# Return new sequence and the used reorder rate (for adaptive weighting if needed).
return reordered_seq, reorder_rate
################################################################################
# Discrepancies and Implementation Extensions
#
# 1. This file only implements single-sequence augmentation (M-Reorder, M-Substitute).
# The cross-sequence augmentation (nonlinear mixup between representations of
# different users) and the adaptive loss weighting described in the paper are not
# present here; these would be implemented elsewhere in the codebase, typically
# at the model or trainer level.
#
# 2. The paper describes mixing in the *representation* space (embedding-level mixup),
# while this code augments in the *input sequence* (item index) space.
# The transition from sequence augmentation to embedding-level mixup is likely
# handled in downstream code, not shown here.
#
# 3. The "Random" class and ensemble mechanism for Substitute are not explicitly
# described in the paper, but serve to improve practical diversity and robustness.
#
# 4. The return values include the applied augmentation rate, which is necessary
# for adaptive loss weighting (see Eq. 9 of the paper), but the weighting is not
# computed here—again, likely handled elsewhere in the pipeline.
#
# 5. Any similarity model interface or logic (e.g., .most_similar) is assumed to be
# defined outside this code; the paper does not specify the similarity computation
# details.
################################################################################