|
| 1 | +from abc import ABC, abstractmethod |
| 2 | +from typing import Union, Optional |
| 3 | + |
| 4 | +import numpy as np |
| 5 | + |
| 6 | +from sklearn.base import BaseEstimator, OutlierMixin |
| 7 | +from sklearn.decomposition._base import _BasePCA |
| 8 | +from sklearn.cross_decomposition._pls import _PLS |
| 9 | +from sklearn.pipeline import Pipeline |
| 10 | +from sklearn.utils.validation import check_is_fitted |
| 11 | + |
| 12 | +from ._utils import validate_confidence, validate_and_extract_model |
| 13 | + |
| 14 | +ModelTypes = Union[_BasePCA, _PLS] |
| 15 | + |
| 16 | + |
| 17 | +class _ModelResidualsBase(ABC, BaseEstimator, OutlierMixin): |
| 18 | + """Base class for model outlier calculations. |
| 19 | +
|
| 20 | + Implements statistical calculations for outlier detection in dimensionality |
| 21 | + reduction models like PCA and PLS. |
| 22 | +
|
| 23 | + Parameters |
| 24 | + ---------- |
| 25 | + model : Union[ModelTypes, Pipeline] |
| 26 | + A fitted _BasePCA or _PLS models or Pipeline ending with such a model |
| 27 | + confidence : float |
| 28 | + Confidence level for statistical calculations (between 0 and 1) |
| 29 | +
|
| 30 | + Attributes |
| 31 | + ---------- |
| 32 | + model_ : ModelTypes |
| 33 | + The fitted model of type _BasePCA or _PLS |
| 34 | +
|
| 35 | + preprocessing_ : Optional[Pipeline] |
| 36 | + Preprocessing steps before the model |
| 37 | +
|
| 38 | + n_features_in_ : int |
| 39 | + Number of features in the input data |
| 40 | +
|
| 41 | + n_components_ : int |
| 42 | + Number of components in the model |
| 43 | +
|
| 44 | + n_samples_ : int |
| 45 | + Number of samples used to train the model |
| 46 | +
|
| 47 | + critical_value_ : float |
| 48 | + The calculated critical value for outlier detection |
| 49 | + """ |
| 50 | + |
| 51 | + def __init__( |
| 52 | + self, |
| 53 | + model: Union[ModelTypes, Pipeline], |
| 54 | + confidence: float, |
| 55 | + ) -> None: |
| 56 | + ( |
| 57 | + self.model_, |
| 58 | + self.preprocessing_, |
| 59 | + self.n_features_in_, |
| 60 | + self.n_components_, |
| 61 | + self.n_samples_, |
| 62 | + ) = validate_and_extract_model(model) |
| 63 | + self.confidence = validate_confidence(confidence) |
| 64 | + |
| 65 | + def fit_predict_residuals( |
| 66 | + self, X: np.ndarray, y: Optional[np.ndarray] = None |
| 67 | + ) -> np.ndarray: |
| 68 | + """Fit the model to the input data and calculate the residuals. |
| 69 | +
|
| 70 | + Parameters |
| 71 | + ---------- |
| 72 | + X : array-like of shape (n_samples, n_features) |
| 73 | + Input data |
| 74 | +
|
| 75 | + y : array-like of shape (n_samples,), default=None |
| 76 | + Target values |
| 77 | +
|
| 78 | + Returns |
| 79 | + ------- |
| 80 | + ndarray of shape (n_samples,) |
| 81 | + The residuals of the model |
| 82 | + """ |
| 83 | + self.fit(X, y) |
| 84 | + return self.predict_residuals(X, y, validate=True) |
| 85 | + |
| 86 | + @abstractmethod |
| 87 | + def predict_residuals( |
| 88 | + self, X: np.ndarray, y: Optional[np.ndarray], validate: bool |
| 89 | + ) -> np.ndarray: |
| 90 | + """Calculate the residuals of the model. |
| 91 | +
|
| 92 | + Returns |
| 93 | + ------- |
| 94 | + ndarray of shape (n_samples,) |
| 95 | + The residuals of the model |
| 96 | + """ |
| 97 | + |
| 98 | + @abstractmethod |
| 99 | + def _calculate_critical_value(self, X: Optional[np.ndarray]) -> float: |
| 100 | + """Calculate the critical value for outlier detection. |
| 101 | +
|
| 102 | + Returns |
| 103 | + ------- |
| 104 | + float |
| 105 | + The calculated critical value for outlier detection |
| 106 | + """ |
| 107 | + |
| 108 | + |
| 109 | +class _ModelDiagnosticsBase(ABC): |
| 110 | + """Base class for model diagnostics methods. This does not implement outlier detection algorithms, |
| 111 | + but rather implements methods that are used to assess trained models. |
| 112 | +
|
| 113 | + Parameters |
| 114 | + ---------- |
| 115 | + model : Union[ModelTypes, Pipeline] |
| 116 | + A fitted PCA/PLS model or Pipeline ending with such a model |
| 117 | +
|
| 118 | + Attributes |
| 119 | + ---------- |
| 120 | + model_ : ModelTypes |
| 121 | + The fitted model of type _BasePCA or _PLS |
| 122 | +
|
| 123 | + preprocessing_ : Optional[Pipeline] |
| 124 | + Preprocessing steps before the model |
| 125 | +
|
| 126 | + """ |
| 127 | + |
| 128 | + def __init__(self, model: Union[ModelTypes, Pipeline]): |
| 129 | + self.model_, self.preprocessing_ = self._validate_and_extract_model(model) |
| 130 | + |
| 131 | + def _validate_and_extract_model(self, model): |
| 132 | + """Validate and extract the model and preprocessing steps. |
| 133 | +
|
| 134 | + Parameters |
| 135 | + ---------- |
| 136 | + model : Union[ModelTypes, Pipeline] |
| 137 | + A fitted PCA/PLS model or Pipeline ending with such a model |
| 138 | +
|
| 139 | + Returns |
| 140 | + ------- |
| 141 | + Tuple[ModelTypes, Optional[Pipeline]] |
| 142 | + The extracted model and preprocessing steps |
| 143 | +
|
| 144 | + Raises |
| 145 | + ------ |
| 146 | + ValueError |
| 147 | + If the model is not of type _BasePCA or _PLS or a Pipeline ending with one of these types or if the model is not fitted |
| 148 | + """ |
| 149 | + if isinstance(model, Pipeline): |
| 150 | + preprocessing = model[:-1] |
| 151 | + model = model[-1] |
| 152 | + else: |
| 153 | + preprocessing = None |
| 154 | + |
| 155 | + if isinstance(model, (_BasePCA, _PLS)): |
| 156 | + check_is_fitted(model) |
| 157 | + else: |
| 158 | + raise ValueError( |
| 159 | + "Model not a valid model. Must be of base type _BasePCA or _PLS or a Pipeline ending with one of these types." |
| 160 | + ) |
| 161 | + check_is_fitted(model) |
| 162 | + return model, preprocessing |
| 163 | + |
| 164 | + @abstractmethod |
| 165 | + def predict(self, X: np.ndarray, y: Optional[np.ndarray]) -> np.ndarray: |
| 166 | + """Predict the output of the model. |
| 167 | +
|
| 168 | + Parameters |
| 169 | + ---------- |
| 170 | + X : array-like of shape (n_samples, n_features) |
| 171 | + Input data |
| 172 | +
|
| 173 | + y : array-like of shape (n_samples,), default=None |
| 174 | + Target values |
| 175 | +
|
| 176 | + Returns |
| 177 | + ------- |
| 178 | + ndarray of shape (n_samples,) |
| 179 | + Predicted values |
| 180 | + """ |
0 commit comments