|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +from typing import List, Optional |
| 4 | +from dataclasses import dataclass |
| 5 | + |
| 6 | +from numpy import concatenate, ndarray, zeros, ones, expand_dims, reshape, sum as npsum, repeat, array_split, asarray |
| 7 | +from pandas import DataFrame |
| 8 | +from typeguard import typechecked |
| 9 | + |
| 10 | +from ydata_synthetic.preprocessing.regular.processor import RegularDataProcessor |
| 11 | + |
| 12 | + |
| 13 | +@dataclass |
| 14 | +class ColumnMetadata: |
| 15 | + """ |
| 16 | + Dataclass that stores the metadata of each column. |
| 17 | + """ |
| 18 | + discrete: bool |
| 19 | + output_dim: int |
| 20 | + name: str |
| 21 | + |
| 22 | + |
| 23 | +@typechecked |
| 24 | +class DoppelGANgerProcessor(RegularDataProcessor): |
| 25 | + """ |
| 26 | + Main class for class the DoppelGANger preprocessing. |
| 27 | + It works like any other transformer in scikit learn with the methods fit, transform and inverse transform. |
| 28 | + Args: |
| 29 | + num_cols (list of strings): |
| 30 | + List of names of numerical columns. |
| 31 | + measurement_cols (list of strings): |
| 32 | + List of measurement columns. |
| 33 | + sequence_length (int): |
| 34 | + Sequence length. |
| 35 | + """ |
| 36 | + SUPPORTED_MODEL = 'DoppelGANger' |
| 37 | + |
| 38 | + def __init__(self, num_cols: Optional[List[str]] = None, |
| 39 | + cat_cols: Optional[List[str]] = None, |
| 40 | + measurement_cols: Optional[List[str]] = None, |
| 41 | + sequence_length: Optional[int] = None): |
| 42 | + super().__init__(num_cols, cat_cols) |
| 43 | + |
| 44 | + if num_cols is None: |
| 45 | + num_cols = [] |
| 46 | + if cat_cols is None: |
| 47 | + cat_cols = [] |
| 48 | + if measurement_cols is None: |
| 49 | + measurement_cols = [] |
| 50 | + self.sequence_length = sequence_length |
| 51 | + self._measurement_num_cols = [c for c in self.num_cols if c in measurement_cols] |
| 52 | + self._measurement_cat_cols = [c for c in self.cat_cols if c in measurement_cols] |
| 53 | + self._attribute_num_cols = [c for c in self.num_cols if c not in measurement_cols] |
| 54 | + self._attribute_cat_cols = [c for c in self.cat_cols if c not in measurement_cols] |
| 55 | + self._measurement_cols_metadata = None |
| 56 | + self._attribute_cols_metadata = None |
| 57 | + self._measurement_one_hot_cat_cols = None |
| 58 | + self._attribute_one_hot_cat_cols = None |
| 59 | + self._has_attributes = self._attribute_num_cols or self._attribute_cat_cols |
| 60 | + |
| 61 | + @property |
| 62 | + def measurement_cols_metadata(self): |
| 63 | + return self._measurement_cols_metadata |
| 64 | + |
| 65 | + @property |
| 66 | + def attribute_cols_metadata(self): |
| 67 | + return self._attribute_cols_metadata |
| 68 | + |
| 69 | + def add_gen_flag(self, data_features: ndarray, sample_len: int): |
| 70 | + num_sample = data_features.shape[0] |
| 71 | + length = data_features.shape[1] |
| 72 | + if length % sample_len != 0: |
| 73 | + raise Exception("length must be a multiple of sample_len") |
| 74 | + data_gen_flag = ones((num_sample, length)) |
| 75 | + data_gen_flag = expand_dims(data_gen_flag, 2) |
| 76 | + shift_gen_flag = concatenate( |
| 77 | + [data_gen_flag[:, 1:, :], |
| 78 | + zeros((data_gen_flag.shape[0], 1, 1))], |
| 79 | + axis=1) |
| 80 | + data_gen_flag_t = reshape( |
| 81 | + data_gen_flag, |
| 82 | + [num_sample, int(length / sample_len), sample_len]) |
| 83 | + data_gen_flag_t = npsum(data_gen_flag_t, 2) |
| 84 | + data_gen_flag_t = data_gen_flag_t > 0.5 |
| 85 | + data_gen_flag_t = repeat(data_gen_flag_t, sample_len, axis=1) |
| 86 | + data_gen_flag_t = expand_dims(data_gen_flag_t, 2) |
| 87 | + data_features = concatenate( |
| 88 | + [data_features, |
| 89 | + shift_gen_flag, |
| 90 | + (1 - shift_gen_flag) * data_gen_flag_t], |
| 91 | + axis=2) |
| 92 | + |
| 93 | + return data_features |
| 94 | + |
| 95 | + def transform(self, X: DataFrame) -> tuple[ndarray, ndarray]: |
| 96 | + """Transforms the passed DataFrame with the fit DataProcessor. |
| 97 | + Args: |
| 98 | + X (DataFrame): |
| 99 | + DataFrame used to fit the processor parameters. |
| 100 | + Should be aligned with the columns types defined in initialization. |
| 101 | + Returns: |
| 102 | + transformed (ndarray, ndarray): |
| 103 | + Processed version of the passed DataFrame. |
| 104 | + """ |
| 105 | + self._check_is_fitted() |
| 106 | + |
| 107 | + measurement_cols = self._measurement_num_cols + self._measurement_cat_cols |
| 108 | + if not measurement_cols: |
| 109 | + raise ValueError("At least one measurement column must be supplied.") |
| 110 | + if not all(c in self.num_cols + self.cat_cols for c in measurement_cols): |
| 111 | + raise ValueError("At least one of the supplied measurement columns does not exist in the dataset.") |
| 112 | + if self.sequence_length is None: |
| 113 | + raise ValueError("The sequence length is mandatory.") |
| 114 | + |
| 115 | + num_data = DataFrame(self.num_pipeline.transform(X[self.num_cols]) if self.num_cols else zeros([len(X), 0]), columns=self.num_cols) |
| 116 | + one_hot_cat_cols = self.cat_pipeline.get_feature_names_out() |
| 117 | + cat_data = DataFrame(self.cat_pipeline.transform(X[self.cat_cols]) if self.cat_cols else zeros([len(X), 0]), columns=one_hot_cat_cols) |
| 118 | + |
| 119 | + self._measurement_one_hot_cat_cols = [c for c in one_hot_cat_cols if c.split("_")[0] in self._measurement_cat_cols] |
| 120 | + measurement_num_data = num_data[self._measurement_num_cols].to_numpy() if self._measurement_num_cols else zeros([len(X), 0]) |
| 121 | + self._measurement_cols_metadata = [ColumnMetadata(discrete=False, output_dim=1, name=c) for c in self._measurement_num_cols] |
| 122 | + measurement_cat_data = cat_data[self._measurement_one_hot_cat_cols].to_numpy() if self._measurement_one_hot_cat_cols else zeros([len(X), 0]) |
| 123 | + self._measurement_cols_metadata += [ColumnMetadata(discrete=True, output_dim=X[c].nunique(), name=c) for c in self._measurement_cat_cols] |
| 124 | + data_features = concatenate([measurement_num_data, measurement_cat_data], axis=1) |
| 125 | + |
| 126 | + if self._has_attributes: |
| 127 | + self._attribute_one_hot_cat_cols = [c for c in one_hot_cat_cols if c.split("_")[0] in self._attribute_cat_cols] |
| 128 | + attribute_num_data = num_data[self._attribute_num_cols].to_numpy() if self._attribute_num_cols else zeros([len(X), 0]) |
| 129 | + self._attribute_cols_metadata = [ColumnMetadata(discrete=False, output_dim=1, name=c) for c in self._attribute_num_cols] |
| 130 | + attribute_cat_data = cat_data[self._attribute_one_hot_cat_cols].to_numpy() if self._attribute_one_hot_cat_cols else zeros([len(X), 0]) |
| 131 | + self._attribute_cols_metadata += [ColumnMetadata(discrete=True, output_dim=X[c].nunique(), name=c) for c in self._attribute_cat_cols] |
| 132 | + data_attributes = concatenate([attribute_num_data, attribute_cat_data], axis=1) |
| 133 | + else: |
| 134 | + self._attribute_one_hot_cat_cols = [] |
| 135 | + data_attributes = zeros((data_features.shape[0], 1)) |
| 136 | + self._attribute_cols_metadata = [ColumnMetadata(discrete=False, output_dim=1, name="zeros_attribute")] |
| 137 | + |
| 138 | + num_samples = int(X.shape[0] / self.sequence_length) |
| 139 | + data_features = asarray(array_split(data_features, num_samples)) |
| 140 | + data_attributes = asarray(array_split(data_attributes, num_samples)) |
| 141 | + |
| 142 | + data_features = self.add_gen_flag(data_features, sample_len=self.sequence_length) |
| 143 | + self._measurement_cols_metadata += [ColumnMetadata(discrete=True, output_dim=2, name="gen_flags")] |
| 144 | + return data_features, data_attributes.mean(axis=1) |
| 145 | + |
| 146 | + def inverse_transform(self, X_features: ndarray, X_attributes: ndarray) -> list[DataFrame]: |
| 147 | + """Inverts the data transformation pipelines on a passed DataFrame. |
| 148 | + Args: |
| 149 | + X_features (ndarray): |
| 150 | + Numpy array with the measurement data to be brought back to the original format. |
| 151 | + X_attributes (ndarray): |
| 152 | + Numpy array with the attribute data to be brought back to the original format. |
| 153 | + Returns: |
| 154 | + result (DataFrame): |
| 155 | + DataFrame with all performed transformations inverted. |
| 156 | + """ |
| 157 | + self._check_is_fitted() |
| 158 | + |
| 159 | + num_samples = X_attributes.shape[0] |
| 160 | + if self._has_attributes: |
| 161 | + X_attributes = repeat(X_attributes.reshape((num_samples, 1, X_attributes.shape[1])), repeats=X_features.shape[1], axis=1) |
| 162 | + generated_data = concatenate((X_features, X_attributes), axis=2) |
| 163 | + else: |
| 164 | + generated_data = X_features |
| 165 | + output_cols = self._measurement_num_cols + self._measurement_one_hot_cat_cols + self._attribute_num_cols + self._attribute_one_hot_cat_cols |
| 166 | + one_hot_cat_cols = self._measurement_one_hot_cat_cols + self._attribute_one_hot_cat_cols |
| 167 | + |
| 168 | + samples = [] |
| 169 | + for i in range(num_samples): |
| 170 | + df = DataFrame(generated_data[i], columns=output_cols) |
| 171 | + df_num = self.num_pipeline.inverse_transform(df[self.num_cols]) if self.num_cols else zeros([len(df), 0]) |
| 172 | + df_cat = self.cat_pipeline.inverse_transform(df[one_hot_cat_cols].round(0)) if self.cat_cols else zeros([len(df), 0]) |
| 173 | + df = DataFrame(concatenate((df_num, df_cat), axis=1), columns=self.num_cols+self.cat_cols) |
| 174 | + df = df.loc[:, self._col_order_] |
| 175 | + for col in df.columns: |
| 176 | + df[col] = df[col].astype(self._types[col]) |
| 177 | + samples.append(df) |
| 178 | + |
| 179 | + return samples |
0 commit comments