Source code for vcnet.data

"""VCNet data module.
This module provides the classes to manage the data for VCNet."""

from typing import Callable, List, Tuple, Optional, Union

import pandas as pd
from sklearn.base import BaseEstimator
from sklearn.model_selection import train_test_split
from sklearn import preprocessing
from sklearn.impute import SimpleImputer
from numpy import bitwise_or, where
import numpy as np

from torch.utils.data.dataset import TensorDataset
from torch.utils.data import DataLoader
import torch

import lightning as L

# pylint: disable=C0103


[docs] class PostHocRounder: """ A class dedicated to rounding values to a given number of decimals. This is a post-hoc rounder, as it rounds the numerical values generated by VCNet to make them more realistic. The class implements only an `inverse_transform`, as it applies the transformation to the generated counterfactuals. Args: precisions (Dict(str,int)): map giving the precision (number of decimals) to apply to each attribute """ def __init__(self, precisions): self.precisions = precisions self.max_prec = 5
[docs] def inverse_transform(self, df): """Applies the inverse transformation to the dataframe `df`.""" for att, p in self.precisions.items(): if p > self.max_prec: continue df[att] = df[att].round(p) return df
[docs] def fit_rounder(df): """Builds a rounder from a dataframe. Parameters ---------- df: pd.DataFrame DataFrame containing only continuous data. Returns ------- PostHocRounder """ precisions = {} for att in df.columns: if pd.api.types.is_integer_dtype(df[att]): precisions[att] = 0 elif pd.api.types.is_float_dtype(df[att]): precisions[att] = max( df[att].astype(float).astype(str).apply(lambda x: len(x.split(".")[1])) ) return PostHocRounder(precisions)
[docs] def fit_scaler(scaling_method, df): """Fits a scaler on a dataframe. Parameters ---------- scaling_method: {"MinMax", "Standard", "Identity"} String indicating which scaling method to use, or an sklearn.preprocessing scaler. df: pd.DataFrame DataFrame containing only continuous data. Returns ------- sklearn.base.BaseEstimator """ # pylint: disable=E0606 if isinstance(scaling_method, str): if scaling_method == "MinMax": fitted_scaler = preprocessing.MinMaxScaler().fit(df) elif scaling_method == "Standard": fitted_scaler = preprocessing.StandardScaler().fit(df) elif scaling_method is None or "Identity": fitted_scaler = preprocessing.FunctionTransformer( func=None, inverse_func=None ) else: raise ValueError("Unknown scaling method") elif hasattr(scaling_method, "fit"): # check if function has fit attribute fitted_scaler = scaling_method.fit(df) else: fitted_scaler = None return fitted_scaler
[docs] def fit_imputer(imputation_method, df): """Fits an imputer of missing values on a dataframe. Parameters ---------- imputation_method: {"SimpleImputer", "Identity"} String indicating which imputation method to use, or an sklearn.impute imputer. df: pd.DataFrame DataFrame containing only continuous data. Returns ------- sklearn.base.BaseEstimator """ # pylint: disable=E0606 if isinstance(imputation_method, str): if imputation_method == "SimpleImputer": fitted_imputer = SimpleImputer().fit(df) elif imputation_method is None or "Identity": fitted_imputer = preprocessing.FunctionTransformer( func=None, inverse_func=None ) else: raise ValueError("Unknown imputation method") elif hasattr(imputation_method, "fit"): # check if function has fit attribute fitted_imputer = imputation_method.fit(df) else: fitted_imputer = None return fitted_imputer
[docs] def fit_encoder(encoding_method, df): """Fits an encoder of categorical attributes on a dataframe. Parameters ---------- encoding_method: {"OneHot", "OneHot_drop_binary", "Identity"} String indicating which encoding method to use, or an sklearn.preprocessing encoder. df: pd.DataFrame DataFrame containing only categorical data. Returns ------- sklearn.base.BaseEstimator """ # pylint: disable=E0606 if isinstance(encoding_method, str): if encoding_method == "OneHot": fitted_encoder = preprocessing.OneHotEncoder( handle_unknown="error", sparse_output=False ).fit(df) elif encoding_method == "OneHot_drop_binary": fitted_encoder = preprocessing.OneHotEncoder( drop="if_binary", handle_unknown="error", sparse_output=False ).fit(df) elif encoding_method is None or "Identity": fitted_encoder = preprocessing.FunctionTransformer( func=None, inverse_func=None ) elif hasattr(encoding_method, "fit"): # check if function has fit attribute fitted_encoder = encoding_method.fit(df) else: fitted_encoder = None return fitted_encoder
[docs] def scale( fitted_scaler: BaseEstimator, features: List[str], df: pd.DataFrame ) -> pd.DataFrame: """ Pipeline function to normalize data with a fitted sklearn scaler. Parameters ---------- fitted_scaler : sklearn Scaler Scaler used to normalize the input data features : list List of continuous features df : pd.DataFrame Data to normalize Returns ------- output : pd.DataFrame Whole DataFrame with normalized values """ output = df.copy() output[features] = fitted_scaler.transform(output[features]) return output
[docs] def descale( fitted_scaler: BaseEstimator, features: List[str], df: pd.DataFrame ) -> pd.DataFrame: """ Pipeline function to denormalize data with a fitted sklearn scaler. Parameters ---------- fitted_scaler : sklearn Scaler Scaler used to normalize the input data features : list List of continuous features df : pd.DataFrame Data to denormalize Returns ------- output : pd.DataFrame Whole DataFrame with denormalized values """ output = df.copy() output[features] = fitted_scaler.inverse_transform(output[features]) return output
[docs] def encode( fitted_encoder: BaseEstimator, features: List[str], df: pd.DataFrame ) -> pd.DataFrame: """ Pipeline function to encode data with a fitted sklearn OneHotEncoder. Parameters ---------- fitted_encoder : sklearn OneHotEncoder Encoder of the input data. features : list List of categorical features. df : pd.DataFrame Data to encode Returns ------- output : pd.DataFrame Whole DataFrame with encoded values """ output = df.copy() encoded_features = fitted_encoder.get_feature_names_out(features) output[encoded_features] = fitted_encoder.transform(output[features]) output = output.drop(features, axis=1) return output
[docs] def decode( fitted_encoder: BaseEstimator, features: List[str], df: pd.DataFrame ) -> pd.DataFrame: """ Pipeline function to decode data with a fitted sklearn OneHotEncoder. Parameters ---------- fitted_encoder : sklearn OneHotEncoder Encoder of the input data. features : list List of categorical features. df : pd.DataFrame Data to decode Returns ------- output : pd.DataFrame Whole DataFrame with decoded values """ output = df.copy() encoded_features = fitted_encoder.get_feature_names_out(features) # Prevent errors for datasets without categorical data # inverse_transform cannot handle these cases if len(encoded_features) == 0: return output output[features] = fitted_encoder.inverse_transform(output[encoded_features]) output = output.drop(encoded_features, axis=1) return output
[docs] def impute( fitted_imputer: BaseEstimator, features: List[str], df: pd.DataFrame ) -> pd.DataFrame: """ Pipeline function to impute missing values in the dataset with a fitted sklearn imputer. In the preparation pipeline of :py:class:`DataCatalog`, it is applied after the scaling. Parameters ---------- fitted_imputer : sklearn Imputer Imputer of missing values. features : list List of numerical features. df : pd.DataFrame Data to modify Returns ------- output : pd.DataFrame Whole DataFrame without missing values (in the selected features) """ output = df.copy() output[features] = fitted_imputer.transform(output[features]) return output
[docs] def attribute_round( fitted_rounder: PostHocRounder, features: List[str], df: pd.DataFrame ) -> pd.DataFrame: """ Pipeline function to round the numerical attributes of the data. Parameters ---------- fitted_rounder : PostHocRounder Rounds the attributes of the data to a fitted level of precision features : list List of continuous features df : pd.DataFrame Data to round Returns ------- output : pd.DataFrame Whole DataFrame with rounded values """ output = df.copy() output[features] = fitted_rounder.inverse_transform(output[features]) return output
[docs] def order_data(feature_order: List[str], df: pd.DataFrame) -> pd.DataFrame: """ Restores the correct order of the input features for the ML model. Only works for encoded data. Parameters ---------- feature_order : list List of input features in the correct order df : pd.DataFrame Data to reorder Returns ------- output : pd.DataFrame Whole DataFrame with ordered features """ return df[feature_order]
[docs] class NumpyDataset(TensorDataset): """Dataset with only numerical attributes. A numpy dataset is represented by a tensor with attributes in columns. When it is a training dataset, the last column is the numerical target feature. """ def __init__( self, *arrs, ): super(NumpyDataset, self).__init__() # init tensors # small patch: skip continuous or discrete arrays without content self.tensors = [torch.tensor(arr).float() for arr in arrs if arr.shape[-1] != 0] assert all(self.tensors[0].size(0) == tensor.size(0) for tensor in self.tensors)
[docs] def data_loader(self, batch_size=128, shuffle=True, num_workers=4): """Builds a torch data loader to be used for training VCNet. Args: batch_size (int, optional): Size of the batches. Defaults to 128. shuffle (bool, optional): Whether to shuffle the examples before creating batches. Defaults to True. num_workers (int, optional): Number of workers. Defaults to 4. Returns: torch.DataLoader: representation of a dataset for mini-batch optimization """ return DataLoader( self, batch_size=batch_size, shuffle=shuffle, num_workers=num_workers )
[docs] def features(self, test=False): """Returns the feature part of the tensors. Args: test (bool, optional): indicates whether the dataset contains labels (False) or not (True). Defaults to False. """ return tuple(self.tensors[:-1] if not test else self.tensors)
[docs] def target(self, test=False): """Returns the labels of the dataset (if they exist, otherwise it returns None). Args: test (bool, optional): indicates whether the dataset contains labels (False) or not (True). Defaults to False. """ return self.tensors[-1] if not test else None
[docs] class DataCatalog(L.LightningDataModule): """Generic framework for tabular datasets, using sklearn preprocessing. The preprocessing pipeline is made of the following steps: scaling of numerical attributes, imputation of missing values and encoding of categorical attributes. The reverse pipeline decodes the categorical attributes, reverses the scaling and can also round the numerical attributes. Args: config: Dict Configuration dictionary containing the required and optional settings to prepare the dataset for counterfactual generation. The settings are used to set up an internal pipeline (and its reverse pipeline). The settings must at least define the following attributes: * `target` (`str`): name of the target attribute * `continuous` (`List[str]`): list of continuous attributes of the dataset * `categorical` (`List[str]`): list of categorical attributes of the dataset * `immutables` (`List[str]`): list of immutable attributes (among the continuous or categorical attributes) If the dataset is stored in a file, it can be loaded in the pipeline by setting the `filename` attribute. The following optional settings define the train/test sets: * `test_size`/`val_size` (`float`): proportions of the dataset dedicated to test and validation * `stratify` (`bool`): use a stratification strategy to sample the test/train sets The following optional settings define the preprocessing pipeline: * `scaling_method` (`str`, default: "MinMax"): type of sklearn scaler. It can be set with the property setter to any sklearn scaler. Set to "Identity" for no scaling. * `encoding_method` (`str`, default: "OneHot_drop_binary"): type of one-hot encoding ("OneHot" or "OneHot_drop_binary"). "OneHot_drop_binary" drops one of the two columns of binary features. It can be set with the property setter to any sklearn encoder. Set to "Identity" for no encoding. * `imputation_method` (`str`, default: "Identity"): type of sklearn imputer ("SimpleImputer" or "Identity"). Set to "Identity" for no imputation. * `activate_rounding` (`bool`, default: `False`): if `True`, the values of the continuous attributes of generated counterfactuals are rounded to be more realistic. Finally, other optional parameters: * `batch_size` (`int`): default value is 64 Attributes: df: pandas.DataFrame The complete DataFrame (restricted to the attributes listed in the settings). This is the combination of `df_train`, `df_val` and `df_test` before preprocessing, although not shuffled. df_train: pandas.DataFrame Training portion of the complete DataFrame. df_test: pandas.DataFrame Test portion of the complete DataFrame. df_val: pandas.DataFrame Validation portion of the complete DataFrame. .. warning:: Imputation works only for continuous variables. .. warning:: The names of the attributes and of the target are not checked at this stage, but when the dataset is prepared. .. warning:: Rounding is applied to all numerical attributes or to none of them. You cannot choose the attributes to which the rounding is applied. Nonetheless, the rounding precision (number of decimals) is automatically inferred from the training data for each attribute (two attributes can have different precisions). """ def __init__(self, config: dict): super().__init__() self._config = config try: self._target = config["target"] except KeyError: print("A 'target' attribute must be defined in the settings") raise try: self._categorical = config["categorical"] except KeyError: self._categorical = [] try: self._continuous = config["continuous"] except KeyError: self._continuous = [] if len(self._continuous+self._categorical)==0: raise KeyError("At least one attribute has to be provided with 'categorical' or 'continuous'.") try: self._immutables = config["immutables"] except KeyError: self._immutables = [] self._immutables_pos = None self.df = None # Define default attribute values if not "batch_size" in self._config: self._config["batch_size"] = 64 self._raw_df_test = None self._df_test = None self._df_val = None self._df_train = None self._raw_df_train = None self._raw_df_val = None self._identity_encoding = None self.imputer = None self.rounder = None self._class_encoder = None self._inverse_pipeline = None self._pipeline = None
[docs] def prepare_data(self, raw_pd: Optional[pd.DataFrame] = None): """Prepares the data: splits the dataset and fits the preprocessing pipeline. Args: raw_pd (pd.DataFrame, optional): a pandas dataframe containing the data to prepare. If None, the data are loaded from the `filename` setting. Defaults to None. Returns: Dict or None: updated settings, ready to be used in a VCNet model. None means that the data preparation failed. """ self.df = None # Use the dataframe in parameters if not isinstance(raw_pd, pd.DataFrame): # Load the raw data from the file in the config try: self.df = pd.read_csv(self._config["filename"]) except KeyError: print("Neither a dataset nor a `filename` is provided in the dataset settings.") raise else: self.df = raw_pd.copy() try: self.df = self.df[ self._categorical + self._continuous + [self._target] ] # keep only variables that have been listed except KeyError: print("Invalid attribute name(s) in the settings.") raise if self._target in self.categorical: raise KeyError( "Target attribute must not appear in the categorical features." ) if self._target in self._continuous: raise KeyError( "Target attribute must not appear in the continuous features." ) if "test_size" in self._config: test_size = self._config["test_size"] else: test_size = 0.33 if "val_size" in self._config: val_size = self._config["val_size"] else: val_size = 0.33 if "stratify" in self._config and self._config["stratify"]: stratify = self.df[self._target].to_numpy() else: stratify = None other_raw, self._raw_df_test = train_test_split( self.df, test_size=test_size, stratify=stratify ) self._df_test = self._raw_df_test if val_size > 0: if not stratify is None: stratify = other_raw[self._target].to_numpy() self._raw_df_train, self._raw_df_val = train_test_split( other_raw, test_size=val_size, stratify=stratify ) self._df_val = self._raw_df_val self._df_train = self._raw_df_train else: self._df_val = None self._df_train = other_raw if "scaling_method" not in self._config: self._config["scaling_method"]="MinMax" if "encoding_method" not in self._config: self._config["encoding_method"]="OneHot_drop_binary" ## TG: TODO fit the transformers on train only (?) self.scaler: BaseEstimator = fit_scaler( self._config["scaling_method"], self.df[self.continuous] ) self.encoder: BaseEstimator = fit_encoder( self._config["encoding_method"], self.df[self.categorical] ) self._identity_encoding = ( self._config["encoding_method"] is None or self._config["encoding_method"] == "Identity" ) if "imputation_method" in self._config: self.imputer: BaseEstimator = fit_imputer( self._config["imputation_method"], self.df[self.continuous] ) else: self.imputer: BaseEstimator = fit_imputer( "Identity", self.df[self.continuous] ) if "activate_rounding" in self._config and self._config["activate_rounding"]: self.rounder = fit_rounder(self.df[self.continuous]) else: self.rounder = preprocessing.FunctionTransformer( func=None, inverse_func=None ) # Preparing pipeline components self._pipeline = self.__init_pipeline() self._inverse_pipeline = self.__init_inverse_pipeline() ######### # Fit the class transformer # create values from categories # if self.df[self._target].dtype == "O": # self.df[self._target] = self.df[self._target].astype("category").cat.codes self._class_encoder: BaseEstimator = preprocessing.OneHotEncoder( handle_unknown="error", sparse_output=False ).fit(self.df[[self._target]].to_numpy()) # automatic set up of the number of classes self._config["class_size"] = len( self._class_encoder.categories_[0] ) # len(self.df[self._target].unique()) ######### # Fit scaler and encoder # Process the data (it calls the transformation pipeline for each dataset) self._df_train = self.transform(self.df_train) self._df_test = self.transform(self.df_test) if isinstance(self._df_val, pd.DataFrame): self._df_val = self.transform(self.df_val) # change the list of immutables based on attributes names if len(self._immutables) > 0: self._immutables = self.df_train.columns[ bitwise_or.reduce( [self.df_train.columns.str.startswith(x) for x in self._immutables] ) ] self._immutables_pos = where( bitwise_or.reduce( [self.df_train.columns.str.startswith(x) for x in self._immutables] ) )[0] else: self._immutables_pos = [] # shift the positions of the immutable attributes if the target comes before them target_pos = where(self.df_train.columns == self._target)[0] self._immutables_pos = [ x if x < target_pos else x - 1 for x in self._immutables_pos ] self._config["feature_size"] = ( len(self.df_train.columns) - 1 ) # removed the target self._config["feature_size_immutable"] = len(self._immutables_pos) self._config["feature_size_mutable"] = ( len(self.df_train.columns) - 1 - self._config["feature_size_immutable"] ) self._config["immutables_pos"] = self._immutables_pos return self._config
[docs] def train_dataloader(self) -> DataLoader: train_X = self.df_train.drop(columns=[self.target]).to_numpy() # train_y = self.df_train[self.target].to_numpy() train_y = self._class_encoder.transform(self.df_train[[self.target]].to_numpy()) return DataLoader( NumpyDataset(train_X, train_y), batch_size=self._config["batch_size"], pin_memory=True, shuffle=True, num_workers=7, )
[docs] def val_dataloader(self) -> DataLoader: if not self._df_val: return None val_X = self.df_val.drop(columns=[self.target]).to_numpy() val_y = self._class_encoder.transform(self.df_val[[self.target]].to_numpy()) return DataLoader( NumpyDataset(val_X, val_y), batch_size=self._config["batch_size"], pin_memory=True, shuffle=True, num_workers=7, )
[docs] def test_dataloader(self) -> DataLoader: test_X = self.df_test.drop(columns=[self.target]).to_numpy() test_y = self._class_encoder.transform(self.df_test[[self.target]].to_numpy()) test_dataset = NumpyDataset(test_X, test_y) return DataLoader( test_dataset, batch_size=len(test_dataset), pin_memory=True, shuffle=False, num_workers=7, )
[docs] def data_unloader( self, X: torch.tensor, y: Union[torch.tensor, np.array] ) -> pd.DataFrame: """Recreates a dataframe from the numerical tensors of data and labels used internally by VCNet models. It applies the inverse transformation to the data structures required internally by VCNet. Depending on the dataset parameters, it reverses the one-hot encoding to recreate categorical features readable by the user; it reverses the scaling of numerical attributes and can also round them; finally, it decodes the class labels from the probabilistic predictions. Args: X (torch.tensor): examples, as represented internally by VCNet y (torch.tensor or np.array): class probabilities of the examples Returns: DataFrame: dataframe with the same columns as the input dataframe .. warning:: If the preprocessing included the imputation of missing values, this step is not reversed and the output dataset contains the imputed values. """ l = list(self.df_train.columns) l.remove(self.target) l = l + [self.target] if torch.is_tensor(y): y_codes = self._class_encoder.inverse_transform(y.detach().cpu()) else: y_codes = self._class_encoder.inverse_transform(y) df = pd.DataFrame( np.concatenate([X.detach().cpu(), y_codes], axis=1), columns=l ) return self.inverse_transform(df)
[docs] def class_encoding(self, y): """Computes the internal encoding of the given class labels. Args: y: vector of class labels Returns: The probabilistic representation of the classes (one-hot encoding) """ if y.ndim == 1: y = y.reshape(-1, 1) return self._class_encoder.transform(y)
@property def settings(self): """Settings of the dataset""" return self._config @property def df_train(self) -> pd.DataFrame: """Dataframe containing prepared train data""" return self._df_train.copy() @property def df_test(self) -> pd.DataFrame: """Dataframe containing prepared test data""" return self._df_test.copy() @property def df_val(self) -> pd.DataFrame: """Dataframe containing prepared validation data""" return self._df_val.copy() @property def raw_df_train(self) -> pd.DataFrame: """Dataframe containing raw train data""" return self._raw_df_train.copy() @property def raw_df_test(self) -> pd.DataFrame: """Dataframe containing raw test data""" return self._raw_df_test.copy() @property def raw_df_val(self) -> pd.DataFrame: """Dataframe containing raw validation data""" return self._raw_df_val.copy() @property def scaler(self) -> BaseEstimator: """ Contains a fitted sklearn scaler. Returns ------- sklearn.preprocessing.BaseEstimator """ return self._scaler @property def categorical(self) -> List[str]: """List of categorical attributes""" return self._categorical @property def continuous(self) -> List[str]: """List of numerical attributes""" return self._continuous @property def immutables(self) -> List[str]: """List of immutable attributes""" return self._immutables @property def target(self) -> str: """Name of the target attribute""" return self._target @scaler.setter def scaler(self, scaler: BaseEstimator): """ Sets a new fitted sklearn scaler. Parameters ---------- scaler : sklearn.preprocessing.Scaler Fitted scaler for ML model. Returns ------- sklearn.preprocessing.BaseEstimator """ self._scaler = scaler @property def encoder(self) -> BaseEstimator: """ Contains a fitted sklearn encoder. Returns ------- sklearn.preprocessing.BaseEstimator """ return self._encoder @encoder.setter def encoder(self, encoder: BaseEstimator): """ Sets a new fitted sklearn encoder. Parameters ---------- encoder: sklearn.preprocessing.Encoder Fitted encoder for ML model. """ self._encoder = encoder @property def imputer(self) -> BaseEstimator: """ Contains a fitted sklearn imputer. Returns ------- sklearn.preprocessing.BaseEstimator """ return self._imputer @imputer.setter def imputer(self, imputer: BaseEstimator): """ Sets a new fitted sklearn imputer. Parameters ---------- imputer: sklearn.impute.Imputer Fitted imputer of missing values. """ self._imputer = imputer
[docs] def transform(self, df: pd.DataFrame) -> pd.DataFrame: """ Transforms raw data into the form expected by the models. Only applicable to DataFrames that have not been preprocessed yet. It is recommended to use it to keep consistent encodings and normalization. Parameters ---------- df : pd.DataFrame Contains raw (not normalized and not encoded) data. Returns ------- output : pd.DataFrame Prediction input normalized and encoded """ output = df.copy() for trans_name, trans_function in self._pipeline: if trans_name == "encoder" and self._identity_encoding: continue else: output = trans_function(output) return output
[docs] def inverse_transform(self, df: pd.DataFrame) -> pd.DataFrame: """ Transforms the output of the models back into the original form of the data. Only applicable to preprocessed DataFrames. Parameters ---------- df : pd.DataFrame Contains normalized and encoded data. Returns ------- output : pd.DataFrame Prediction output denormalized and decoded """ output = df.copy() for trans_name, trans_function in self._inverse_pipeline: if trans_name == "encoder" and self._identity_encoding: continue else: output = trans_function(output) return output
[docs] def get_pipeline_element(self, key: str) -> Callable: """ Returns a specific element of the transformation pipeline. Parameters ---------- key : str Name of the pipeline element to return Returns ------- Pipeline element """ key_idx = list(zip(*self._pipeline))[0].index(key) # find key in pipeline return self._pipeline[key_idx][1]
def __init_pipeline(self) -> List[Tuple[str, Callable]]: return [ ("scaler", lambda x: scale(self.scaler, self.continuous, x)), ("imputer", lambda x: impute(self.imputer, self.continuous, x)), ("encoder", lambda x: encode(self.encoder, self.categorical, x)), ] def __init_inverse_pipeline(self) -> List[Tuple[str, Callable]]: return [ ("encoder", lambda x: decode(self.encoder, self.categorical, x)), ("scaler", lambda x: descale(self.scaler, self.continuous, x)), ("rounder", lambda x: attribute_round(self.rounder, self.continuous, x)), ]