|
| 1 | +# stdlib |
| 2 | +import math |
| 3 | +from copy import copy |
| 4 | +from typing import Any, Dict, Optional |
| 5 | + |
| 6 | +# third party |
| 7 | +import numpy as np |
| 8 | +import pandas as pd |
| 9 | +from pydantic import validate_arguments |
| 10 | +from typing_extensions import Literal |
| 11 | + |
| 12 | +# synthcity absolute |
| 13 | +from synthcity.plugins.core.constraints import Constraints |
| 14 | +from synthcity.plugins.core.dataloader import DataLoader |
| 15 | + |
| 16 | + |
| 17 | +def calculate_fair_aug_sample_size( |
| 18 | + X_train: pd.DataFrame, |
| 19 | + fairness_column: Optional[str], # a categorical column of K levels |
| 20 | + rule: Literal[ |
| 21 | + "equal", "log", "ad-hoc" |
| 22 | + ], # TODO: Confirm are there any more methods to include |
| 23 | + ad_hoc_augment_vals: Optional[ |
| 24 | + Dict[Any, int] |
| 25 | + ] = None, # Only required for rule == "ad-hoc" |
| 26 | +) -> Dict: |
| 27 | + """Calculate how many samples to augment. |
| 28 | +
|
| 29 | + Args: |
| 30 | + X_train (pd.DataFrame): The real dataset to be augmented. |
| 31 | + fairness_column (str): The column name of the column to test the fairness of a downstream model with respect to. |
| 32 | + rule (Literal["equal", "log", "ad-hoc"]): The rule used to achieve the desired proportion records with each value in the fairness column. Defaults to "equal". |
| 33 | + ad_hoc_augment_vals (Dict[ Union[int, str], int ], optional): A dictionary containing the number of each class to augment the real data with. If using rule="ad-hoc" this function returns ad_hoc_augment_vals, otherwise this parameter is ignored. Defaults to {}. |
| 34 | +
|
| 35 | + Returns: |
| 36 | + Dict: A dictionary containing the number of each class to augment the real data with. |
| 37 | + """ |
| 38 | + |
| 39 | + # the majority class is unchanged |
| 40 | + if rule == "equal": |
| 41 | + # number of sample will be the same for each value in the fairness column after augmentation |
| 42 | + # N_aug(i) = N_ang(j) for all i and j in value in the fairness column |
| 43 | + fairness_col_counts = X_train[fairness_column].value_counts() |
| 44 | + majority_size = fairness_col_counts.max() |
| 45 | + augmentation_counts = { |
| 46 | + fair_col_val: (majority_size - fairness_col_counts.loc[fair_col_val]) |
| 47 | + for fair_col_val in fairness_col_counts.index |
| 48 | + } |
| 49 | + elif rule == "log": |
| 50 | + # number of samples in aug data will be proportional to the log frequency in the real data. |
| 51 | + # Note: taking the log makes the distribution more even. |
| 52 | + # N_aug(i) is proportional to log(N_real(i)) |
| 53 | + fairness_col_counts = X_train[fairness_column].value_counts() |
| 54 | + majority_size = fairness_col_counts.max() |
| 55 | + log_coefficient = majority_size / math.log(majority_size) |
| 56 | + |
| 57 | + augmentation_counts = { |
| 58 | + fair_col_val: ( |
| 59 | + majority_size - round(math.log(fair_col_count) * log_coefficient) |
| 60 | + ) |
| 61 | + for fair_col_val, fair_col_count in fairness_col_counts.items() |
| 62 | + } |
| 63 | + elif rule == "ad-hoc": |
| 64 | + # use user-specified values to augment |
| 65 | + if not ad_hoc_augment_vals: |
| 66 | + raise ValueError( |
| 67 | + "When augmenting with an `ad-hoc` method, ad_hoc_augment_vals must be a dictionary, where the dictionary keys are the values of the fairness_column and the dictionary values are the number of records to augment." |
| 68 | + ) |
| 69 | + else: |
| 70 | + if not set(ad_hoc_augment_vals.keys()).issubset( |
| 71 | + set(X_train[fairness_column].values) |
| 72 | + ): |
| 73 | + raise ValueError( |
| 74 | + "ad_hoc_augment_vals must be a dictionary, where the dictionary keys are the values of the fairness_column and the dictionary values are the number of records to augment." |
| 75 | + ) |
| 76 | + elif set(X_train[fairness_column].values) != set( |
| 77 | + ad_hoc_augment_vals.keys() |
| 78 | + ): |
| 79 | + ad_hoc_augment_vals = { |
| 80 | + k: v |
| 81 | + for k, v in ad_hoc_augment_vals.items() |
| 82 | + if k in set(X_train[fairness_column].values) |
| 83 | + } |
| 84 | + |
| 85 | + augmentation_counts = ad_hoc_augment_vals |
| 86 | + |
| 87 | + return augmentation_counts |
| 88 | + |
| 89 | + |
| 90 | +@validate_arguments(config=dict(arbitrary_types_allowed=True)) |
| 91 | +def _generate_synthetic_data( |
| 92 | + X_train: DataLoader, |
| 93 | + augment_generator: Any, |
| 94 | + strict: bool = True, |
| 95 | + rule: Literal["equal", "log", "ad-hoc"] = "equal", |
| 96 | + ad_hoc_augment_vals: Optional[ |
| 97 | + Dict[Any, int] |
| 98 | + ] = None, # Only required for rule == "ad-hoc" |
| 99 | + synthetic_constraints: Optional[Constraints] = None, |
| 100 | + **generate_kwargs: Any, |
| 101 | +) -> pd.DataFrame: |
| 102 | + """Generates synthetic data |
| 103 | +
|
| 104 | + Args: |
| 105 | + X_train (DataLoader): The dataset used to train the downstream model. |
| 106 | + augment_generator (Any): The synthetic model to be used to generate the synthetic portion of the augmented dataset. |
| 107 | + strict (bool, optional): Flag to ensure that the condition for generating synthetic data is strictly met. Defaults to False. |
| 108 | + rule (Literal["equal", "log", "ad-hoc"): The rule used to achieve the desired proportion records with each value in the fairness column. Defaults to "equal". |
| 109 | + ad_hoc_augment_vals (Dict[ Union[int, str], int ], optional): A dictionary containing the number of each class to augment the real data with. This is only required if using the rule="ad-hoc" option. Defaults to {}. |
| 110 | +
|
| 111 | + Returns: |
| 112 | + pd.DataFrame: The generated synthetic data. |
| 113 | + """ |
| 114 | + augmentation_counts = calculate_fair_aug_sample_size( |
| 115 | + X_train.dataframe(), |
| 116 | + X_train.get_fairness_column(), |
| 117 | + rule, |
| 118 | + ad_hoc_augment_vals=ad_hoc_augment_vals, |
| 119 | + ) |
| 120 | + if not strict: |
| 121 | + # set count equal to the total number of records required according to calculate_fair_aug_sample_size |
| 122 | + count = sum(augmentation_counts.values()) |
| 123 | + cond = pd.Series( |
| 124 | + np.repeat( |
| 125 | + list(augmentation_counts.keys()), list(augmentation_counts.values()) |
| 126 | + ) |
| 127 | + ) |
| 128 | + syn_data = augment_generator.generate( |
| 129 | + count=count, |
| 130 | + cond=cond, |
| 131 | + constraints=synthetic_constraints, |
| 132 | + **generate_kwargs, |
| 133 | + ).dataframe() |
| 134 | + else: |
| 135 | + syn_data_list = [] |
| 136 | + for fairness_value, count in augmentation_counts.items(): |
| 137 | + if count > 0: |
| 138 | + constraints = Constraints( |
| 139 | + rules=[(X_train.get_fairness_column(), "==", fairness_value)] |
| 140 | + ) |
| 141 | + syn_data_list.append( |
| 142 | + augment_generator.generate( |
| 143 | + count=count, constraints=constraints |
| 144 | + ).dataframe() |
| 145 | + ) |
| 146 | + syn_data = pd.concat(syn_data_list) |
| 147 | + return syn_data |
| 148 | + |
| 149 | + |
| 150 | +@validate_arguments(config=dict(arbitrary_types_allowed=True)) |
| 151 | +def augment_data( |
| 152 | + X_train: DataLoader, |
| 153 | + augment_generator: Any, |
| 154 | + strict: bool = False, |
| 155 | + rule: Literal["equal", "log", "ad-hoc"] = "equal", |
| 156 | + ad_hoc_augment_vals: Optional[ |
| 157 | + Dict[Any, int] |
| 158 | + ] = None, # Only required for rule == "ad-hoc" |
| 159 | + synthetic_constraints: Optional[Constraints] = None, |
| 160 | + **generate_kwargs: Any, |
| 161 | +) -> DataLoader: |
| 162 | + """Augment the real data with generated synthetic data |
| 163 | +
|
| 164 | + Args: |
| 165 | + X_train (DataLoader): The ground truth DataLoader to augment with synthetic data. |
| 166 | + augment_generator (Any): The synthetic model to be used to generate the synthetic portion of the augmented dataset. |
| 167 | + strict (bool, optional): Flag to ensure that the condition for generating synthetic data is strictly met. Defaults to False. |
| 168 | + rule (Literal["equal", "log", "ad-hoc"): The rule used to achieve the desired proportion records with each value in the fairness column. Defaults to "equal". |
| 169 | + ad_hoc_augment_vals (Dict[Union[int, str], int], optional): A dictionary containing the number of each class to augment the real data with. This is only required if using the rule="ad-hoc" option. Defaults to None. |
| 170 | + synthetic_constraints (Optional[Constraints]): Constraints placed on the generation of the synthetic data. Defaults to None. |
| 171 | +
|
| 172 | + Returns: |
| 173 | + DataLoader: The augmented dataset and labels. |
| 174 | + """ |
| 175 | + syn_data = _generate_synthetic_data( |
| 176 | + X_train, |
| 177 | + augment_generator, |
| 178 | + strict=strict, |
| 179 | + rule=rule, |
| 180 | + ad_hoc_augment_vals=ad_hoc_augment_vals, |
| 181 | + synthetic_constraints=synthetic_constraints, |
| 182 | + **generate_kwargs, |
| 183 | + ) |
| 184 | + |
| 185 | + augmented_data_loader = copy(X_train) |
| 186 | + augmented_data_loader.data = pd.concat( |
| 187 | + [ |
| 188 | + X_train.data, |
| 189 | + syn_data, |
| 190 | + ] |
| 191 | + ) |
| 192 | + |
| 193 | + return augmented_data_loader |
0 commit comments