|
| 1 | +from typing import Union, Optional, Dict, Any |
| 2 | +from typing import TYPE_CHECKING |
| 3 | +from alibi_detect.exceptions import _catch_error as catch_error |
| 4 | + |
| 5 | + |
| 6 | +import numpy as np |
| 7 | + |
| 8 | +from alibi_detect.utils._types import Literal |
| 9 | +from alibi_detect.base import BaseDetector, FitMixin, ThresholdMixin, outlier_prediction_dict |
| 10 | +from alibi_detect.od.pytorch import MahalanobisTorch |
| 11 | +from alibi_detect.utils.frameworks import BackendValidator |
| 12 | +from alibi_detect.version import __version__ |
| 13 | + |
| 14 | + |
| 15 | +if TYPE_CHECKING: |
| 16 | + import torch |
| 17 | + |
| 18 | + |
| 19 | +backends = { |
| 20 | + 'pytorch': MahalanobisTorch |
| 21 | +} |
| 22 | + |
| 23 | + |
| 24 | +class Mahalanobis(BaseDetector, FitMixin, ThresholdMixin): |
| 25 | + def __init__( |
| 26 | + self, |
| 27 | + min_eigenvalue: float = 1e-6, |
| 28 | + backend: Literal['pytorch'] = 'pytorch', |
| 29 | + device: Optional[Union[Literal['cuda', 'gpu', 'cpu'], 'torch.device']] = None, |
| 30 | + ) -> None: |
| 31 | + """ |
| 32 | + The Mahalanobis outlier detection method. |
| 33 | +
|
| 34 | + The Mahalanobis detector computes the directions of variation of a dataset and uses them to detect when points |
| 35 | + are outliers by checking to see if the points vary from dataset points in unexpected ways. |
| 36 | +
|
| 37 | + When we fit the Mahalanobis detector we compute the covariance matrix of the reference data and its eigenvectors |
| 38 | + and eigenvalues. We filter small eigenvalues for numerical stability using the `min_eigenvalue` parameter. We |
| 39 | + then inversely weight each eigenvector by its eigenvalue. |
| 40 | +
|
| 41 | + When we score test points we project them onto the eigenvectors and compute the l2-norm of the projected point. |
| 42 | + Because the eigenvectors are inversely weighted by the eigenvalues, the score will take into account the |
| 43 | + difference in variance along each direction of variation. If a test point lies along a direction of high |
| 44 | + variation then it must lie very far out to obtain a high score. If a test point lies along a direction of low |
| 45 | + variation then it doesn't need to lie very far out to obtain a high score. |
| 46 | +
|
| 47 | + Parameters |
| 48 | + ---------- |
| 49 | + min_eigenvalue |
| 50 | + Eigenvectors with eigenvalues below this value will be discarded. This is to ensure numerical stability. |
| 51 | + backend |
| 52 | + Backend used for outlier detection. Defaults to ``'pytorch'``. Options are ``'pytorch'``. |
| 53 | + device |
| 54 | + Device type used. The default tries to use the GPU and falls back on CPU if needed. Can be specified by |
| 55 | + passing either ``'cuda'``, ``'gpu'``, ``'cpu'`` or an instance of ``torch.device``. |
| 56 | +
|
| 57 | + Raises |
| 58 | + ------ |
| 59 | + NotImplementedError |
| 60 | + If choice of `backend` is not implemented. |
| 61 | + """ |
| 62 | + super().__init__() |
| 63 | + |
| 64 | + backend_str: str = backend.lower() |
| 65 | + BackendValidator( |
| 66 | + backend_options={'pytorch': ['pytorch']}, |
| 67 | + construct_name=self.__class__.__name__ |
| 68 | + ).verify_backend(backend_str) |
| 69 | + |
| 70 | + backend_cls = backends[backend] |
| 71 | + self.backend = backend_cls(min_eigenvalue, device=device) |
| 72 | + |
| 73 | + # set metadata |
| 74 | + self.meta['detector_type'] = 'outlier' |
| 75 | + self.meta['data_type'] = 'numeric' |
| 76 | + self.meta['online'] = False |
| 77 | + |
| 78 | + def fit(self, x_ref: np.ndarray) -> None: |
| 79 | + """Fit the detector on reference data. |
| 80 | +
|
| 81 | + Fitting the Mahalanobis detector amounts to computing the covariance matrix and its eigenvectors. We filter out |
| 82 | + very small eigenvalues using the `min_eigenvalue` parameter. We then scale the eigenvectors such that the data |
| 83 | + projected onto them has mean ``0`` and std ``1``. |
| 84 | +
|
| 85 | + Parameters |
| 86 | + ---------- |
| 87 | + x_ref |
| 88 | + Reference data used to fit the detector. |
| 89 | + """ |
| 90 | + self.backend.fit(self.backend._to_tensor(x_ref)) |
| 91 | + |
| 92 | + @catch_error('NotFittedError') |
| 93 | + def score(self, x: np.ndarray) -> np.ndarray: |
| 94 | + """Score `x` instances using the detector. |
| 95 | +
|
| 96 | + The mahalanobis method projects `x` onto the scaled eigenvectors computed during the fit step. The score is then |
| 97 | + the l2-norm of the projected data. The higher the score, the more outlying the instance. |
| 98 | +
|
| 99 | + Parameters |
| 100 | + ---------- |
| 101 | + x |
| 102 | + Data to score. The shape of `x` should be `(n_instances, n_features)`. |
| 103 | +
|
| 104 | + Returns |
| 105 | + ------- |
| 106 | + Outlier scores. The shape of the scores is `(n_instances,)`. The higher the score, the more outlying the \ |
| 107 | + instance. |
| 108 | +
|
| 109 | + Raises |
| 110 | + ------ |
| 111 | + NotFittedError |
| 112 | + If called before detector has been fit. |
| 113 | + """ |
| 114 | + score = self.backend.score(self.backend._to_tensor(x)) |
| 115 | + return self.backend._to_numpy(score) |
| 116 | + |
| 117 | + @catch_error('NotFittedError') |
| 118 | + def infer_threshold(self, x: np.ndarray, fpr: float) -> None: |
| 119 | + """Infer the threshold for the Mahalanobis detector. |
| 120 | +
|
| 121 | + The threshold is computed so that the outlier detector would incorrectly classify `fpr` proportion of the |
| 122 | + reference data as outliers. |
| 123 | +
|
| 124 | + Parameters |
| 125 | + ---------- |
| 126 | + x |
| 127 | + Reference data used to infer the threshold. |
| 128 | + fpr |
| 129 | + False positive rate used to infer the threshold. The false positive rate is the proportion of |
| 130 | + instances in `x` that are incorrectly classified as outliers. The false positive rate should |
| 131 | + be in the range ``(0, 1)``. |
| 132 | +
|
| 133 | + Raises |
| 134 | + ------ |
| 135 | + ValueError |
| 136 | + Raised if `fpr` is not in ``(0, 1)``. |
| 137 | + NotFittedError |
| 138 | + If called before detector has been fit. |
| 139 | + """ |
| 140 | + self.backend.infer_threshold(self.backend._to_tensor(x), fpr) |
| 141 | + |
| 142 | + @catch_error('NotFittedError') |
| 143 | + def predict(self, x: np.ndarray) -> Dict[str, Any]: |
| 144 | + """Predict whether the instances in `x` are outliers or not. |
| 145 | +
|
| 146 | + Scores the instances in `x` and if the threshold was inferred, returns the outlier labels and p-values as well. |
| 147 | +
|
| 148 | + Parameters |
| 149 | + ---------- |
| 150 | + x |
| 151 | + Data to predict. The shape of `x` should be `(n_instances, n_features)`. |
| 152 | +
|
| 153 | + Returns |
| 154 | + ------- |
| 155 | + Dictionary with keys 'data' and 'meta'. 'data' contains the outlier scores. If threshold inference was \ |
| 156 | + performed, 'data' also contains the threshold value, outlier labels and p-vals . The shape of the scores is \ |
| 157 | + `(n_instances,)`. The higher the score, the more anomalous the instance. 'meta' contains information about \ |
| 158 | + the detector. |
| 159 | +
|
| 160 | + Raises |
| 161 | + ------ |
| 162 | + NotFittedError |
| 163 | + If called before detector has been fit. |
| 164 | + """ |
| 165 | + outputs = self.backend.predict(self.backend._to_tensor(x)) |
| 166 | + output = outlier_prediction_dict() |
| 167 | + output['data'] = { |
| 168 | + **output['data'], |
| 169 | + **self.backend._to_numpy(outputs) |
| 170 | + } |
| 171 | + output['meta'] = { |
| 172 | + **output['meta'], |
| 173 | + 'name': self.__class__.__name__, |
| 174 | + 'detector_type': 'outlier', |
| 175 | + 'online': False, |
| 176 | + 'version': __version__, |
| 177 | + } |
| 178 | + return output |
0 commit comments