def test_avalanche_dataset_add(self): dataset_mnist = MNIST('./data/mnist', download=True, transform=CenterCrop(16)) dataset1 = AvalancheDataset(dataset_mnist, transform=ToTensor(), target_transform=lambda target: -1) dataset2 = AvalancheDataset(dataset_mnist, target_transform=lambda target: -2, task_labels=ConstantSequence( 2, len(dataset_mnist))) dataset3 = dataset1 + dataset2 self.assertEqual(len(dataset_mnist) * 2, len(dataset3)) x1, y1, t1 = dataset1[0] x2, y2, t2 = dataset2[0] x3, y3, t3 = dataset3[0] x3_2, y3_2, t3_2 = dataset3[len(dataset_mnist)] self.assertIsInstance(x1, Tensor) self.assertEqual(x1.shape, (1, 16, 16)) self.assertEqual(-1, y1) self.assertEqual(0, t1) self.assertIsInstance(x2, PIL.Image.Image) self.assertEqual(x2.size, (16, 16)) self.assertEqual(-2, y2) self.assertEqual(2, t2) self.assertEqual((y1, t1), (y3, t3)) self.assertEqual(16 * 16, torch.sum(torch.eq(x1, x3)).item()) self.assertEqual((y2, t2), (y3_2, t3_2)) self.assertTrue(pil_images_equal(x2, x3_2))
def __init__( self, train_dataset: AvalancheDataset, test_dataset: AvalancheDataset, n_experiences: int, task_labels: bool = False, shuffle: bool = True, seed: Optional[int] = None, balance_experiences: bool = False, min_class_patterns_in_exp: int = 0, fixed_exp_assignment: Optional[Sequence[Sequence[int]]] = None, reproducibility_data: Optional[Dict[str, Any]] = None): """ Creates a NIScenario instance given the training and test Datasets and the number of experiences. :param train_dataset: The training dataset. The dataset must be an instance of :class:`AvalancheDataset`. For instance, one can use the datasets from the torchvision package like that: ``train_dataset=AvalancheDataset(torchvision_dataset)``. :param test_dataset: The test dataset. The dataset must be a subclass of :class:`AvalancheDataset`. For instance, one can use the datasets from the torchvision package like that: ``test_dataset=AvalancheDataset(torchvision_dataset)``. :param n_experiences: The number of experiences. :param task_labels: If True, each experience will have an ascending task label. If False, the task label will be 0 for all the experiences. Defaults to False. :param shuffle: If True, the patterns order will be shuffled. Defaults to True. :param seed: If shuffle is True and seed is not None, the class order will be shuffled according to the seed. When None, the current PyTorch random number generator state will be used. Defaults to None. :param balance_experiences: If True, pattern of each class will be equally spread across all experiences. If False, patterns will be assigned to experiences in a complete random way. Defaults to False. :param min_class_patterns_in_exp: The minimum amount of patterns of every class that must be assigned to every experience. Compatible with the ``balance_experiences`` parameter. An exception will be raised if this constraint can't be satisfied. Defaults to 0. :param fixed_exp_assignment: If not None, the pattern assignment to use. It must be a list with an entry for each experience. Each entry is a list that contains the indexes of patterns belonging to that experience. Overrides the ``shuffle``, ``balance_experiences`` and ``min_class_patterns_in_exp`` parameters. :param reproducibility_data: If not None, overrides all the other scenario definition options, including ``fixed_exp_assignment``. This is usually a dictionary containing data used to reproduce a specific experiment. One can use the ``get_reproducibility_data`` method to get (and even distribute) the experiment setup so that it can be loaded by passing it as this parameter. In this way one can be sure that the same specific experimental setup is being used (for reproducibility purposes). Beware that, in order to reproduce an experiment, the same train and test datasets must be used. Defaults to None. """ self._has_task_labels = task_labels self.train_exps_patterns_assignment = [] if reproducibility_data is not None: self.train_exps_patterns_assignment = reproducibility_data[ 'exps_patterns_assignment'] self._has_task_labels = reproducibility_data['has_task_labels'] n_experiences = len(self.train_exps_patterns_assignment) if n_experiences < 1: raise ValueError('Invalid number of experiences (n_experiences ' 'parameter): must be greater than 0') if min_class_patterns_in_exp < 0 and reproducibility_data is None: raise ValueError('Invalid min_class_patterns_in_exp parameter: ' 'must be greater than or equal to 0') # # Good idea, but doesn't work # transform_groups = train_eval_transforms(train_dataset, test_dataset) # # train_dataset = train_dataset \ # .replace_transforms(*transform_groups['train'], group='train') \ # .replace_transforms(*transform_groups['eval'], group='eval') # # test_dataset = test_dataset \ # .replace_transforms(*transform_groups['train'], group='train') \ # .replace_transforms(*transform_groups['eval'], group='eval') unique_targets, unique_count = torch.unique(torch.as_tensor( train_dataset.targets), return_counts=True) self.n_classes: int = len(unique_targets) """ The amount of classes in the original training set. """ self.n_patterns_per_class: List[int] = \ [0 for _ in range(self.n_classes)] """ The amount of patterns for each class in the original training set. """ if fixed_exp_assignment: included_patterns = list() for exp_def in fixed_exp_assignment: included_patterns.extend(exp_def) subset = AvalancheSubset(train_dataset, indices=included_patterns) unique_targets, unique_count = torch.unique(torch.as_tensor( subset.targets), return_counts=True) for unique_idx in range(len(unique_targets)): class_id = int(unique_targets[unique_idx]) class_count = int(unique_count[unique_idx]) self.n_patterns_per_class[class_id] = class_count self.n_patterns_per_experience: List[int] = [] """ The number of patterns in each experience. """ self.exp_structure: List[List[int]] = [] """ This field contains, for each training experience, the number of instances of each class assigned to that experience. """ if reproducibility_data or fixed_exp_assignment: # fixed_patterns_assignment/reproducibility_data is the user # provided pattern assignment. All we have to do is populate # remaining fields of the class! # n_patterns_per_experience is filled later based on exp_structure # so we only need to fill exp_structure. if reproducibility_data: exp_patterns = self.train_exps_patterns_assignment else: exp_patterns = fixed_exp_assignment self.exp_structure = _exp_structure_from_assignment( train_dataset, exp_patterns, self.n_classes) else: # All experiences will all contain the same amount of patterns # The amount of patterns doesn't need to be divisible without # remainder by the number of experience, so we distribute remaining # patterns across randomly selected experience (when shuffling) or # the first N experiences (when not shuffling). However, we first # have to check if the min_class_patterns_in_exp constraint is # satisfiable. min_class_patterns = min(self.n_patterns_per_class) if min_class_patterns < n_experiences * min_class_patterns_in_exp: raise ValueError('min_class_patterns_in_exp constraint ' 'can\'t be satisfied') if seed is not None: torch.random.manual_seed(seed) # First, get the patterns indexes for each class targets_as_tensor = torch.as_tensor(train_dataset.targets) classes_to_patterns_idx = [ torch.nonzero(torch.eq(targets_as_tensor, class_id)).view(-1).tolist() for class_id in range(self.n_classes) ] if shuffle: classes_to_patterns_idx = [ torch.as_tensor(cls_patterns)[torch.randperm( len(cls_patterns))].tolist() for cls_patterns in classes_to_patterns_idx ] # Here we assign patterns to each experience. Two different # strategies are required in order to manage the # balance_experiences parameter. if balance_experiences: # If balance_experiences is True we have to make sure that # patterns of each class are equally distributed across # experiences. # # To do this, populate self.exp_structure, which will # describe how many patterns of each class are assigned to each # experience. Then, for each experience, assign the required # amount of patterns of each class. # # We already checked that there are enough patterns for each # class to satisfy the min_class_patterns_in_exp param so here # we don't need to explicitly enforce that constraint. # First, count how many patterns of each class we have to assign # to all the experiences (avg). We also get the number of # remaining patterns which we'll have to assign in a second # experience. class_patterns_per_exp = [ ((n_class_patterns // n_experiences), (n_class_patterns % n_experiences)) for n_class_patterns in self.n_patterns_per_class ] # Remember: exp_structure[exp_id][class_id] is the amount of # patterns of class "class_id" in experience "exp_id" # # This is the easier experience: just assign the average amount # of class patterns to each experience. self.exp_structure = [[ class_patterns_this_exp[0] for class_patterns_this_exp in class_patterns_per_exp ] for _ in range(n_experiences)] # Now we have to distribute the remaining patterns of each class # # This means that, for each class, we can (randomly) select # "n_class_patterns % n_experiences" experiences to assign a # single additional pattern of that class. for class_id in range(self.n_classes): n_remaining = class_patterns_per_exp[class_id][1] if n_remaining == 0: continue if shuffle: assignment_of_remaining_patterns = torch.randperm( n_experiences).tolist()[:n_remaining] else: assignment_of_remaining_patterns = range(n_remaining) for exp_id in assignment_of_remaining_patterns: self.exp_structure[exp_id][class_id] += 1 # Following the self.exp_structure definition, assign # the actual patterns to each experience. # # For each experience we assign exactly # self.exp_structure[exp_id][class_id] patterns of # class "class_id" exp_patterns = [[] for _ in range(n_experiences)] next_idx_per_class = [0 for _ in range(self.n_classes)] for exp_id in range(n_experiences): for class_id in range(self.n_classes): start_idx = next_idx_per_class[class_id] n_patterns = self.exp_structure[exp_id][class_id] end_idx = start_idx + n_patterns exp_patterns[exp_id].extend( classes_to_patterns_idx[class_id] [start_idx:end_idx]) next_idx_per_class[class_id] = end_idx else: # If balance_experiences if False, we just randomly shuffle the # patterns indexes and pick N patterns for each experience. # # However, we have to enforce the min_class_patterns_in_exp # constraint, which makes things difficult. # In the balance_experiences scenario, that constraint is # implicitly enforced by equally distributing class patterns in # each experience (we already checked that there are enough # overall patterns for each class to satisfy # min_class_patterns_in_exp) # Here we have to assign the minimum required amount of class # patterns to each experience first, then we can move to # randomly assign the remaining patterns to each experience. # First, initialize exp_patterns and exp_structure exp_patterns = [[] for _ in range(n_experiences)] self.exp_structure = [[0 for _ in range(self.n_classes)] for _ in range(n_experiences)] # For each experience we assign exactly # min_class_patterns_in_exp patterns from each class # # Very similar to the loop found in the balance_experiences # branch! Remember that classes_to_patterns_idx is already # shuffled (if required) next_idx_per_class = [0 for _ in range(self.n_classes)] remaining_patterns = set(range(len(train_dataset))) for exp_id in range(n_experiences): for class_id in range(self.n_classes): next_idx = next_idx_per_class[class_id] end_idx = next_idx + min_class_patterns_in_exp selected_patterns = \ classes_to_patterns_idx[next_idx:end_idx] exp_patterns[exp_id].extend(selected_patterns) self.exp_structure[exp_id][class_id] += \ min_class_patterns_in_exp remaining_patterns.difference_update(selected_patterns) next_idx_per_class[class_id] = end_idx remaining_patterns = list(remaining_patterns) # We have assigned the required min_class_patterns_in_exp, # now we assign the remaining patterns # # We'll work on remaining_patterns, which contains indexes of # patterns not assigned in the previous experience. if shuffle: patterns_order = torch.as_tensor(remaining_patterns)[ torch.randperm(len(remaining_patterns))].tolist() else: remaining_patterns.sort() patterns_order = remaining_patterns targets_order = [ train_dataset.targets[pattern_idx] for pattern_idx in patterns_order ] avg_exp_size = len(patterns_order) // n_experiences n_remaining = len(patterns_order) % n_experiences prev_idx = 0 for exp_id in range(n_experiences): next_idx = prev_idx + avg_exp_size exp_patterns[exp_id].extend( patterns_order[prev_idx:next_idx]) cls_ids, cls_counts = torch.unique(torch.as_tensor( targets_order[prev_idx:next_idx]), return_counts=True) cls_ids = cls_ids.tolist() cls_counts = cls_counts.tolist() for unique_idx in range(len(cls_ids)): self.exp_structure[exp_id][cls_ids[unique_idx]] += \ cls_counts[unique_idx] prev_idx = next_idx # Distribute remaining patterns if n_remaining > 0: if shuffle: assignment_of_remaining_patterns = torch.randperm( n_experiences).tolist()[:n_remaining] else: assignment_of_remaining_patterns = range(n_remaining) for exp_id in assignment_of_remaining_patterns: pattern_idx = patterns_order[prev_idx] pattern_target = targets_order[prev_idx] exp_patterns[exp_id].append(pattern_idx) self.exp_structure[exp_id][pattern_target] += 1 prev_idx += 1 self.n_patterns_per_experience = [ len(exp_patterns[exp_id]) for exp_id in range(n_experiences) ] self._classes_in_exp = None # Will be lazy initialized later train_experiences = [] train_task_labels = [] for t_id, exp_def in enumerate(exp_patterns): if self._has_task_labels: train_task_labels.append(t_id) else: train_task_labels.append(0) task_labels = ConstantSequence(train_task_labels[-1], len(train_dataset)) train_experiences.append( AvalancheSubset(train_dataset, indices=exp_def, task_labels=task_labels)) self.train_exps_patterns_assignment = exp_patterns """ A list containing which training instances are assigned to each experience in the train stream. Instances are identified by their id w.r.t. the dataset found in the original_train_dataset field. """ super(NIScenario, self).__init__(stream_definitions={ 'train': (train_experiences, train_task_labels, train_dataset), 'test': (test_dataset, [0], test_dataset) }, complete_test_set_only=True, experience_factory=NIExperience)
def create_multi_dataset_generic_scenario( train_dataset_list: Sequence[SupportedDataset], test_dataset_list: Sequence[SupportedDataset], task_labels: Sequence[int], complete_test_set_only: bool = False, train_transform=None, train_target_transform=None, eval_transform=None, eval_target_transform=None, dataset_type: AvalancheDatasetType = None, ) -> GenericCLScenario: """ This helper function is DEPRECATED in favor of `create_multi_dataset_generic_benchmark`. Creates a generic scenario given a list of datasets and the respective task labels. Each training dataset will be considered as a separate training experience. Contents of the datasets will not be changed, including the targets. When loading the datasets from a set of fixed filelist, consider using the :func:`create_generic_scenario_from_filelists` helper method instead. In its base form, this function accepts a list of test datsets that must contain the same amount of datasets of the training list. Those pairs are then used to create the "past", "cumulative" (a.k.a. growing) and "future" test sets. However, in certain Continual Learning scenarios only the concept of "complete" test set makes sense. In that case, the ``complete_test_set_only`` should be set to True (see the parameter description for more info). Beware that pattern transformations must already be included in the datasets (when needed). :param train_dataset_list: A list of training datasets. :param test_dataset_list: A list of test datasets. :param task_labels: A list of task labels. Must contain the same amount of elements of the ``train_dataset_list`` parameter. For Single-Incremental-Task (a.k.a. Task-Free) scenarios, this is usually a list of zeros. For Multi Task scenario, this is usually a list of ascending task labels (starting from 0). :param complete_test_set_only: If True, only the complete test set will be returned by the scenario. This means that the ``test_dataset_list`` parameter must be list with a single element (the complete test set). Defaults to False, which means that ``train_dataset_list`` and ``test_dataset_list`` must contain the same amount of datasets. :param train_transform: The transformation to apply to the training data, e.g. a random crop, a normalization or a concatenation of different transformations (see torchvision.transform documentation for a comprehensive list of possible transformations). Defaults to None. :param train_target_transform: The transformation to apply to training patterns targets. Defaults to None. :param eval_transform: The transformation to apply to the test data, e.g. a random crop, a normalization or a concatenation of different transformations (see torchvision.transform documentation for a comprehensive list of possible transformations). Defaults to None. :param eval_target_transform: The transformation to apply to test patterns targets. Defaults to None. :param dataset_type: The type of the dataset. Defaults to None, which means that the type will be obtained from the input datasets. If input datasets are not instances of :class:`AvalancheDataset`, the type UNDEFINED will be used. :returns: A :class:`GenericCLScenario` instance. """ warnings.warn( "create_multi_dataset_generic_scenario is deprecated in favor" " of create_multi_dataset_generic_benchmark.", DeprecationWarning, ) transform_groups = dict( train=(train_transform, train_target_transform), eval=(eval_transform, eval_target_transform), ) if complete_test_set_only: if len(test_dataset_list) != 1: raise ValueError("Test must contain 1 element when" "complete_test_set_only is True") else: if len(test_dataset_list) != len(train_dataset_list): raise ValueError("Train and test lists must define the same " " amount of experiences") train_t_labels = [] train_dataset_list = list(train_dataset_list) for dataset_idx in range(len(train_dataset_list)): dataset = train_dataset_list[dataset_idx] train_t_labels.append(task_labels[dataset_idx]) train_dataset_list[dataset_idx] = AvalancheDataset( dataset, task_labels=ConstantSequence(task_labels[dataset_idx], len(dataset)), transform_groups=transform_groups, initial_transform_group="train", dataset_type=dataset_type, ) test_t_labels = [] test_dataset_list = list(test_dataset_list) for dataset_idx in range(len(test_dataset_list)): dataset = test_dataset_list[dataset_idx] test_t_label = task_labels[dataset_idx] if complete_test_set_only: test_t_label = 0 test_t_labels.append(test_t_label) test_dataset_list[dataset_idx] = AvalancheDataset( dataset, task_labels=ConstantSequence(test_t_label, len(dataset)), transform_groups=transform_groups, initial_transform_group="eval", dataset_type=dataset_type, ) return GenericCLScenario( stream_definitions={ "train": (train_dataset_list, train_t_labels), "test": (test_dataset_list, test_t_labels), }, complete_test_set_only=complete_test_set_only, )
def create_multi_dataset_generic_scenario( train_dataset_list: Sequence[SupportedDataset], test_dataset_list: Sequence[SupportedDataset], task_labels: Sequence[int], complete_test_set_only: bool = False, train_transform=None, train_target_transform=None, eval_transform=None, eval_target_transform=None, dataset_type: AvalancheDatasetType = None) \ -> GenericCLScenario: """ Creates a generic scenario given a list of datasets and the respective task labels. Each training dataset will be considered as a separate training experience. Contents of the datasets will not be changed, including the targets. When loading the datasets from a set of fixed filelist, consider using the :func:`create_generic_scenario_from_filelists` helper method instead. In its base form, this function accepts a list of test datsets that must contain the same amount of datasets of the training list. Those pairs are then used to create the "past", "cumulative" (a.k.a. growing) and "future" test sets. However, in certain Continual Learning scenarios only the concept of "complete" test set makes sense. In that case, the ``complete_test_set_only`` should be set to True (see the parameter description for more info). Beware that pattern transformations must already be included in the datasets (when needed). :param train_dataset_list: A list of training datasets. :param test_dataset_list: A list of test datasets. :param task_labels: A list of task labels. Must contain the same amount of elements of the ``train_dataset_list`` parameter. For Single-Incremental-Task (a.k.a. Task-Free) scenarios, this is usually a list of zeros. For Multi Task scenario, this is usually a list of ascending task labels (starting from 0). :param complete_test_set_only: If True, only the complete test set will be returned by the scenario. This means that the ``test_dataset_list`` parameter must be list with a single element (the complete test set). Defaults to False, which means that ``train_dataset_list`` and ``test_dataset_list`` must contain the same amount of datasets. :param train_transform: The transformation to apply to the training data, e.g. a random crop, a normalization or a concatenation of different transformations (see torchvision.transform documentation for a comprehensive list of possible transformations). Defaults to None. :param train_target_transform: The transformation to apply to training patterns targets. Defaults to None. :param eval_transform: The transformation to apply to the test data, e.g. a random crop, a normalization or a concatenation of different transformations (see torchvision.transform documentation for a comprehensive list of possible transformations). Defaults to None. :param eval_target_transform: The transformation to apply to test patterns targets. Defaults to None. :param dataset_type: The type of the dataset. Defaults to None, which means that the type will be obtained from the input datasets. If input datasets are not instances of :class:`AvalancheDataset`, the type UNDEFINED will be used. :returns: A :class:`GenericCLScenario` instance. """ # TODO: more generic handling of task labels transform_groups = dict(train=(train_transform, train_target_transform), eval=(eval_transform, eval_target_transform)) # GenericCLScenario accepts a single training+test sets couple along with # the respective list of patterns indexes to include in each experience. # This means that we have to concat the list of train and test sets # and create, for each experience, a of indexes. # Each dataset describes a different experience so the lists of indexes will # just be ranges of ascending indexes. train_structure = [] pattern_train_task_labels = [] concat_train_dataset = AvalancheConcatDataset( train_dataset_list, transform_groups=transform_groups, initial_transform_group='train', dataset_type=dataset_type) next_idx = 0 for dataset_idx, train_dataset in enumerate(train_dataset_list): end_idx = next_idx + len(train_dataset) train_structure.append(range(next_idx, end_idx)) pattern_train_task_labels.append( ConstantSequence(task_labels[dataset_idx], len(train_dataset))) next_idx = end_idx pattern_train_task_labels = LazyConcatIntTargets(pattern_train_task_labels) test_structure = [] if complete_test_set_only: # If complete_test_set_only is True, we can leave test_structure = [] # In this way, GenericCLScenario will consider the whole test set. # # We don't offer a way to reduce the test set here. However, consider # that the user may reduce the test set by creating a subset and passing # it to this function directly. if len(test_dataset_list) != 1: raise ValueError('Test must contain 1 element when' 'complete_test_set_only is True') concat_test_dataset = as_avalanche_dataset(test_dataset_list[0], dataset_type=dataset_type) concat_test_dataset = concat_test_dataset.train().add_transforms( train_transform, train_target_transform) concat_test_dataset = concat_test_dataset.eval().add_transforms( eval_transform, eval_target_transform) pattern_test_task_labels = ConstantSequence(0, len(concat_test_dataset)) else: concat_test_dataset = AvalancheConcatDataset( test_dataset_list, transform_groups=transform_groups, initial_transform_group='eval', dataset_type=dataset_type) test_structure = [] pattern_test_task_labels = [] next_idx = 0 for dataset_idx, test_dataset in enumerate(test_dataset_list): end_idx = next_idx + len(test_dataset) test_structure.append(range(next_idx, end_idx)) pattern_test_task_labels.append( ConstantSequence(task_labels[dataset_idx], len(test_dataset))) next_idx = end_idx pattern_test_task_labels = LazyConcatIntTargets( pattern_test_task_labels) task_labels = [[x] for x in task_labels] # GenericCLScenario constructor will also check that the same amount of # train/test sets + task_labels have been defined. return GenericCLScenario(concat_train_dataset, concat_test_dataset, concat_train_dataset, concat_test_dataset, train_structure, test_structure, task_labels, pattern_train_task_labels, pattern_test_task_labels, complete_test_set_only=complete_test_set_only)
def __init__(self, train_dataset: AvalancheDataset, test_dataset: AvalancheDataset, n_experiences: int, task_labels: bool, shuffle: bool = True, seed: Optional[int] = None, fixed_class_order: Optional[Sequence[int]] = None, per_experience_classes: Optional[Dict[int, int]] = None, class_ids_from_zero_from_first_exp: bool = False, class_ids_from_zero_in_each_exp: bool = False, reproducibility_data: Optional[Dict[str, Any]] = None): """ Creates a ``NCGenericScenario`` instance given the training and test Datasets and the number of experiences. By default, the number of classes will be automatically detected by looking at the training Dataset ``targets`` field. Classes will be uniformly distributed across ``n_experiences`` unless a ``per_experience_classes`` argument is specified. The number of classes must be divisible without remainder by the number of experiences. This also applies when the ``per_experience_classes`` argument is not None. :param train_dataset: The training dataset. The dataset must be a subclass of :class:`AvalancheDataset`. For instance, one can use the datasets from the torchvision package like that: ``train_dataset=AvalancheDataset(torchvision_dataset)``. :param test_dataset: The test dataset. The dataset must be a subclass of :class:`AvalancheDataset`. For instance, one can use the datasets from the torchvision package like that: ``test_dataset=AvalancheDataset(torchvision_dataset)``. :param n_experiences: The number of experiences. :param task_labels: If True, each experience will have an ascending task label. If False, the task label will be 0 for all the experiences. :param shuffle: If True, the class order will be shuffled. Defaults to True. :param seed: If shuffle is True and seed is not None, the class order will be shuffled according to the seed. When None, the current PyTorch random number generator state will be used. Defaults to None. :param fixed_class_order: If not None, the class order to use (overrides the shuffle argument). Very useful for enhancing reproducibility. Defaults to None. :param per_experience_classes: Is not None, a dictionary whose keys are (0-indexed) experience IDs and their values are the number of classes to include in the respective experiences. The dictionary doesn't have to contain a key for each experience! All the remaining experiences will contain an equal amount of the remaining classes. The remaining number of classes must be divisible without remainder by the remaining number of experiences. For instance, if you want to include 50 classes in the first experience while equally distributing remaining classes across remaining experiences, just pass the "{0: 50}" dictionary as the per_experience_classes parameter. Defaults to None. :param class_ids_from_zero_from_first_exp: If True, original class IDs will be remapped so that they will appear as having an ascending order. For instance, if the resulting class order after shuffling (or defined by fixed_class_order) is [23, 34, 11, 7, 6, ...] and class_ids_from_zero_from_first_exp is True, then all the patterns belonging to class 23 will appear as belonging to class "0", class "34" will be mapped to "1", class "11" to "2" and so on. This is very useful when drawing confusion matrices and when dealing with algorithms with dynamic head expansion. Defaults to False. Mutually exclusive with the ``class_ids_from_zero_in_each_exp`` parameter. :param class_ids_from_zero_in_each_exp: If True, original class IDs will be mapped to range [0, n_classes_in_exp) for each experience. Defaults to False. Mutually exclusive with the ``class_ids_from_zero_from_first_exp parameter``. :param reproducibility_data: If not None, overrides all the other scenario definition options. This is usually a dictionary containing data used to reproduce a specific experiment. One can use the ``get_reproducibility_data`` method to get (and even distribute) the experiment setup so that it can be loaded by passing it as this parameter. In this way one can be sure that the same specific experimental setup is being used (for reproducibility purposes). Beware that, in order to reproduce an experiment, the same train and test datasets must be used. Defaults to None. """ if class_ids_from_zero_from_first_exp and \ class_ids_from_zero_in_each_exp: raise ValueError('Invalid mutually exclusive options ' 'class_ids_from_zero_from_first_exp and ' 'class_ids_from_zero_in_each_exp set at the ' 'same time') if reproducibility_data: n_experiences = reproducibility_data['n_experiences'] if n_experiences < 1: raise ValueError('Invalid number of experiences (n_experiences ' 'parameter): must be greater than 0') self.classes_order: List[int] = [] """ Stores the class order (remapped class IDs). """ self.classes_order_original_ids: List[int] = torch.unique( torch.as_tensor(train_dataset.targets), sorted=True).tolist() """ Stores the class order (original class IDs) """ n_original_classes = max(self.classes_order_original_ids) + 1 self.class_mapping: List[int] = [] """ class_mapping stores the class mapping so that `mapped_class_id = class_mapping[original_class_id]`. If the scenario is created with an amount of classes which is less than the amount of all classes in the dataset, then class_mapping will contain some -1 values corresponding to ignored classes. This can happen when passing a fixed class order to the constructor. """ self.n_classes_per_exp: List[int] = [] """ A list that, for each experience (identified by its index/ID), stores the number of classes assigned to that experience. """ self._classes_in_exp: List[Set[int]] = [] self.original_classes_in_exp: List[Set[int]] = [] """ A list that, for each experience (identified by its index/ID), stores a set of the original IDs of classes assigned to that experience. This field applies to both train and test streams. """ self.class_ids_from_zero_from_first_exp: bool = \ class_ids_from_zero_from_first_exp """ If True the class IDs have been remapped to start from zero. """ self.class_ids_from_zero_in_each_exp: bool = \ class_ids_from_zero_in_each_exp """ If True the class IDs have been remapped to start from zero in each experience """ # Note: if fixed_class_order is None and shuffle is False, # the class order will be the one encountered # By looking at the train_dataset targets field if reproducibility_data: self.classes_order_original_ids = \ reproducibility_data['classes_order_original_ids'] self.class_ids_from_zero_from_first_exp = \ reproducibility_data['class_ids_from_zero_from_first_exp'] self.class_ids_from_zero_in_each_exp = \ reproducibility_data['class_ids_from_zero_in_each_exp'] elif fixed_class_order is not None: # User defined class order -> just use it if len(set(self.classes_order_original_ids).union( set(fixed_class_order))) != \ len(self.classes_order_original_ids): raise ValueError( 'Invalid classes defined in fixed_class_order') self.classes_order_original_ids = list(fixed_class_order) elif shuffle: # No user defined class order. # If a seed is defined, set the random number generator seed. # If no seed has been defined, use the actual # random number generator state. # Finally, shuffle the class list to obtain a random classes # order if seed is not None: torch.random.manual_seed(seed) self.classes_order_original_ids = \ torch.as_tensor(self.classes_order_original_ids)[ torch.randperm(len(self.classes_order_original_ids)) ].tolist() self.n_classes: int = len(self.classes_order_original_ids) """ The number of classes """ if reproducibility_data: self.n_classes_per_exp = \ reproducibility_data['n_classes_per_exp'] elif per_experience_classes is not None: # per_experience_classes is a user-defined dictionary that defines # the number of classes to include in some (or all) experiences. # Remaining classes are equally distributed across the other # experiences. # # Format of per_experience_classes dictionary: # - key = experience id # - value = number of classes for this experience if max(per_experience_classes.keys()) >= n_experiences or min( per_experience_classes.keys()) < 0: # The dictionary contains a key (that is, a experience id) >= # the number of requested experiences... or < 0 raise ValueError( 'Invalid experience id in per_experience_classes parameter:' ' experience ids must be in range [0, n_experiences)') if min(per_experience_classes.values()) < 0: # One or more values (number of classes for each experience) < 0 raise ValueError('Wrong number of classes defined for one or ' 'more experiences: must be a non-negative ' 'value') if sum(per_experience_classes.values()) > self.n_classes: # The sum of dictionary values (n. of classes for each # experience) >= the number of classes raise ValueError('Insufficient number of classes: ' 'per_experience_classes parameter can\'t ' 'be satisfied') # Remaining classes are equally distributed across remaining # experiences. This amount of classes must be be divisible without # remainder by the number of remaining experiences remaining_exps = n_experiences - len(per_experience_classes) if remaining_exps > 0 and (self.n_classes - sum( per_experience_classes.values())) % remaining_exps > 0: raise ValueError('Invalid number of experiences: remaining ' 'classes cannot be divided by n_experiences') # default_per_exp_classes is the default amount of classes # for the remaining experiences if remaining_exps > 0: default_per_exp_classes = (self.n_classes - sum( per_experience_classes.values())) // remaining_exps else: default_per_exp_classes = 0 # Initialize the self.n_classes_per_exp list using # "default_per_exp_classes" as the default # amount of classes per experience. Then, loop through the # per_experience_classes dictionary to set the customized, # user defined, classes for the required experiences. self.n_classes_per_exp = \ [default_per_exp_classes] * n_experiences for exp_id in per_experience_classes: self.n_classes_per_exp[exp_id] = per_experience_classes[exp_id] else: # Classes will be equally distributed across the experiences # The amount of classes must be be divisible without remainder # by the number of experiences if self.n_classes % n_experiences > 0: raise ValueError( 'Invalid number of experiences: classes contained in ' 'dataset cannot be divided by n_experiences') self.n_classes_per_exp = \ [self.n_classes // n_experiences] * n_experiences # Before populating the classes_in_experience list, # define the remapped class IDs. if reproducibility_data: # Method 0: use reproducibility data self.classes_order = reproducibility_data['classes_order'] self.class_mapping = reproducibility_data['class_mapping'] elif self.class_ids_from_zero_from_first_exp: # Method 1: remap class IDs so that they appear in ascending order # over all experiences self.classes_order = list(range(0, self.n_classes)) self.class_mapping = [-1] * n_original_classes for class_id in range(n_original_classes): # This check is needed because, when a fixed class order is # used, the user may have defined an amount of classes less than # the overall amount of classes in the dataset. if class_id in self.classes_order_original_ids: self.class_mapping[class_id] = \ self.classes_order_original_ids.index(class_id) elif self.class_ids_from_zero_in_each_exp: # Method 2: remap class IDs so that they appear in range [0, N] in # each experience self.classes_order = [] self.class_mapping = [-1] * n_original_classes next_class_idx = 0 for exp_id, exp_n_classes in enumerate(self.n_classes_per_exp): self.classes_order += list(range(exp_n_classes)) for exp_class_idx in range(exp_n_classes): original_class_position = next_class_idx + exp_class_idx original_class_id = self.classes_order_original_ids[ original_class_position] self.class_mapping[original_class_id] = exp_class_idx next_class_idx += exp_n_classes else: # Method 3: no remapping of any kind # remapped_id = class_mapping[class_id] -> class_id == remapped_id self.classes_order = self.classes_order_original_ids self.class_mapping = list(range(0, n_original_classes)) original_training_dataset = train_dataset original_test_dataset = test_dataset # Populate the _classes_in_exp and original_classes_in_exp lists # "_classes_in_exp[exp_id]": list of (remapped) class IDs assigned # to experience "exp_id" # "original_classes_in_exp[exp_id]": list of original class IDs # assigned to experience "exp_id" for exp_id in range(n_experiences): classes_start_idx = sum(self.n_classes_per_exp[:exp_id]) classes_end_idx = classes_start_idx + self.n_classes_per_exp[exp_id] self._classes_in_exp.append( set(self.classes_order[classes_start_idx:classes_end_idx])) self.original_classes_in_exp.append( set(self.classes_order_original_ids[ classes_start_idx:classes_end_idx])) # Finally, create the experience -> patterns assignment. # In order to do this, we don't load all the patterns # instead we use the targets field. train_exps_patterns_assignment = [] test_exps_patterns_assignment = [] self._has_task_labels = task_labels if reproducibility_data is not None: self._has_task_labels = bool( reproducibility_data['has_task_labels']) if self._has_task_labels: pattern_train_task_labels = [-1] * len(train_dataset) pattern_test_task_labels = [-1] * len(test_dataset) else: pattern_train_task_labels = ConstantSequence(0, len(train_dataset)) pattern_test_task_labels = ConstantSequence(0, len(test_dataset)) for exp_id in range(n_experiences): selected_classes = self.original_classes_in_exp[exp_id] selected_indexes_train = [] for idx, element in enumerate(original_training_dataset.targets): if element in selected_classes: selected_indexes_train.append(idx) if self._has_task_labels: pattern_train_task_labels[idx] = exp_id selected_indexes_test = [] for idx, element in enumerate(original_test_dataset.targets): if element in selected_classes: selected_indexes_test.append(idx) if self._has_task_labels: pattern_test_task_labels[idx] = exp_id train_exps_patterns_assignment.append(selected_indexes_train) test_exps_patterns_assignment.append(selected_indexes_test) # Good idea, but doesn't work # transform_groups = train_eval_transforms(train_dataset, test_dataset) # # train_dataset = train_dataset\ # .replace_transforms(*transform_groups['train'], group='train') \ # .replace_transforms(*transform_groups['eval'], group='eval') # # test_dataset = test_dataset \ # .replace_transforms(*transform_groups['train'], group='train') \ # .replace_transforms(*transform_groups['eval'], group='eval') train_dataset = AvalancheSubset(train_dataset, class_mapping=self.class_mapping, initial_transform_group='train') test_dataset = AvalancheSubset(test_dataset, class_mapping=self.class_mapping, initial_transform_group='eval') self.train_exps_patterns_assignment = train_exps_patterns_assignment """ A list containing which training instances are assigned to each experience in the train stream. Instances are identified by their id w.r.t. the dataset found in the original_train_dataset field. """ self.test_exps_patterns_assignment = test_exps_patterns_assignment """ A list containing which test instances are assigned to each experience in the test stream. Instances are identified by their id w.r.t. the dataset found in the original_test_dataset field. """ train_experiences = [] train_task_labels = [] for t_id, exp_def in enumerate(train_exps_patterns_assignment): if self._has_task_labels: train_task_labels.append(t_id) else: train_task_labels.append(0) task_labels = ConstantSequence(train_task_labels[-1], len(train_dataset)) train_experiences.append( AvalancheSubset(train_dataset, indices=exp_def, task_labels=task_labels)) test_experiences = [] test_task_labels = [] for t_id, exp_def in enumerate(test_exps_patterns_assignment): if self._has_task_labels: test_task_labels.append(t_id) else: test_task_labels.append(0) task_labels = ConstantSequence(test_task_labels[-1], len(test_dataset)) test_experiences.append( AvalancheSubset(test_dataset, indices=exp_def, task_labels=task_labels)) super(NCScenario, self).__init__(stream_definitions={ 'train': (train_experiences, train_task_labels, train_dataset), 'test': (test_experiences, test_task_labels, test_dataset) }, experience_factory=NCExperience)