robpy 0.0.1__tar.gz → 0.0.3__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- robpy-0.0.3/LICENSE +21 -0
- {robpy-0.0.1 → robpy-0.0.3}/PKG-INFO +5 -2
- {robpy-0.0.1 → robpy-0.0.3}/README.rst +3 -1
- {robpy-0.0.1 → robpy-0.0.3}/pyproject.toml +1 -1
- robpy-0.0.3/robpy/covariance/__init__.py +6 -0
- {robpy-0.0.1 → robpy-0.0.3}/robpy/covariance/base.py +3 -3
- {robpy-0.0.1 → robpy-0.0.3}/robpy/covariance/cellmcd.py +47 -16
- {robpy-0.0.1 → robpy-0.0.3}/robpy/covariance/initial_ddcw.py +16 -18
- {robpy-0.0.1 → robpy-0.0.3}/robpy/covariance/kendall.py +4 -4
- {robpy-0.0.1 → robpy-0.0.3}/robpy/covariance/mcd.py +41 -41
- {robpy-0.0.1 → robpy-0.0.3}/robpy/covariance/ogk.py +2 -2
- {robpy-0.0.1 → robpy-0.0.3}/robpy/covariance/utils/cellmcd_utils.py +1 -1
- {robpy-0.0.1 → robpy-0.0.3}/robpy/covariance/utils/cellmcd_visualization_utils.py +39 -33
- {robpy-0.0.1 → robpy-0.0.3}/robpy/covariance/wrapping.py +2 -2
- {robpy-0.0.1 → robpy-0.0.3}/robpy/datasets/base.py +10 -10
- {robpy-0.0.1 → robpy-0.0.3}/robpy/datasets/data/topgear.csv +1 -1
- {robpy-0.0.1 → robpy-0.0.3}/robpy/datasets/descr/topgear.rst +1 -1
- {robpy-0.0.1 → robpy-0.0.3}/robpy/outliers/__init__.py +1 -1
- {robpy-0.0.1 → robpy-0.0.3}/robpy/outliers/ddc.py +156 -44
- robpy-0.0.3/robpy/pca/__init__.py +3 -0
- {robpy-0.0.1 → robpy-0.0.3}/robpy/pca/base.py +3 -3
- {robpy-0.0.1 → robpy-0.0.3}/robpy/pca/robpca.py +5 -5
- {robpy-0.0.1 → robpy-0.0.3}/robpy/pca/spca.py +3 -3
- {robpy-0.0.1 → robpy-0.0.3}/robpy/preprocessing/scaling.py +3 -3
- {robpy-0.0.1 → robpy-0.0.3}/robpy/preprocessing/transfo.py +6 -6
- robpy-0.0.3/robpy/regression/__init__.py +3 -0
- {robpy-0.0.1 → robpy-0.0.3}/robpy/regression/base.py +7 -7
- {robpy-0.0.1 → robpy-0.0.3}/robpy/regression/lts.py +9 -7
- robpy-0.0.1/robpy/regression/mm_estimator.py → robpy-0.0.3/robpy/regression/mm.py +5 -5
- robpy-0.0.1/robpy/regression/s_estimator.py → robpy-0.0.3/robpy/regression/s.py +3 -3
- robpy-0.0.3/robpy/univariate/__init__.py +6 -0
- {robpy-0.0.1 → robpy-0.0.3}/robpy/univariate/base.py +2 -2
- {robpy-0.0.1 → robpy-0.0.3}/robpy/univariate/mcd.py +11 -11
- {robpy-0.0.1 → robpy-0.0.3}/robpy/univariate/onestep_m.py +8 -8
- {robpy-0.0.1 → robpy-0.0.3}/robpy/univariate/qn.py +2 -2
- {robpy-0.0.1 → robpy-0.0.3}/robpy/univariate/tau.py +2 -2
- robpy-0.0.1/robpy/covariance/__init__.py +0 -6
- robpy-0.0.1/robpy/pca/__init__.py +0 -3
- robpy-0.0.1/robpy/regression/__init__.py +0 -3
- robpy-0.0.1/robpy/univariate/__init__.py +0 -10
- {robpy-0.0.1 → robpy-0.0.3}/robpy/__init__.py +0 -0
- {robpy-0.0.1 → robpy-0.0.3}/robpy/covariance/utils/alter_covariance.py +0 -0
- {robpy-0.0.1 → robpy-0.0.3}/robpy/datasets/__init__.py +0 -0
- {robpy-0.0.1 → robpy-0.0.3}/robpy/datasets/data/animals.csv +0 -0
- {robpy-0.0.1 → robpy-0.0.3}/robpy/datasets/data/glass.csv +0 -0
- {robpy-0.0.1 → robpy-0.0.3}/robpy/datasets/data/stars.csv +0 -0
- {robpy-0.0.1 → robpy-0.0.3}/robpy/datasets/data/telephone.csv +0 -0
- {robpy-0.0.1 → robpy-0.0.3}/robpy/datasets/descr/animals.rst +0 -0
- {robpy-0.0.1 → robpy-0.0.3}/robpy/datasets/descr/glass.rst +0 -0
- {robpy-0.0.1 → robpy-0.0.3}/robpy/datasets/descr/stars.rst +0 -0
- {robpy-0.0.1 → robpy-0.0.3}/robpy/datasets/descr/telephone.rst +0 -0
- {robpy-0.0.1 → robpy-0.0.3}/robpy/preprocessing/__init__.py +0 -0
- {robpy-0.0.1 → robpy-0.0.3}/robpy/preprocessing/data_cleaner.py +0 -0
- {robpy-0.0.1 → robpy-0.0.3}/robpy/preprocessing/utils.py +0 -0
- {robpy-0.0.1 → robpy-0.0.3}/robpy/univariate/adjusted_boxplot.py +0 -0
- {robpy-0.0.1 → robpy-0.0.3}/robpy/utils/distance.py +0 -0
- {robpy-0.0.1 → robpy-0.0.3}/robpy/utils/general.py +0 -0
- {robpy-0.0.1 → robpy-0.0.3}/robpy/utils/logging.py +0 -0
- {robpy-0.0.1 → robpy-0.0.3}/robpy/utils/median.py +0 -0
- {robpy-0.0.1 → robpy-0.0.3}/robpy/utils/outlyingness.py +0 -0
- {robpy-0.0.1 → robpy-0.0.3}/robpy/utils/rho.py +0 -0
robpy-0.0.3/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 STAN-UAntwerp
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.1
|
|
2
2
|
Name: robpy
|
|
3
|
-
Version: 0.0.
|
|
3
|
+
Version: 0.0.3
|
|
4
4
|
Summary:
|
|
5
5
|
Author: Thomas Servotte
|
|
6
6
|
Author-email: servottethomas@gmail.com
|
|
@@ -9,6 +9,7 @@ Classifier: Programming Language :: Python :: 3
|
|
|
9
9
|
Classifier: Programming Language :: Python :: 3.10
|
|
10
10
|
Classifier: Programming Language :: Python :: 3.11
|
|
11
11
|
Classifier: Programming Language :: Python :: 3.12
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
12
13
|
Requires-Dist: matplotlib (>=3.8.2,<4.0.0)
|
|
13
14
|
Requires-Dist: scikit-learn (>=1.3)
|
|
14
15
|
Requires-Dist: scipy (>=1.11.4,<2.0.0)
|
|
@@ -24,7 +25,9 @@ Robpy
|
|
|
24
25
|
SciPy.
|
|
25
26
|
|
|
26
27
|
The project was started in 2023 by Tim Verdonck, Jakob Raymaekers, Thomas Servotte, Sarah Leyder & Thomas Decorte at the University of Antwerp and imec IDLab.
|
|
27
|
-
The project is currently maintained by
|
|
28
|
+
The project is currently maintained by the same team and distributed under MIT license.
|
|
29
|
+
|
|
30
|
+
Documentation is available at https://robpy.readthedocs.io/en/latest/
|
|
28
31
|
|
|
29
32
|
|
|
30
33
|
|
|
@@ -5,7 +5,9 @@ Robpy
|
|
|
5
5
|
SciPy.
|
|
6
6
|
|
|
7
7
|
The project was started in 2023 by Tim Verdonck, Jakob Raymaekers, Thomas Servotte, Sarah Leyder & Thomas Decorte at the University of Antwerp and imec IDLab.
|
|
8
|
-
The project is currently maintained by
|
|
8
|
+
The project is currently maintained by the same team and distributed under MIT license.
|
|
9
|
+
|
|
10
|
+
Documentation is available at https://robpy.readthedocs.io/en/latest/
|
|
9
11
|
|
|
10
12
|
|
|
11
13
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[tool.poetry]
|
|
2
2
|
name = "robpy"
|
|
3
|
-
version = "0.0.
|
|
3
|
+
version = "0.0.3" # versioning is done by poetry-dynamic-versioning
|
|
4
4
|
description = ""
|
|
5
5
|
authors = ["Thomas Servotte <servottethomas@gmail.com>", "Sarah Leyder <sarah.leyder@uantwerpen.be>"]
|
|
6
6
|
readme = "README.rst"
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
from robpy.covariance.base import RobustCovariance
|
|
2
|
+
from robpy.covariance.mcd import FastMCD, DetMCD
|
|
3
|
+
from robpy.covariance.wrapping import WrappingCovariance
|
|
4
|
+
from robpy.covariance.ogk import OGK
|
|
5
|
+
from robpy.covariance.kendall import KendallTau
|
|
6
|
+
from robpy.covariance.cellmcd import CellMCD
|
|
@@ -10,7 +10,7 @@ from sklearn.exceptions import NotFittedError
|
|
|
10
10
|
from robpy.utils.distance import mahalanobis_distance
|
|
11
11
|
|
|
12
12
|
|
|
13
|
-
class
|
|
13
|
+
class RobustCovariance(EmpiricalCovariance):
|
|
14
14
|
def __init__(self, *, store_precision=True, assume_centered=False, nans_allowed=False):
|
|
15
15
|
super().__init__(
|
|
16
16
|
store_precision=store_precision,
|
|
@@ -18,7 +18,7 @@ class RobustCovarianceEstimator(EmpiricalCovariance):
|
|
|
18
18
|
)
|
|
19
19
|
self.nans_allowed = nans_allowed
|
|
20
20
|
|
|
21
|
-
def fit(self, X: np.ndarray | pd.DataFrame) ->
|
|
21
|
+
def fit(self, X: np.ndarray | pd.DataFrame) -> RobustCovariance:
|
|
22
22
|
"""Fit the covariance estimator."""
|
|
23
23
|
if isinstance(X, pd.DataFrame):
|
|
24
24
|
X = X.values
|
|
@@ -76,7 +76,7 @@ class RobustCovarianceEstimator(EmpiricalCovariance):
|
|
|
76
76
|
ax.axvline(threshold, color="grey", linestyle="--")
|
|
77
77
|
ax.axline((0, 0), slope=1, color="grey", linestyle="-.")
|
|
78
78
|
|
|
79
|
-
ax.set_xlabel("
|
|
79
|
+
ax.set_xlabel("Non-robust distance")
|
|
80
80
|
ax.set_ylabel("Robust distance")
|
|
81
81
|
|
|
82
82
|
return fig
|
|
@@ -5,7 +5,7 @@ import matplotlib.pyplot as plt
|
|
|
5
5
|
from scipy.stats import chi2, median_abs_deviation
|
|
6
6
|
from typing import Literal, Optional
|
|
7
7
|
from robpy.covariance.utils.alter_covariance import truncated_covariance
|
|
8
|
-
from robpy.covariance.base import
|
|
8
|
+
from robpy.covariance.base import RobustCovariance
|
|
9
9
|
from robpy.utils.logging import get_logger
|
|
10
10
|
from robpy.covariance.utils.cellmcd_utils import objective_function
|
|
11
11
|
from robpy.utils.general import inverse_submatrix
|
|
@@ -17,12 +17,12 @@ from robpy.covariance.utils.cellmcd_visualization_utils import (
|
|
|
17
17
|
get_thresholds,
|
|
18
18
|
)
|
|
19
19
|
from robpy.preprocessing.scaling import RobustScaler
|
|
20
|
-
from robpy.univariate.onestep_m import
|
|
21
|
-
from robpy.covariance.initial_ddcw import
|
|
20
|
+
from robpy.univariate.onestep_m import OneStepWrapping
|
|
21
|
+
from robpy.covariance.initial_ddcw import InitialDDCW
|
|
22
22
|
from sklearn.exceptions import NotFittedError
|
|
23
23
|
|
|
24
24
|
|
|
25
|
-
class
|
|
25
|
+
class CellMCD(RobustCovariance):
|
|
26
26
|
def __init__(
|
|
27
27
|
self,
|
|
28
28
|
*,
|
|
@@ -68,7 +68,7 @@ class CellMCDEstimator(RobustCovarianceEstimator):
|
|
|
68
68
|
self.crit = crit
|
|
69
69
|
self.max_c_steps = max_c_steps
|
|
70
70
|
self.min_eigenvalue = min_eigenvalue
|
|
71
|
-
self.logger = get_logger("
|
|
71
|
+
self.logger = get_logger("CellMCD", level=verbosity)
|
|
72
72
|
self.verbosity = verbosity
|
|
73
73
|
|
|
74
74
|
def calculate_covariance(self, X: np.ndarray) -> np.ndarray:
|
|
@@ -76,7 +76,7 @@ class CellMCDEstimator(RobustCovarianceEstimator):
|
|
|
76
76
|
mads = median_abs_deviation(X, nan_policy="omit", axis=0)
|
|
77
77
|
if np.min(mads) < 1e-8:
|
|
78
78
|
raise ValueError("At least one variable has an almost zero median absolute deviation.")
|
|
79
|
-
scaler = RobustScaler(scale_estimator=
|
|
79
|
+
scaler = RobustScaler(scale_estimator=OneStepWrapping())
|
|
80
80
|
scaler.fit(X, ignore_nan=True)
|
|
81
81
|
X_scaled = scaler.transform(X)
|
|
82
82
|
|
|
@@ -85,7 +85,7 @@ class CellMCDEstimator(RobustCovarianceEstimator):
|
|
|
85
85
|
self._check_data(X_scaled)
|
|
86
86
|
|
|
87
87
|
# Step 2: calculate the initial estimates
|
|
88
|
-
ddcw =
|
|
88
|
+
ddcw = InitialDDCW(alpha=self.alpha, min_eigenvalue=self.min_eigenvalue)
|
|
89
89
|
ddcw.fit(X_scaled)
|
|
90
90
|
initial_location = ddcw.location_
|
|
91
91
|
initial_cov = ddcw.covariance_
|
|
@@ -109,7 +109,7 @@ class CellMCDEstimator(RobustCovarianceEstimator):
|
|
|
109
109
|
X_imputed = X.copy()
|
|
110
110
|
X_imputed[W == 0] = predictions[W == 0]
|
|
111
111
|
residuals = (X - predictions) / conditional_stds
|
|
112
|
-
scaler_residuals = RobustScaler(scale_estimator=
|
|
112
|
+
scaler_residuals = RobustScaler(scale_estimator=OneStepWrapping())
|
|
113
113
|
scaler_residuals.fit(residuals, ignore_nan=True)
|
|
114
114
|
residuals = residuals / scaler_residuals.scales_
|
|
115
115
|
|
|
@@ -139,6 +139,7 @@ class CellMCDEstimator(RobustCovarianceEstimator):
|
|
|
139
139
|
"bivariate",
|
|
140
140
|
] = "indexplot",
|
|
141
141
|
figsize: tuple[int, int] = (8, 8),
|
|
142
|
+
annotation_quantile: float | None = None,
|
|
142
143
|
):
|
|
143
144
|
"""
|
|
144
145
|
Function to plot the results of a cellMCD analysis: 5 types of diagnostic plots.
|
|
@@ -163,29 +164,49 @@ class CellMCDEstimator(RobustCovarianceEstimator):
|
|
|
163
164
|
row_names (list of strings, optional): Row_names of the observations if you want
|
|
164
165
|
the outliers annoted with their name.
|
|
165
166
|
figsize (tuple[int,int], optional): Size of the figure. Defaults to (8,8).
|
|
167
|
+
annotation_quantile (float, optional):
|
|
168
|
+
the quantile used to draw an imaginary threhsold around the data.
|
|
169
|
+
Only points outside these thresholds will be annotated. If None, use self.quantile
|
|
166
170
|
"""
|
|
167
171
|
|
|
168
172
|
if not hasattr(self, "covariance_"):
|
|
169
173
|
raise NotFittedError()
|
|
170
174
|
|
|
171
175
|
fig, ax = plt.subplots(1, 1, figsize=figsize)
|
|
172
|
-
cutoff = np.sqrt(chi2.ppf(self.quantile, 1))
|
|
176
|
+
cutoff = float(np.sqrt(chi2.ppf(self.quantile, 1)))
|
|
177
|
+
annotation_cutoff = (
|
|
178
|
+
cutoff
|
|
179
|
+
if annotation_quantile is None
|
|
180
|
+
else float(np.sqrt(chi2.ppf(annotation_quantile, 1)))
|
|
181
|
+
)
|
|
173
182
|
|
|
174
183
|
if plottype == "indexplot":
|
|
175
184
|
x, y = np.arange(self.W.shape[0]), self.residuals[:, variable]
|
|
176
185
|
h_thresholds, v_thresholds = (-cutoff, cutoff), None
|
|
186
|
+
h_thresholds_annotate, v_thresholds_annotate = (
|
|
187
|
+
-annotation_cutoff,
|
|
188
|
+
annotation_cutoff,
|
|
189
|
+
), None
|
|
177
190
|
xlabel, ylabel = "index", f"standardized residuals of {variable_name}"
|
|
178
191
|
title = "Indexplot: standardized residuals"
|
|
179
192
|
|
|
180
193
|
elif plottype == "residuals_vs_variable":
|
|
181
194
|
x, y = self.X[:, variable], self.residuals[:, variable]
|
|
182
195
|
h_thresholds, v_thresholds = (-cutoff, cutoff), get_thresholds(cutoff, x)
|
|
196
|
+
h_thresholds_annotate, v_thresholds_annotate = (
|
|
197
|
+
-annotation_cutoff,
|
|
198
|
+
annotation_cutoff,
|
|
199
|
+
), get_thresholds(annotation_cutoff, x)
|
|
183
200
|
xlabel, ylabel = variable_name, f"standardized residuals of {variable_name}"
|
|
184
201
|
title = f"Standardized residuals versus the {variable_name}"
|
|
185
202
|
|
|
186
203
|
elif plottype == "residuals_vs_predictions":
|
|
187
204
|
x, y = self.predictions[:, variable], self.residuals[:, variable]
|
|
188
205
|
h_thresholds, v_thresholds = (-cutoff, cutoff), get_thresholds(cutoff, x)
|
|
206
|
+
h_thresholds_annotate, v_thresholds_annotate = (
|
|
207
|
+
-annotation_cutoff,
|
|
208
|
+
annotation_cutoff,
|
|
209
|
+
), get_thresholds(annotation_cutoff, x)
|
|
189
210
|
xlabel, ylabel = (
|
|
190
211
|
f"predictions of {variable_name}",
|
|
191
212
|
f"standardized residuals of {variable_name}",
|
|
@@ -195,6 +216,9 @@ class CellMCDEstimator(RobustCovarianceEstimator):
|
|
|
195
216
|
elif plottype == "variable_vs_predictions":
|
|
196
217
|
x, y = self.predictions[:, variable], self.X[:, variable]
|
|
197
218
|
h_thresholds, v_thresholds = get_thresholds(cutoff, y), get_thresholds(cutoff, x)
|
|
219
|
+
h_thresholds_annotate, v_thresholds_annotate = get_thresholds(
|
|
220
|
+
annotation_cutoff, y
|
|
221
|
+
), get_thresholds(annotation_cutoff, x)
|
|
198
222
|
xlabel, ylabel = f"predictions of {variable_name}", f"observed {variable_name}"
|
|
199
223
|
ax.axline((x[0], x[0]), slope=1, color="grey", linestyle="-.")
|
|
200
224
|
title = f"{variable_name} versus its predictions"
|
|
@@ -218,7 +242,14 @@ class CellMCDEstimator(RobustCovarianceEstimator):
|
|
|
218
242
|
|
|
219
243
|
if row_names is not None:
|
|
220
244
|
if plottype != "bivariate":
|
|
221
|
-
annote_outliers(
|
|
245
|
+
annote_outliers(
|
|
246
|
+
ax,
|
|
247
|
+
row_names,
|
|
248
|
+
x,
|
|
249
|
+
y,
|
|
250
|
+
h_thresholds_annotate,
|
|
251
|
+
v_thresholds_annotate,
|
|
252
|
+
)
|
|
222
253
|
else:
|
|
223
254
|
annote_outliers_ellipse(
|
|
224
255
|
ax,
|
|
@@ -229,7 +260,7 @@ class CellMCDEstimator(RobustCovarianceEstimator):
|
|
|
229
260
|
second_variable,
|
|
230
261
|
x,
|
|
231
262
|
y,
|
|
232
|
-
self.quantile,
|
|
263
|
+
self.quantile if annotation_quantile is None else annotation_quantile,
|
|
233
264
|
)
|
|
234
265
|
|
|
235
266
|
draw_threshold_lines(ax, h_thresholds, v_thresholds)
|
|
@@ -511,9 +542,9 @@ class CellMCDEstimator(RobustCovarianceEstimator):
|
|
|
511
542
|
X: np.ndarray,
|
|
512
543
|
predictions: np.ndarray,
|
|
513
544
|
conditional_variances: np.ndarray,
|
|
514
|
-
row_idx_w: np.
|
|
515
|
-
observed_col_idx: np.
|
|
516
|
-
mu: np.
|
|
545
|
+
row_idx_w: np.ndarray,
|
|
546
|
+
observed_col_idx: np.ndarray,
|
|
547
|
+
mu: np.ndarray,
|
|
517
548
|
sigma: np.ndarray,
|
|
518
549
|
sigma_inv: np.ndarray,
|
|
519
550
|
):
|
|
@@ -552,8 +583,8 @@ class CellMCDEstimator(RobustCovarianceEstimator):
|
|
|
552
583
|
X: np.ndarray,
|
|
553
584
|
predictions: np.ndarray,
|
|
554
585
|
conditional_variances: np.ndarray,
|
|
555
|
-
row_idx_w: np.
|
|
556
|
-
mu: np.
|
|
586
|
+
row_idx_w: np.ndarray,
|
|
587
|
+
mu: np.ndarray,
|
|
557
588
|
sigma: np.ndarray,
|
|
558
589
|
sigma_inv: np.ndarray,
|
|
559
590
|
):
|
|
@@ -1,17 +1,17 @@
|
|
|
1
1
|
import numpy as np
|
|
2
2
|
import pandas as pd
|
|
3
3
|
|
|
4
|
-
from robpy.covariance.base import
|
|
4
|
+
from robpy.covariance.base import RobustCovariance
|
|
5
5
|
from robpy.utils.distance import mahalanobis_distance
|
|
6
6
|
from robpy.covariance.utils.alter_covariance import truncated_covariance, covariance_to_correlation
|
|
7
7
|
from robpy.preprocessing.scaling import RobustScaler
|
|
8
|
-
from robpy.univariate.onestep_m import
|
|
9
|
-
from robpy.outliers.ddc import
|
|
8
|
+
from robpy.univariate.onestep_m import OneStepWrapping
|
|
9
|
+
from robpy.outliers.ddc import DDC
|
|
10
10
|
from robpy.preprocessing.utils import wrapping_transformation
|
|
11
11
|
from scipy.stats import chi2
|
|
12
12
|
|
|
13
13
|
|
|
14
|
-
class
|
|
14
|
+
class InitialDDCW(RobustCovariance):
|
|
15
15
|
def __init__(
|
|
16
16
|
self,
|
|
17
17
|
*,
|
|
@@ -53,23 +53,21 @@ class InitialDDCWEstimator(RobustCovarianceEstimator):
|
|
|
53
53
|
n, p = X.shape
|
|
54
54
|
|
|
55
55
|
# DDC with constraint -> imputed and rescaled Zimp:
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
)
|
|
59
|
-
W = np.copy(DDC.cellwise_outliers_)
|
|
56
|
+
ddc = DDC(chi2_quantile=0.9, scale_estimator=OneStepWrapping()).fit(pd.DataFrame(X))
|
|
57
|
+
W = np.copy(ddc.cellwise_outliers_)
|
|
60
58
|
flagged_too_many = np.where(np.sum(W, axis=0) / X.shape[0] > 1 - self.alpha)[0]
|
|
61
59
|
for i in flagged_too_many:
|
|
62
|
-
ordering = np.argsort(np.abs(
|
|
60
|
+
ordering = np.argsort(np.abs(ddc.standardized_residuals_[:, i]))[::-1]
|
|
63
61
|
W[:, i] = [False for _ in range(n)]
|
|
64
62
|
W[ordering[0 : int(n * 0.25)], i] = True
|
|
65
63
|
Zimp = np.copy(X)
|
|
66
|
-
Zimp[np.logical_or(W, np.isnan(X))] =
|
|
64
|
+
Zimp[np.logical_or(W, np.isnan(X))] = ddc.impute(
|
|
67
65
|
pd.DataFrame(X), impute_outliers=True
|
|
68
66
|
).to_numpy()[np.logical_or(W, np.isnan(X))]
|
|
69
|
-
Z = (X -
|
|
70
|
-
Zimp = (Zimp -
|
|
67
|
+
Z = (X - ddc.location_) / ddc.scale_
|
|
68
|
+
Zimp = (Zimp - ddc.location_) / ddc.scale_
|
|
71
69
|
Zimp_original = np.copy(Zimp)
|
|
72
|
-
Zimp = np.delete(Zimp, np.where(
|
|
70
|
+
Zimp = np.delete(Zimp, np.where(ddc.row_outliers_)[0], axis=0)
|
|
73
71
|
|
|
74
72
|
# project data on eigenvectors
|
|
75
73
|
eigvals, eigvecs = np.linalg.eigh(np.cov(Zimp, rowvar=False))
|
|
@@ -77,7 +75,7 @@ class InitialDDCWEstimator(RobustCovarianceEstimator):
|
|
|
77
75
|
Zimp_proj = Zimp @ eigenvectors
|
|
78
76
|
|
|
79
77
|
# wrapped location and covariance
|
|
80
|
-
Zimp_proj_scaler = RobustScaler(scale_estimator=
|
|
78
|
+
Zimp_proj_scaler = RobustScaler(scale_estimator=OneStepWrapping()).fit(
|
|
81
79
|
Zimp_proj, ignore_nan=True
|
|
82
80
|
)
|
|
83
81
|
Zimp_proj_scaler.scales_[
|
|
@@ -94,7 +92,7 @@ class InitialDDCWEstimator(RobustCovarianceEstimator):
|
|
|
94
92
|
)
|
|
95
93
|
cov = eigenvectors @ Zimp_proj_wrapped_cov @ eigenvectors.T # back to original axis system
|
|
96
94
|
cov = covariance_to_correlation(cov)
|
|
97
|
-
cov = (truncated_covariance(cov, self.min_eigenvalue) *
|
|
95
|
+
cov = (truncated_covariance(cov, self.min_eigenvalue) * ddc.scale_).T * ddc.scale_
|
|
98
96
|
|
|
99
97
|
# temporary points: delete casewise outliers
|
|
100
98
|
U = np.minimum(np.maximum(Z, -2), 2)
|
|
@@ -109,7 +107,7 @@ class InitialDDCWEstimator(RobustCovarianceEstimator):
|
|
|
109
107
|
Zimp_proj = Zimp @ eigenvectors
|
|
110
108
|
|
|
111
109
|
# wrapped location and covariance
|
|
112
|
-
Zimp_proj_scaler = RobustScaler(scale_estimator=
|
|
110
|
+
Zimp_proj_scaler = RobustScaler(scale_estimator=OneStepWrapping()).fit(
|
|
113
111
|
Zimp_proj, ignore_nan=True
|
|
114
112
|
)
|
|
115
113
|
Zimp_proj_scaler.scales_[
|
|
@@ -126,8 +124,8 @@ class InitialDDCWEstimator(RobustCovarianceEstimator):
|
|
|
126
124
|
)
|
|
127
125
|
cov = eigenvectors @ Zimp_proj_wrapped_cov @ eigenvectors.T # back to original axis system
|
|
128
126
|
cov = covariance_to_correlation(cov)
|
|
129
|
-
cov = (truncated_covariance(cov, self.min_eigenvalue) *
|
|
127
|
+
cov = (truncated_covariance(cov, self.min_eigenvalue) * ddc.scale_).T * ddc.scale_
|
|
130
128
|
|
|
131
|
-
self.location_ = np.array(
|
|
129
|
+
self.location_ = np.array(ddc.location_)
|
|
132
130
|
|
|
133
131
|
return cov
|
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
import numpy as np
|
|
2
2
|
from scipy.stats import kendalltau
|
|
3
|
-
from robpy.covariance.base import
|
|
4
|
-
from robpy.univariate import
|
|
3
|
+
from robpy.covariance.base import RobustCovariance
|
|
4
|
+
from robpy.univariate import Qn
|
|
5
5
|
|
|
6
6
|
|
|
7
|
-
class
|
|
7
|
+
class KendallTau(RobustCovariance):
|
|
8
8
|
"""Estimate the covariance matrix using Kendall's tau correlation."""
|
|
9
9
|
|
|
10
10
|
def calculate_covariance(self, X) -> np.ndarray:
|
|
11
11
|
p = X.shape[1]
|
|
12
|
-
scales = [
|
|
12
|
+
scales = [Qn().fit(col).scale for col in X.T]
|
|
13
13
|
cor = np.ones(shape=(p, p))
|
|
14
14
|
cov = np.ones(shape=(p, p))
|
|
15
15
|
for i in range(p):
|
|
@@ -6,12 +6,12 @@ from dataclasses import dataclass
|
|
|
6
6
|
from scipy.linalg import sqrtm
|
|
7
7
|
from scipy.stats import chi2, gamma, rankdata, norm
|
|
8
8
|
|
|
9
|
-
from robpy.covariance.base import
|
|
9
|
+
from robpy.covariance.base import RobustCovariance
|
|
10
10
|
from robpy.utils.distance import mahalanobis_distance
|
|
11
11
|
from robpy.utils.logging import get_logger
|
|
12
|
-
from robpy.univariate.qn import
|
|
13
|
-
from robpy.covariance.ogk import
|
|
14
|
-
from robpy.univariate.tau import
|
|
12
|
+
from robpy.univariate.qn import Qn
|
|
13
|
+
from robpy.covariance.ogk import OGK
|
|
14
|
+
from robpy.univariate.tau import Tau
|
|
15
15
|
|
|
16
16
|
|
|
17
17
|
@dataclass
|
|
@@ -23,11 +23,11 @@ class HSubset:
|
|
|
23
23
|
n_c_steps: int = 0
|
|
24
24
|
|
|
25
25
|
|
|
26
|
-
class
|
|
26
|
+
class FastMCD(RobustCovariance):
|
|
27
27
|
def __init__(
|
|
28
28
|
self,
|
|
29
29
|
*,
|
|
30
|
-
|
|
30
|
+
alpha: float | int | None = None,
|
|
31
31
|
n_initial_subsets: int = 500,
|
|
32
32
|
n_initial_c_steps: int = 2,
|
|
33
33
|
n_best_subsets: int = 10,
|
|
@@ -43,7 +43,7 @@ class FastMCDEstimator(RobustCovarianceEstimator):
|
|
|
43
43
|
Fast MCD estimator based on the algorithm proposed in Rousseeuw and Van Driessen (1999)
|
|
44
44
|
|
|
45
45
|
Args:
|
|
46
|
-
|
|
46
|
+
alpha (float | int | None, optional):
|
|
47
47
|
size of the h subset.
|
|
48
48
|
If an integer between n/2 and n is passed, it is interpreted as an absolute value.
|
|
49
49
|
If a float between 0.5 and 1 is passed, it is interpreted as a proportation
|
|
@@ -73,7 +73,7 @@ class FastMCDEstimator(RobustCovarianceEstimator):
|
|
|
73
73
|
|
|
74
74
|
"""
|
|
75
75
|
super().__init__(store_precision=store_precision, assume_centered=assume_centered)
|
|
76
|
-
self.
|
|
76
|
+
self.alpha = alpha
|
|
77
77
|
self.n_initial_subsets = n_initial_subsets
|
|
78
78
|
self.n_initial_c_steps = n_initial_c_steps
|
|
79
79
|
self.n_best_subsets = n_best_subsets
|
|
@@ -81,12 +81,12 @@ class FastMCDEstimator(RobustCovarianceEstimator):
|
|
|
81
81
|
self.tolerance = tolerance
|
|
82
82
|
self.correct_covariance = correct_covariance
|
|
83
83
|
self.reweighting = reweighting
|
|
84
|
-
self.logger = get_logger("
|
|
84
|
+
self.logger = get_logger("FastMCD", level=verbosity)
|
|
85
85
|
self.verbosity = verbosity
|
|
86
86
|
|
|
87
87
|
def calculate_covariance(self, X) -> np.ndarray:
|
|
88
|
-
if self.
|
|
89
|
-
self.logger.warning(f"Default covariance is returned as
|
|
88
|
+
if self.alpha == 1 or self.alpha == X.shape[0]:
|
|
89
|
+
self.logger.warning(f"Default covariance is returned as alpha is {self.alpha}.")
|
|
90
90
|
self.location_ = X.mean(0)
|
|
91
91
|
return np.cov(X, rowvar=False)
|
|
92
92
|
# partition data (n_partitions > 1 can speed up algorithm for large datasets)
|
|
@@ -174,23 +174,23 @@ class FastMCDEstimator(RobustCovarianceEstimator):
|
|
|
174
174
|
"""
|
|
175
175
|
# Calculate the Mahalanobis distances
|
|
176
176
|
mahalanobis = mahalanobis_distance(X, subset.location, subset.scale)
|
|
177
|
-
# Find the h_size smallest distances
|
|
177
|
+
# Find the alpha (h_size) smallest distances
|
|
178
178
|
h = self._get_h(X)
|
|
179
179
|
idx = np.argsort(mahalanobis)[:h]
|
|
180
180
|
|
|
181
181
|
return self._get_subset(indices=idx, X=X, n_c_steps=subset.n_c_steps + 1)
|
|
182
182
|
|
|
183
183
|
def _get_h(self, X: np.ndarray) -> int:
|
|
184
|
-
if self.
|
|
184
|
+
if self.alpha is None:
|
|
185
185
|
return int((X.shape[0] + X.shape[1] + 1) / 2)
|
|
186
|
-
elif isinstance(self.
|
|
187
|
-
return self.
|
|
188
|
-
elif (isinstance(self.
|
|
189
|
-
return int(self.
|
|
186
|
+
elif isinstance(self.alpha, int) and (X.shape[0] / 2 <= self.alpha <= X.shape[0]):
|
|
187
|
+
return self.alpha
|
|
188
|
+
elif (isinstance(self.alpha, float) and (0.5 <= self.alpha <= 1)) or self.alpha == 1:
|
|
189
|
+
return int(self.alpha * X.shape[0])
|
|
190
190
|
else:
|
|
191
191
|
raise ValueError(
|
|
192
|
-
f"
|
|
193
|
-
f" a float between 0.5 and 1, but received {self.
|
|
192
|
+
f"alpha must be an integer between n/2 ({X.shape[0] // 2}) and n ({X.shape[0]}) or"
|
|
193
|
+
f" a float between 0.5 and 1, but received {self.alpha}."
|
|
194
194
|
)
|
|
195
195
|
|
|
196
196
|
def _partition_data(self, X: np.ndarray) -> list[np.ndarray]:
|
|
@@ -242,11 +242,11 @@ class FastMCDEstimator(RobustCovarianceEstimator):
|
|
|
242
242
|
]
|
|
243
243
|
|
|
244
244
|
|
|
245
|
-
class
|
|
245
|
+
class DetMCD(RobustCovariance):
|
|
246
246
|
def __init__(
|
|
247
247
|
self,
|
|
248
248
|
*,
|
|
249
|
-
|
|
249
|
+
alpha: float | int | None = None,
|
|
250
250
|
tolerance: float = 1e-8,
|
|
251
251
|
correct_covariance: bool = True,
|
|
252
252
|
reweighting: bool = True,
|
|
@@ -257,7 +257,7 @@ class DetMCDEstimator(RobustCovarianceEstimator):
|
|
|
257
257
|
Hubert, Rousseeuw and Verdonck (2012)
|
|
258
258
|
|
|
259
259
|
Args:
|
|
260
|
-
|
|
260
|
+
alpha (float | int | None, optional):
|
|
261
261
|
size of the h subset.
|
|
262
262
|
If an integer between n/2 and n is passed, it is interpreted as an absolute value.
|
|
263
263
|
If a float between 0.5 and 1 is passed, it is interpreted as a proportation
|
|
@@ -277,16 +277,16 @@ class DetMCDEstimator(RobustCovarianceEstimator):
|
|
|
277
277
|
|
|
278
278
|
"""
|
|
279
279
|
super().__init__()
|
|
280
|
-
self.
|
|
280
|
+
self.alpha = alpha
|
|
281
281
|
self.tolerance = tolerance
|
|
282
282
|
self.correct_covariance = correct_covariance
|
|
283
283
|
self.reweighting = reweighting
|
|
284
|
-
self.logger = get_logger("
|
|
284
|
+
self.logger = get_logger("DetMCD", level=verbosity)
|
|
285
285
|
self.verbosity = verbosity
|
|
286
286
|
|
|
287
287
|
def calculate_covariance(self, X: np.ndarray) -> np.ndarray:
|
|
288
|
-
if self.
|
|
289
|
-
self.logger.warning(f"Default covariance is returned as
|
|
288
|
+
if self.alpha == 1 or self.alpha == X.shape[0]:
|
|
289
|
+
self.logger.warning(f"Default covariance is returned as alpha is {self.alpha}.")
|
|
290
290
|
self.location_ = X.mean(0)
|
|
291
291
|
return np.cov(X, rowvar=False)
|
|
292
292
|
|
|
@@ -341,21 +341,21 @@ class DetMCDEstimator(RobustCovarianceEstimator):
|
|
|
341
341
|
|
|
342
342
|
def _Qn_scale(self, X: np.ndarray, axis=0):
|
|
343
343
|
if X.ndim == 1:
|
|
344
|
-
return
|
|
344
|
+
return Qn().fit(X).scale
|
|
345
345
|
elif axis == 0:
|
|
346
|
-
return [
|
|
346
|
+
return [Qn().fit(col).scale for col in X.T]
|
|
347
347
|
elif axis == 1:
|
|
348
|
-
return [
|
|
348
|
+
return [Qn().fit(col).scale for col in X]
|
|
349
349
|
else:
|
|
350
350
|
raise ValueError(f"axis {axis} not supported")
|
|
351
351
|
|
|
352
352
|
def _tau_scale(self, X: np.ndarray, axis=0):
|
|
353
353
|
if X.ndim == 1:
|
|
354
|
-
return
|
|
354
|
+
return Tau().fit(X).scale
|
|
355
355
|
elif axis == 0:
|
|
356
|
-
return [
|
|
356
|
+
return [Tau().fit(col).scale for col in X.T]
|
|
357
357
|
elif axis == 1:
|
|
358
|
-
return [
|
|
358
|
+
return [Tau().fit(col).scale for col in X]
|
|
359
359
|
else:
|
|
360
360
|
raise ValueError(f"axis {axis} not supported")
|
|
361
361
|
|
|
@@ -371,7 +371,7 @@ class DetMCDEstimator(RobustCovarianceEstimator):
|
|
|
371
371
|
S4 = np.dot((Z * w[:, np.newaxis]).T, (Z * w[:, np.newaxis])) / n
|
|
372
372
|
idx = np.argsort(znorm)[: math.ceil(n / 2)]
|
|
373
373
|
S5 = np.cov(Z[idx, :], rowvar=False)
|
|
374
|
-
S6 =
|
|
374
|
+
S6 = OGK(
|
|
375
375
|
location_estimator=np.median, scale_estimator=self._Qn_scale, reweighting=False
|
|
376
376
|
).calculate_covariance(Z)
|
|
377
377
|
estimates_S = [S1, S2, S3, S4, S5, S6]
|
|
@@ -404,16 +404,16 @@ class DetMCDEstimator(RobustCovarianceEstimator):
|
|
|
404
404
|
# TODO: de functies hieronder moeten nog naar ergens anders.
|
|
405
405
|
|
|
406
406
|
def _get_h(self, X: np.ndarray) -> int:
|
|
407
|
-
if self.
|
|
407
|
+
if self.alpha is None:
|
|
408
408
|
return int((X.shape[0] + X.shape[1] + 1) / 2)
|
|
409
|
-
elif isinstance(self.
|
|
410
|
-
return self.
|
|
411
|
-
elif (isinstance(self.
|
|
412
|
-
return int(self.
|
|
409
|
+
elif isinstance(self.alpha, int) and (X.shape[0] / 2 <= self.alpha <= X.shape[0]):
|
|
410
|
+
return self.alpha
|
|
411
|
+
elif (isinstance(self.alpha, float) and (0.5 <= self.alpha <= 1)) or self.alpha == 1:
|
|
412
|
+
return int(self.alpha * X.shape[0])
|
|
413
413
|
else:
|
|
414
414
|
raise ValueError(
|
|
415
|
-
f"
|
|
416
|
-
f" a float between 0.5 and 1, but received {self.
|
|
415
|
+
f"alpha must be an integer between n/2 ({X.shape[0] // 2}) and n ({X.shape[0]}) or"
|
|
416
|
+
f" a float between 0.5 and 1, but received {self.alpha}."
|
|
417
417
|
)
|
|
418
418
|
|
|
419
419
|
def _get_subset(
|
|
@@ -456,7 +456,7 @@ class DetMCDEstimator(RobustCovarianceEstimator):
|
|
|
456
456
|
"""
|
|
457
457
|
# Calculate the Mahalanobis distances
|
|
458
458
|
mahalanobis = mahalanobis_distance(X, subset.location, subset.scale)
|
|
459
|
-
# Find the h_size smallest distances
|
|
459
|
+
# Find the alpha (h_size) smallest distances
|
|
460
460
|
h = self._get_h(X)
|
|
461
461
|
idx = np.argsort(mahalanobis)[:h]
|
|
462
462
|
|
|
@@ -2,11 +2,11 @@ import numpy as np
|
|
|
2
2
|
from scipy.stats import median_abs_deviation, chi2
|
|
3
3
|
|
|
4
4
|
from robpy.utils.distance import mahalanobis_distance
|
|
5
|
-
from robpy.covariance.base import
|
|
5
|
+
from robpy.covariance.base import RobustCovariance
|
|
6
6
|
from robpy.univariate import LocationOrScaleEstimator
|
|
7
7
|
|
|
8
8
|
|
|
9
|
-
class
|
|
9
|
+
class OGK(RobustCovariance):
|
|
10
10
|
def __init__(
|
|
11
11
|
self,
|
|
12
12
|
*,
|
|
@@ -4,7 +4,7 @@ from robpy.utils.general import inverse_submatrix
|
|
|
4
4
|
|
|
5
5
|
|
|
6
6
|
def objective_function(
|
|
7
|
-
X: np.ndarray, W: np.ndarray, location: np.
|
|
7
|
+
X: np.ndarray, W: np.ndarray, location: np.ndarray, cov: np.ndarray, cov_inv: np.ndarray
|
|
8
8
|
) -> float:
|
|
9
9
|
"""Calculates the value of the objective function in equation (8) of the CellMCD paper without
|
|
10
10
|
the penalty for a certain X, W, location, covariance and the inverse covariance
|