|
| 1 | +"""Feature Drift evaluator""" |
| 2 | +from credoai.artifacts import ClassificationModel |
| 3 | +from credoai.evaluators import Evaluator |
| 4 | +from credoai.evaluators.utils.validation import check_requirements_existence |
| 5 | +from credoai.evidence import MetricContainer |
| 6 | +from credoai.evidence.containers import TableContainer |
| 7 | +from credoai.modules.credoai_metrics import population_stability_index |
| 8 | +from pandas import DataFrame, Series |
| 9 | + |
| 10 | + |
| 11 | +class FeatureDrift(Evaluator): |
| 12 | + """ |
| 13 | + Measure Feature Drift using population stability index. |
| 14 | +
|
| 15 | + This evaluator measures feature drift in: |
| 16 | +
|
| 17 | + 1. Model prediction: the prediction for the assessment dataset is compared |
| 18 | + to the prediction for the training dataset. |
| 19 | + In the case of classifiers, the prediction is performed with predict proba if available. |
| 20 | + If it is not available, the prediction is treated like a categorical variable, see the |
| 21 | + processing of categorical variables in the item below. |
| 22 | +
|
| 23 | + 2. Dataset features: 1 to 1 comparison across all features for the datasets. This is also |
| 24 | + referred to as "characteristic stability index" (CSI). |
| 25 | + - Numerical features are directly fed into the population_stability_index metric, and |
| 26 | + binned according to the parameters specified at init time. |
| 27 | + - Categorical features percentage distribution is manually calculated. The % amount of |
| 28 | + samples per each class is calculated and then fed into the population_stability_index metric. |
| 29 | + The percentage flag in the metric is set to True, to bypass the internal binning process. |
| 30 | +
|
| 31 | +
|
| 32 | + Parameters |
| 33 | + ---------- |
| 34 | + buckets : int, optional |
| 35 | + Number of buckets to consider to bin the predictions, by default 10 |
| 36 | + buckettype : Literal["bins", "quantiles"] |
| 37 | + Type of strategy for creating buckets, bins splits into even splits, |
| 38 | + quantiles splits into quantiles buckets, by default "bins" |
| 39 | + csi_calculation : bool, optional |
| 40 | + Calculate characteristic stability index, i.e., PSI for all features in the datasets, |
| 41 | + by default False |
| 42 | + """ |
| 43 | + |
| 44 | + def __init__(self, buckets: int = 10, buckettype="bins", csi_calculation=False): |
| 45 | + |
| 46 | + self.bucket_number = buckets |
| 47 | + self.buckettype = buckettype |
| 48 | + self.csi_calculation = csi_calculation |
| 49 | + self.percentage = False |
| 50 | + super().__init__() |
| 51 | + |
| 52 | + required_artifacts = {"model", "assessment_data", "training_data"} |
| 53 | + |
| 54 | + def _validate_arguments(self): |
| 55 | + check_requirements_existence(self) |
| 56 | + |
| 57 | + def _setup(self): |
| 58 | + # Default prediction to predict method |
| 59 | + prediction_method = self.model.predict |
| 60 | + if isinstance(self.model, ClassificationModel): |
| 61 | + if hasattr(self.model, "predict_proba"): |
| 62 | + prediction_method = self.model.predict_proba |
| 63 | + else: |
| 64 | + self.percentage = True |
| 65 | + |
| 66 | + self.expected_prediction = prediction_method(self.training_data.X) |
| 67 | + self.actual_prediction = prediction_method(self.assessment_data.X) |
| 68 | + |
| 69 | + # Create the bins manually for categorical prediction if predict_proba |
| 70 | + # is not available. |
| 71 | + if self.percentage: |
| 72 | + ( |
| 73 | + self.expected_prediction, |
| 74 | + self.actual_prediction, |
| 75 | + ) = self._create_bin_percentage( |
| 76 | + self.expected_prediction, self.actual_prediction |
| 77 | + ) |
| 78 | + |
| 79 | + def evaluate(self): |
| 80 | + prediction_psi = self._calculate_psi_on_prediction() |
| 81 | + self.results = [MetricContainer(prediction_psi, **self.get_container_info())] |
| 82 | + if self.csi_calculation: |
| 83 | + csi = self._calculate_csi() |
| 84 | + self.results.append(TableContainer(csi, **self.get_container_info())) |
| 85 | + return self |
| 86 | + |
| 87 | + def _calculate_psi_on_prediction(self) -> DataFrame: |
| 88 | + """ |
| 89 | + Calculate the psi index on the model prediction. |
| 90 | +
|
| 91 | + Returns |
| 92 | + ------- |
| 93 | + DataFrame |
| 94 | + Formatted for metric container. |
| 95 | + """ |
| 96 | + psi = population_stability_index( |
| 97 | + self.expected_prediction, |
| 98 | + self.actual_prediction, |
| 99 | + percentage=self.percentage, |
| 100 | + buckets=self.bucket_number, |
| 101 | + buckettype=self.buckettype, |
| 102 | + ) |
| 103 | + res = DataFrame({"value": psi, "type": "population_stability_index"}, index=[0]) |
| 104 | + return res |
| 105 | + |
| 106 | + def _calculate_csi(self) -> DataFrame: |
| 107 | + """ |
| 108 | + Calculate psi for all the columns in the dataframes. |
| 109 | +
|
| 110 | + Returns |
| 111 | + ------- |
| 112 | + DataFrame |
| 113 | + Formatted for the table container. |
| 114 | + """ |
| 115 | + columns_names = list(self.assessment_data.X.columns) |
| 116 | + psis = {} |
| 117 | + for col_name in columns_names: |
| 118 | + train_data = self.training_data.X[col_name] |
| 119 | + assess_data = self.assessment_data.X[col_name] |
| 120 | + if self.assessment_data.X[col_name].dtype == "category": |
| 121 | + train, assess = self._create_bin_percentage(train_data, assess_data) |
| 122 | + psis[col_name] = population_stability_index(train, assess, True) |
| 123 | + else: |
| 124 | + psis[col_name] = population_stability_index(train_data, assess_data) |
| 125 | + psis = DataFrame.from_dict(psis, orient="index") |
| 126 | + psis = psis.reset_index() |
| 127 | + psis.columns = ["feature_names", "value"] |
| 128 | + psis.name = "Characteristic Stability Index" |
| 129 | + return psis |
| 130 | + |
| 131 | + @staticmethod |
| 132 | + def _create_bin_percentage(train: Series, assess: Series) -> tuple: |
| 133 | + """ |
| 134 | + In case of categorical values proceed to count the instances |
| 135 | + of each class and divide by the total amount of samples to get |
| 136 | + the ratios. |
| 137 | +
|
| 138 | + Parameters |
| 139 | + ---------- |
| 140 | + train : Series |
| 141 | + Array of values, dtype == category |
| 142 | + assess : Series |
| 143 | + Array of values, dtype == category |
| 144 | +
|
| 145 | + Returns |
| 146 | + ------- |
| 147 | + tuple |
| 148 | + Class percentages for both arrays |
| 149 | + """ |
| 150 | + len_training = len(train) |
| 151 | + len_assessment = len(assess) |
| 152 | + train_bin_perc = train.value_counts() / len_training |
| 153 | + assess_bin_perc = assess.value_counts() / len_assessment |
| 154 | + return train_bin_perc, assess_bin_perc |
0 commit comments