|
| 1 | +"""Energy Distance module.""" |
| 2 | + |
| 3 | +from typing import Optional, Union |
| 4 | + |
| 5 | +import numpy as np # type: ignore |
| 6 | +from scipy.stats import energy_distance # type: ignore |
| 7 | + |
| 8 | +from frouros.callbacks.batch.base import BaseCallbackBatch |
| 9 | +from frouros.detectors.data_drift.base import UnivariateData |
| 10 | +from frouros.detectors.data_drift.batch.distance_based.base import ( |
| 11 | + BaseDistanceBased, |
| 12 | + DistanceResult, |
| 13 | +) |
| 14 | + |
| 15 | + |
| 16 | +class EnergyDistance(BaseDistanceBased): |
| 17 | + """EnergyDistance [szekely2013energy]_ detector. |
| 18 | +
|
| 19 | + :param callbacks: callbacks, defaults to None |
| 20 | + :type callbacks: Optional[Union[BaseCallbackBatch, list[BaseCallbackBatch]]] |
| 21 | + :param kwargs: additional keyword arguments to pass to scipy.stats.energy_distance |
| 22 | + :type kwargs: Dict[str, Any] |
| 23 | +
|
| 24 | + :References: |
| 25 | +
|
| 26 | + .. [szekely2013energy] Székely, Gábor J., and Maria L. Rizzo. |
| 27 | + "Energy statistics: A class of statistics based on distances." |
| 28 | + Journal of statistical planning and inference 143.8 (2013): 1249-1272. |
| 29 | +
|
| 30 | + :Example: |
| 31 | +
|
| 32 | + >>> from frouros.detectors.data_drift import EnergyDistance |
| 33 | + >>> import numpy as np |
| 34 | + >>> np.random.seed(seed=31) |
| 35 | + >>> X = np.random.normal(loc=0, scale=1, size=100) |
| 36 | + >>> Y = np.random.normal(loc=1, scale=1, size=100) |
| 37 | + >>> detector = EnergyDistance() |
| 38 | + >>> _ = detector.fit(X=X) |
| 39 | + >>> detector.compare(X=Y)[0] |
| 40 | + DistanceResult(distance=0.8359206395514527) |
| 41 | + """ # noqa: E501 |
| 42 | + |
| 43 | + def __init__( # noqa: D107 |
| 44 | + self, |
| 45 | + callbacks: Optional[Union[BaseCallbackBatch, list[BaseCallbackBatch]]] = None, |
| 46 | + **kwargs, |
| 47 | + ) -> None: |
| 48 | + super().__init__( |
| 49 | + statistical_type=UnivariateData(), |
| 50 | + statistical_method=self._energy_distance, |
| 51 | + statistical_kwargs=kwargs, |
| 52 | + callbacks=callbacks, |
| 53 | + ) |
| 54 | + self.kwargs = kwargs |
| 55 | + |
| 56 | + def _distance_measure( |
| 57 | + self, |
| 58 | + X_ref: np.ndarray, # noqa: N803 |
| 59 | + X: np.ndarray, # noqa: N803 |
| 60 | + **kwargs, |
| 61 | + ) -> DistanceResult: |
| 62 | + emd = self._energy_distance(X=X_ref, Y=X, **self.kwargs) |
| 63 | + distance = DistanceResult(distance=emd) |
| 64 | + return distance |
| 65 | + |
| 66 | + @staticmethod |
| 67 | + def _energy_distance( |
| 68 | + X: np.ndarray, # noqa: N803 |
| 69 | + Y: np.ndarray, |
| 70 | + **kwargs, |
| 71 | + ) -> float: |
| 72 | + energy = energy_distance( |
| 73 | + u_values=X.flatten(), |
| 74 | + v_values=Y.flatten(), |
| 75 | + **kwargs, |
| 76 | + ) |
| 77 | + return energy |
0 commit comments