robpy 0.0.4__tar.gz → 0.0.6__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.
Files changed (60) hide show
  1. {robpy-0.0.4 → robpy-0.0.6}/PKG-INFO +4 -3
  2. {robpy-0.0.4 → robpy-0.0.6}/README.rst +2 -1
  3. {robpy-0.0.4 → robpy-0.0.6}/pyproject.toml +2 -2
  4. {robpy-0.0.4 → robpy-0.0.6}/robpy/covariance/base.py +26 -2
  5. {robpy-0.0.4 → robpy-0.0.6}/robpy/covariance/cellmcd.py +41 -28
  6. {robpy-0.0.4 → robpy-0.0.6}/robpy/covariance/initial_ddcw.py +22 -15
  7. {robpy-0.0.4 → robpy-0.0.6}/robpy/covariance/kendall.py +5 -1
  8. {robpy-0.0.4 → robpy-0.0.6}/robpy/covariance/mcd.py +101 -56
  9. {robpy-0.0.4 → robpy-0.0.6}/robpy/covariance/ogk.py +24 -22
  10. robpy-0.0.6/robpy/covariance/wrapping.py +81 -0
  11. {robpy-0.0.4 → robpy-0.0.6}/robpy/datasets/base.py +45 -40
  12. robpy-0.0.6/robpy/datasets/data/animals.csv +29 -0
  13. {robpy-0.0.4 → robpy-0.0.6}/robpy/datasets/descr/animals.rst +4 -5
  14. {robpy-0.0.4 → robpy-0.0.6}/robpy/outliers/ddc.py +15 -20
  15. {robpy-0.0.4 → robpy-0.0.6}/robpy/pca/base.py +12 -12
  16. {robpy-0.0.4 → robpy-0.0.6}/robpy/pca/robpca.py +39 -15
  17. {robpy-0.0.4 → robpy-0.0.6}/robpy/pca/spca.py +8 -3
  18. {robpy-0.0.4 → robpy-0.0.6}/robpy/preprocessing/data_cleaner.py +12 -12
  19. {robpy-0.0.4 → robpy-0.0.6}/robpy/preprocessing/scaling.py +10 -2
  20. {robpy-0.0.4 → robpy-0.0.6}/robpy/preprocessing/transfo.py +36 -28
  21. robpy-0.0.6/robpy/preprocessing/utils.py +80 -0
  22. {robpy-0.0.4 → robpy-0.0.6}/robpy/regression/base.py +29 -12
  23. {robpy-0.0.4 → robpy-0.0.6}/robpy/regression/lts.py +87 -71
  24. {robpy-0.0.4 → robpy-0.0.6}/robpy/regression/mm.py +18 -7
  25. {robpy-0.0.4 → robpy-0.0.6}/robpy/regression/s.py +23 -27
  26. {robpy-0.0.4 → robpy-0.0.6}/robpy/univariate/adjusted_boxplot.py +16 -10
  27. {robpy-0.0.4 → robpy-0.0.6}/robpy/univariate/base.py +2 -4
  28. {robpy-0.0.4 → robpy-0.0.6}/robpy/univariate/mcd.py +23 -11
  29. {robpy-0.0.4 → robpy-0.0.6}/robpy/univariate/onestep_m.py +17 -23
  30. {robpy-0.0.4 → robpy-0.0.6}/robpy/univariate/qn.py +23 -18
  31. {robpy-0.0.4 → robpy-0.0.6}/robpy/univariate/tau.py +10 -10
  32. {robpy-0.0.4 → robpy-0.0.6}/robpy/utils/distance.py +3 -3
  33. {robpy-0.0.4 → robpy-0.0.6}/robpy/utils/general.py +3 -3
  34. {robpy-0.0.4 → robpy-0.0.6}/robpy/utils/logging.py +3 -3
  35. {robpy-0.0.4 → robpy-0.0.6}/robpy/utils/median.py +12 -6
  36. {robpy-0.0.4 → robpy-0.0.6}/robpy/utils/outlyingness.py +21 -16
  37. {robpy-0.0.4 → robpy-0.0.6}/robpy/utils/rho.py +18 -0
  38. robpy-0.0.4/robpy/covariance/wrapping.py +0 -72
  39. robpy-0.0.4/robpy/datasets/data/animals.csv +0 -66
  40. robpy-0.0.4/robpy/preprocessing/utils.py +0 -63
  41. {robpy-0.0.4 → robpy-0.0.6}/LICENSE +0 -0
  42. {robpy-0.0.4 → robpy-0.0.6}/robpy/__init__.py +0 -0
  43. {robpy-0.0.4 → robpy-0.0.6}/robpy/covariance/__init__.py +0 -0
  44. {robpy-0.0.4 → robpy-0.0.6}/robpy/covariance/utils/alter_covariance.py +0 -0
  45. {robpy-0.0.4 → robpy-0.0.6}/robpy/covariance/utils/cellmcd_utils.py +0 -0
  46. {robpy-0.0.4 → robpy-0.0.6}/robpy/covariance/utils/cellmcd_visualization_utils.py +0 -0
  47. {robpy-0.0.4 → robpy-0.0.6}/robpy/datasets/__init__.py +0 -0
  48. {robpy-0.0.4 → robpy-0.0.6}/robpy/datasets/data/glass.csv +0 -0
  49. {robpy-0.0.4 → robpy-0.0.6}/robpy/datasets/data/stars.csv +0 -0
  50. {robpy-0.0.4 → robpy-0.0.6}/robpy/datasets/data/telephone.csv +0 -0
  51. {robpy-0.0.4 → robpy-0.0.6}/robpy/datasets/data/topgear.csv +0 -0
  52. {robpy-0.0.4 → robpy-0.0.6}/robpy/datasets/descr/glass.rst +0 -0
  53. {robpy-0.0.4 → robpy-0.0.6}/robpy/datasets/descr/stars.rst +0 -0
  54. {robpy-0.0.4 → robpy-0.0.6}/robpy/datasets/descr/telephone.rst +0 -0
  55. {robpy-0.0.4 → robpy-0.0.6}/robpy/datasets/descr/topgear.rst +0 -0
  56. {robpy-0.0.4 → robpy-0.0.6}/robpy/outliers/__init__.py +0 -0
  57. {robpy-0.0.4 → robpy-0.0.6}/robpy/pca/__init__.py +0 -0
  58. {robpy-0.0.4 → robpy-0.0.6}/robpy/preprocessing/__init__.py +0 -0
  59. {robpy-0.0.4 → robpy-0.0.6}/robpy/regression/__init__.py +0 -0
  60. {robpy-0.0.4 → robpy-0.0.6}/robpy/univariate/__init__.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: robpy
3
- Version: 0.0.4
3
+ Version: 0.0.6
4
4
  Summary:
5
5
  Author: Thomas Servotte
6
6
  Author-email: servottethomas@gmail.com
@@ -11,7 +11,7 @@ Classifier: Programming Language :: Python :: 3.11
11
11
  Classifier: Programming Language :: Python :: 3.12
12
12
  Classifier: Programming Language :: Python :: 3.13
13
13
  Requires-Dist: matplotlib (>=3.8.2,<4.0.0)
14
- Requires-Dist: scikit-learn (>=1.3)
14
+ Requires-Dist: scikit-learn (>=1.3,<1.7)
15
15
  Requires-Dist: scipy (>=1.11.4,<2.0.0)
16
16
  Requires-Dist: seaborn (>=0.13.2,<0.14.0)
17
17
  Requires-Dist: statsmodels (>=0.14.1,<0.15.0)
@@ -29,6 +29,7 @@ The project is currently maintained by the same team and distributed under MIT l
29
29
 
30
30
  Documentation is available at https://robpy.readthedocs.io/en/latest/
31
31
 
32
-
32
+ The structure and inner workings of the package are described in
33
+ Leyder, S., Raymaekers, J., Rousseeuw, P. J., Servotte, T., & Verdonck, T. (2024). RobPy: a Python Package for Robust Statistical Methods. arXiv preprint arXiv:2411.01954.
33
34
 
34
35
 
@@ -9,5 +9,6 @@ The project is currently maintained by the same team and distributed under MIT l
9
9
 
10
10
  Documentation is available at https://robpy.readthedocs.io/en/latest/
11
11
 
12
-
12
+ The structure and inner workings of the package are described in
13
+ Leyder, S., Raymaekers, J., Rousseeuw, P. J., Servotte, T., & Verdonck, T. (2024). RobPy: a Python Package for Robust Statistical Methods. arXiv preprint arXiv:2411.01954.
13
14
 
@@ -1,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "robpy"
3
- version = "0.0.4" # versioning is done by poetry-dynamic-versioning
3
+ version = "0.0.6" # 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"
@@ -37,7 +37,7 @@ max-line-length = 100
37
37
 
38
38
  [tool.poetry.dependencies]
39
39
  python = "^3.10"
40
- scikit-learn = ">=1.3"
40
+ scikit-learn = ">=1.3,<1.7"
41
41
  matplotlib = "^3.8.2"
42
42
  scipy = "^1.11.4"
43
43
  tqdm = "^4.66.1"
@@ -11,15 +11,39 @@ from robpy.utils.distance import mahalanobis_distance
11
11
 
12
12
 
13
13
  class RobustCovariance(EmpiricalCovariance):
14
- def __init__(self, *, store_precision=True, assume_centered=False, nans_allowed=False):
14
+ def __init__(
15
+ self,
16
+ *,
17
+ store_precision: bool = True,
18
+ assume_centered: bool = False,
19
+ nans_allowed: bool = False,
20
+ ):
21
+ """
22
+ Base class for robust covariance estimators.
23
+
24
+ Args:
25
+ store_precision (boolean, optional):
26
+ Whether to store the precision matrix. Defaults to True.
27
+ assume_centered (boolean, optional):
28
+ Whether the data is already centered. Defaults to False.
29
+ nans_allowed (boolean, optional):
30
+ Attribute specifying if nans are allowed. Defaults to False.
31
+ """
15
32
  super().__init__(
16
33
  store_precision=store_precision,
17
34
  assume_centered=assume_centered,
18
35
  )
36
+
19
37
  self.nans_allowed = nans_allowed
20
38
 
21
39
  def fit(self, X: np.ndarray | pd.DataFrame) -> RobustCovariance:
22
- """Fit the covariance estimator."""
40
+ """Fit the covariance estimator.
41
+
42
+ Args:
43
+ X (np.ndarray | pd.DataFrame):
44
+ Data matrix.
45
+
46
+ """
23
47
  if isinstance(X, pd.DataFrame):
24
48
  X = X.values
25
49
  if self.nans_allowed:
@@ -34,31 +34,31 @@ class CellMCD(RobustCovariance):
34
34
  verbosity: int = logging.WARNING,
35
35
  ):
36
36
  """
37
- Cell MCD estimator based on the algorithm proposed in Raymaekers and Rousseeuw (2023).
38
-
37
+ Cell MCD estimator based on the algorithm proposed in Raymaekers, J., & Rousseeuw, P. J.
38
+ (2024).
39
39
 
40
40
  Args:
41
41
  alpha (float, optional):
42
- Percentage indicating how much cells must remain unflagged in each column.
43
- Defaults to 0.75.
42
+ Percentage indicating how many cells must remain unflagged in each column.
43
+ Must lie within 0.5 to 1.0. Defaults to 0.75.
44
44
  quantile (float, optional):
45
45
  Cutoff value to flag cells.
46
46
  Defaults to 0.99.
47
47
  crit (float, optional):
48
48
  Stop iterating when successive covariance matrices of the standardized data
49
49
  differ by less than crit.
50
- Defaults to 1e-4
50
+ Defaults to 1e-4.
51
51
  max_c_steps (int, optional):
52
52
  Maximum number of C-steps used in the algorithm.
53
53
  Defaults to 100.
54
- min_eigenvalue: (float, optional):
54
+ min_eigenvalue (float, optional):
55
55
  Lower bound on the minimum eigenvalue of the covariance estimator
56
56
  on the standardized data. Should be at least 1e-6.
57
57
  Defaults to 1e-4.
58
58
 
59
59
  References:
60
- - Raymaekers and Rousseeuw, The Cellwise Minimum Covariance Determinant Estimator, 2023,
61
- Journal of the American Statistical Association.
60
+ - Raymaekers, J., & Rousseeuw, P. J. (2024). The cellwise minimum covariance determinant
61
+ estimator. Journal of the American Statistical Association, 119(548), 2610-2621.
62
62
  """
63
63
  if min_eigenvalue < 1e-6:
64
64
  raise ValueError("The lower bound on the eigenvalues should be at least 1e-6.")
@@ -72,6 +72,18 @@ class CellMCD(RobustCovariance):
72
72
  self.verbosity = verbosity
73
73
 
74
74
  def calculate_covariance(self, X: np.ndarray) -> np.ndarray:
75
+ # check that alpha creates a h-subset larger than [n/2]+1
76
+ n = X.shape[0]
77
+ if 0.5 <= self.alpha <= 1:
78
+ if self.alpha < (int(n / 2) + 1.0) / n:
79
+ self.logger.warning(
80
+ f"h = alpha*n is too small and therefore set to [n/2] + 1"
81
+ f" ({(int(n / 2) + 1.0) / n})."
82
+ )
83
+ self.alpha = np.max([self.alpha, (int(n / 2) + 1.0) / n])
84
+ else:
85
+ raise ValueError(f"alpha must a float between 0.5 and 1, but received {self.alpha}.")
86
+
75
87
  # Step 0: robustly standardize the data
76
88
  mads = median_abs_deviation(X, nan_policy="omit", axis=0)
77
89
  if np.min(mads) < 1e-8:
@@ -142,31 +154,32 @@ class CellMCD(RobustCovariance):
142
154
  annotation_quantile: float | None = None,
143
155
  ):
144
156
  """
145
- Function to plot the results of a cellMCD analysis: 5 types of diagnostic plots.
157
+ Function to plot the results of a cell MCD analysis: 5 types of diagnostic plots.
146
158
 
147
159
  Arguments:
148
- plottype (Literal string, optional):
149
- "indexplot": plots the residuals of a variable,
150
- "residuals_vs_variable": plots a variable versus its residuals,
151
- "residuals_vs_predictions": plots the predictions of a variable versus its
152
- residuals,
153
- "variable_vs_predictions": plots a variable against its predictions,
154
- "bivariate": plots two variables against each other,
155
-
156
- Defaults to "indexplot".
157
160
  variable (int): Index of the variable under consideration.
158
161
  variable_name (str, optional): Name of the variable of interest for the axis label.
159
162
  Defaults to "variable".
160
- second_variable (int): Index of the second variable under consideration,
163
+ row_names (list of strings, optional): Row names of the observations if you want
164
+ the outliers annoted with their name.
165
+ second_variable (int, optional): Index of the second variable under consideration,
161
166
  only needed for plottype "bivariate".
162
167
  second_variable_name (str, optional): Name of the second variable for the axis label,
163
168
  only relevant for plottype "bivariate". Defaults to "second variable".
164
- row_names (list of strings, optional): Row_names of the observations if you want
165
- the outliers annoted with their name.
169
+ plottype (Literal string, optional):
170
+ * "indexplot": plots the residuals of a variable versus the case numbers.
171
+ * "residuals_vs_variable": plots the residuals of a variable versus the variable
172
+ itself.
173
+ * "residuals_vs_predictions": plots the residuals of a variable versus the
174
+ predictions of that variable.
175
+ * "variable_vs_predictions": plots a variable against its predictions.
176
+ * "bivariate": plots two variables against each other.
177
+
178
+ Defaults to "indexplot".
166
179
  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
180
+ annotation_quantile (float | None, optional): The quantile used to draw an imaginary
181
+ threshold around the data. Only points outside these thresholds will be annotated. If
182
+ None, use self.quantile.
170
183
  """
171
184
 
172
185
  if not hasattr(self, "covariance_"):
@@ -235,7 +248,7 @@ class CellMCD(RobustCovariance):
235
248
  ax,
236
249
  self.quantile,
237
250
  )
238
- title = f"{variable_name} versus {second_variable_name}"
251
+ title = f"{second_variable_name} versus {variable_name}"
239
252
 
240
253
  ax.scatter(x=x, y=y)
241
254
  ax.set(xlabel=xlabel, ylabel=ylabel, title=title)
@@ -270,7 +283,7 @@ class CellMCD(RobustCovariance):
270
283
  def _make_predictions(
271
284
  self, X: np.ndarray, sigma: np.ndarray, sigma_inv: np.ndarray, mu: np.ndarray, W: np.ndarray
272
285
  ) -> tuple[np.ndarray, np.ndarray]:
273
- """Calculate the predictions of the cells given the other clean cells in the same row"""
286
+ """Calculate the predictions of the cells given the other clean cells in the same row."""
274
287
 
275
288
  n, p = X.shape
276
289
  predictions = np.zeros([n, p])
@@ -459,7 +472,7 @@ class CellMCD(RobustCovariance):
459
472
  mu: np.ndarray,
460
473
  j,
461
474
  ):
462
- """Calculates the delta's from equation (20) for the column j (without q_j)"""
475
+ """Calculates the delta's from equation (20) for the column j (without q_j)."""
463
476
 
464
477
  n = X.shape[0]
465
478
  delta = np.full(n, np.inf)
@@ -548,7 +561,7 @@ class CellMCD(RobustCovariance):
548
561
  sigma: np.ndarray,
549
562
  sigma_inv: np.ndarray,
550
563
  ):
551
- """Predict the observed values when there are both observed and missing values"""
564
+ """Predict the observed values when there are both observed and missing values."""
552
565
 
553
566
  if len(observed_col_idx) == 1: # only 1 observed value
554
567
  for index in row_idx_w:
@@ -1,8 +1,10 @@
1
+ import logging
1
2
  import numpy as np
2
3
  import pandas as pd
3
4
 
4
5
  from robpy.covariance.base import RobustCovariance
5
6
  from robpy.utils.distance import mahalanobis_distance
7
+ from robpy.utils.logging import get_logger
6
8
  from robpy.covariance.utils.alter_covariance import truncated_covariance, covariance_to_correlation
7
9
  from robpy.preprocessing.scaling import RobustScaler
8
10
  from robpy.univariate.onestep_m import OneStepWrapping
@@ -17,41 +19,46 @@ class InitialDDCW(RobustCovariance):
17
19
  *,
18
20
  alpha: float = 0.75,
19
21
  min_eigenvalue: float = 1e-4,
22
+ verbosity: int = logging.WARNING,
20
23
  ):
21
24
  """
22
- Calculates the initial robust scatter and location estimates for the CellMCD. Described
23
- in the Supplementary Material to Raymaekers and Rousseeuw 2023.
24
-
25
- code based on cellWise:::DDCWcov in R
25
+ Calculates the initial robust scatter and location estimates for the CellMCD, described
26
+ in the Supplementary Material to Raymaekers, J., & Rousseeuw, P. J. (2024). The code is
27
+ based on the function cellWise:::DDCWcov in R.
26
28
 
27
29
  Parameters:
28
30
  alpha (float, optional):
29
31
  Percentage indicating how much cells must remain unflagged in each column.
30
- Defaults to 0.75.
32
+ Must lie within 0.5 to 1.0. Defaults to 0.75.
31
33
  min_eigenvalue (float, optional):
32
34
  Lower bound on the minimum eigenvalue of the covariance estimator
33
35
  on the standardized data. Should be at least 1e-6.
34
36
  Defaults to 1e-4.
35
37
 
36
38
  References:
37
- - Raymaekers and Rousseeuw, The Cellwise Minimum Covariance Determinant Estimator, 2023,
38
- Journal of the American Statistical Association.
39
+ - Raymaekers, J., & Rousseeuw, P. J. (2024). The cellwise minimum covariance determinant
40
+ estimator. Journal of the American Statistical Association, 119(548), 2610-2621.
39
41
  """
40
42
  super().__init__(store_precision=True, assume_centered=False, nans_allowed=True)
41
43
  self.alpha = alpha
42
44
  self.min_eigenvalue = min_eigenvalue
45
+ self.logger = get_logger("InitialDDCW", level=verbosity)
46
+ self.verbosity = verbosity
43
47
 
44
48
  def calculate_covariance(self, X: np.ndarray):
45
- """Calculates the initial cellwise robust estimates of location and scatter using an
46
- adaptation of DDC.
47
-
48
- Arguments:
49
- X (np.ndarray): scaled data set
50
-
51
- [based on cellWise:::DDCWcov]"""
52
-
53
49
  n, p = X.shape
54
50
 
51
+ # check that alpha creates a h-subset larger than [n/2]+1
52
+ if 0.5 <= self.alpha <= 1:
53
+ if self.alpha < (int(n / 2) + 1.0) / n:
54
+ self.logger.warning(
55
+ f"h = alpha*n is too small and therefore set to [n/2] + 1"
56
+ f" ({(int(n / 2) + 1.0) / n})."
57
+ )
58
+ self.alpha = np.max([self.alpha, (int(n / 2) + 1.0) / n])
59
+ else:
60
+ raise ValueError(f"alpha must a float between 0.5 and 1, but received {self.alpha}.")
61
+
55
62
  # DDC with constraint -> imputed and rescaled Zimp:
56
63
  ddc = DDC(chi2_quantile=0.9, scale_estimator=OneStepWrapping()).fit(pd.DataFrame(X))
57
64
  W = np.copy(ddc.cellwise_outliers_)
@@ -5,7 +5,11 @@ from robpy.univariate import Qn
5
5
 
6
6
 
7
7
  class KendallTau(RobustCovariance):
8
- """Estimate the covariance matrix using Kendall's tau correlation."""
8
+ def __init__(
9
+ self,
10
+ ):
11
+ """Estimate a covariance matrix using Kendall's tau pairwise correlation."""
12
+ super().__init__()
9
13
 
10
14
  def calculate_covariance(self, X) -> np.ndarray:
11
15
  p = X.shape[1]
@@ -1,6 +1,7 @@
1
1
  import logging
2
2
  import numpy as np
3
3
  import math as math
4
+ import warnings
4
5
 
5
6
  from dataclasses import dataclass
6
7
  from scipy.linalg import sqrtm
@@ -41,38 +42,45 @@ class FastMCD(RobustCovariance):
41
42
  random_seed: int | None = None,
42
43
  ):
43
44
  """
44
- Fast MCD estimator based on the algorithm proposed in Rousseeuw and Van Driessen (1999)
45
+ Fast MCD estimator based on the algorithm proposed in Rousseeuw, P. J., & Van Driessen, K.
46
+ (1999).
45
47
 
46
48
  Args:
47
49
  alpha (float | int | None, optional):
48
- size of the h subset.
49
- If an integer between n/2 and n is passed, it is interpreted as an absolute value.
50
- If a float between 0.5 and 1 is passed, it is interpreted as a proportation
51
- of n (the training set size).
52
- If None, it is set to (n+p+1) / 2.
50
+ Size of the h subset.
51
+ If an integer between n/2 and n is passed, it is interpreted as h.
52
+ If a float between 0.5 and 1 is passed, it is interpreted as a proportion of n
53
+ (the training set size).
54
+ If None or an integer below [(n+p+1)/2], h is set to [(n+p+1)/2].
53
55
  Defaults to None.
54
56
  n_initial_subsets (int, optional):
55
- number of initial random subsets of size p+1
57
+ Number of initial random subsets of size p+1.
58
+ Defaults to 500.
56
59
  n_initial_c_steps (int, optional):
57
- number of initial c steps to perform on all initial subsets
60
+ Number of initial c steps to perform on all initial subsets.
61
+ Defaults to 2.
58
62
  n_best_subsets (int, optional):
59
- number of best subsets to keep and perform c steps on until convergence
63
+ Number of best subsets to keep and perform c steps on until convergence.
64
+ Defaults to 10.
60
65
  n_partitions (int, optional):
61
66
  Number of partitions to split the data into.
62
- This can speed up the algorithm for large datasets (n > 600 suggested in paper)
67
+ This can speed up the algorithm for large datasets (n > 600 suggested in paper).
63
68
  If None, 5 partitions are used if n > 600, otherwise 1 partition is used.
64
69
  tolerance (float, optional):
65
- Minimum difference in determinant between two iterations to stop the C-step
70
+ Minimum difference in determinant between two iterations to stop the C-step.
71
+ Defaults to 1e-8.
66
72
  correct_covariance (bool, optional):
67
- Whether to apply a consistency correction to the raw covariance estimate
73
+ Whether to apply a consistency correction to the raw covariance estimate.
74
+ Defaults to True.
68
75
  reweighting (bool, optional):
69
- Whether to apply reweighting to the raw covariance estimate
76
+ Whether to apply reweighting to the raw covariance estimate.
77
+ Defaults to True.
70
78
  random_seed (int | None, optional):
71
- Can be used to provide a random seed.
79
+ Can be used to provide a random seed. Defaults to None.
80
+
72
81
  References:
73
- Rousseeuw and Van Driessen, A Fast Algorithm for the Minimum Covariance Determinant
74
- Estimator, 1999, American Statistical Association and
75
- the American Society for Quality, TECHNOMETRICS
82
+ - Rousseeuw, P. J., & Van Driessen, K. (1999). A fast algorithm for the minimum
83
+ covariance determinant estimator. Technometrics, 41(3), 212-223.
76
84
 
77
85
  """
78
86
  super().__init__(store_precision=store_precision, assume_centered=assume_centered)
@@ -171,11 +179,11 @@ class FastMCD(RobustCovariance):
171
179
  Perform a single C-step on the subset of the data
172
180
 
173
181
  Args:
174
- subset_idx: indices of the current subset
175
- X: data
182
+ subset (HSubset): indices of the current subset.
183
+ X (np.ndarray): data.
176
184
 
177
185
  Returns:
178
- indices for new h subset
186
+ HSubset: indices for new h subset.
179
187
  """
180
188
  # Calculate the Mahalanobis distances
181
189
  mahalanobis = mahalanobis_distance(X, subset.location, subset.scale)
@@ -186,15 +194,29 @@ class FastMCD(RobustCovariance):
186
194
  return self._get_subset(indices=idx, X=X, n_c_steps=subset.n_c_steps + 1)
187
195
 
188
196
  def _get_h(self, X: np.ndarray) -> int:
197
+ n, p = X.shape
189
198
  if self.alpha is None:
190
- return int((X.shape[0] + X.shape[1] + 1) / 2)
191
- elif isinstance(self.alpha, int) and (X.shape[0] / 2 <= self.alpha <= X.shape[0]):
192
- return self.alpha
199
+ return int((n + p + 1) / 2)
200
+ elif isinstance(self.alpha, int) and (n / 2 <= self.alpha <= n):
201
+ if self.alpha < int((n + p + 1) / 2):
202
+ warnings.warn(
203
+ f"h is too small and therefore set to [(n+p+1)/2] ({int((n + p + 1) / 2)}).",
204
+ category=UserWarning,
205
+ stacklevel=2,
206
+ )
207
+ return np.max([self.alpha, int((n + p + 1) / 2)])
193
208
  elif (isinstance(self.alpha, float) and (0.5 <= self.alpha <= 1)) or self.alpha == 1:
194
- return int(self.alpha * X.shape[0])
209
+ if int(self.alpha * n) < int((n + p + 1) / 2):
210
+ warnings.warn(
211
+ f"h = alpha*n is too small and therefore set to [(n+p+1)/2]"
212
+ f" ({int((n + p + 1) / 2)}).",
213
+ category=UserWarning,
214
+ stacklevel=2,
215
+ )
216
+ return np.max([int(self.alpha * n), int((n + p + 1) / 2)])
195
217
  else:
196
218
  raise ValueError(
197
- f"alpha must be an integer between n/2 ({X.shape[0] // 2}) and n ({X.shape[0]}) or"
219
+ f"alpha must be an integer between n/2 and n or"
198
220
  f" a float between 0.5 and 1, but received {self.alpha}."
199
221
  )
200
222
 
@@ -218,11 +240,12 @@ class FastMCD(RobustCovariance):
218
240
  determinant.
219
241
 
220
242
  Args:
221
- - indices: data indices
222
- - X: complete dataset
223
- - n_c_steps: will be passed directly to the HSubset
224
- - ensure_non_singular: whether to resample in case the determinant is 0 (relevant for
225
- sampling initial subsets)
243
+ - indices (np.ndarray): data indices.
244
+ - X (np.ndarray): complete dataset.
245
+ - n_c_steps (int): will be passed directly to the HSubset.
246
+ - ensure_non_singular (bool): whether to resample in case the determinant is 0
247
+ (relevant for sampling initial subsets).
248
+
226
249
  """
227
250
  mu = X[indices].mean(axis=0)
228
251
  cov = np.cov(X[indices], rowvar=False)
@@ -258,27 +281,31 @@ class DetMCD(RobustCovariance):
258
281
  verbosity: int = logging.WARNING,
259
282
  ):
260
283
  """
261
- Deterministic MCD estimator (DetMCD) based on the algorithm proposed in
262
- Hubert, Rousseeuw and Verdonck (2012)
284
+ Deterministic MCD estimator (DetMCD) based on the algorithm proposed in Hubert, M.,
285
+ Rousseeuw, P. J., & Verdonck, T. (2012).
263
286
 
264
287
  Args:
265
288
  alpha (float | int | None, optional):
266
- size of the h subset.
267
- If an integer between n/2 and n is passed, it is interpreted as an absolute value.
268
- If a float between 0.5 and 1 is passed, it is interpreted as a proportation
269
- of n (the training set size).
270
- If None, it is set to (n+p+1) / 2.
271
- Defaults to None.
289
+ Size of the h subset.
290
+ If an integer between n/2 and n is passed, it is interpreted as h.
291
+ If a float between 0.5 and 1 is passed, it is interpreted as a proportion of n
292
+ (the training set size).
293
+ If None or an integer below [(n+p+1)/2], h is set to [(n+p+1)/2].
294
+ Defaults to None.
272
295
  tolerance (float, optional):
273
- Minimum difference in determinant between two iterations to stop the C-step
296
+ Minimum difference in determinant between two iterations to stop the C-step.
297
+ Defaults to 1e-8.
274
298
  correct_covariance (bool, optional):
275
- Whether to apply a consistency correction to the raw covariance estimate
299
+ Whether to apply a consistency correction to the raw covariance estimate.
300
+ Defaults to True.
276
301
  reweighting (bool, optional):
277
- Whether to apply reweighting to the raw covariance estimate
302
+ Whether to apply reweighting to the raw covariance estimate.
303
+ Defaults to True.
278
304
 
279
305
  References:
280
- Hubert, Rousseeuw and Verdonck, A deterministic algorithm for robust location
281
- and scatter, 2012, Journal of Computational and Graphical Statistics
306
+ - Hubert, M., Rousseeuw, P. J., & Verdonck, T. (2012). A deterministic algorithm for
307
+ robust location and scatter. Journal of Computational and Graphical Statistics, 21(3),
308
+ 618-637.
282
309
 
283
310
  """
284
311
  super().__init__()
@@ -409,15 +436,29 @@ class DetMCD(RobustCovariance):
409
436
  # TODO: de functies hieronder moeten nog naar ergens anders.
410
437
 
411
438
  def _get_h(self, X: np.ndarray) -> int:
439
+ n, p = X.shape
412
440
  if self.alpha is None:
413
- return int((X.shape[0] + X.shape[1] + 1) / 2)
414
- elif isinstance(self.alpha, int) and (X.shape[0] / 2 <= self.alpha <= X.shape[0]):
415
- return self.alpha
441
+ return int((n + p + 1) / 2)
442
+ elif isinstance(self.alpha, int) and (n / 2 <= self.alpha <= n):
443
+ if self.alpha < int((n + p + 1) / 2):
444
+ warnings.warn(
445
+ f"h is too small and therefore set to [(n+p+1)/2] ({int((n + p + 1) / 2)}).",
446
+ category=UserWarning,
447
+ stacklevel=2,
448
+ )
449
+ return np.max([self.alpha, int((n + p + 1) / 2)])
416
450
  elif (isinstance(self.alpha, float) and (0.5 <= self.alpha <= 1)) or self.alpha == 1:
417
- return int(self.alpha * X.shape[0])
451
+ if int(self.alpha * n) < int((n + p + 1) / 2):
452
+ warnings.warn(
453
+ f"h = alpha*n is too small and therefore set to [(n+p+1)/2]"
454
+ f" ({int((n + p + 1) / 2)}).",
455
+ category=UserWarning,
456
+ stacklevel=2,
457
+ )
458
+ return np.max([int(self.alpha * n), int((n + p + 1) / 2)])
418
459
  else:
419
460
  raise ValueError(
420
- f"alpha must be an integer between n/2 ({X.shape[0] // 2}) and n ({X.shape[0]}) or"
461
+ f"alpha must be an integer between n/2 and n or"
421
462
  f" a float between 0.5 and 1, but received {self.alpha}."
422
463
  )
423
464
 
@@ -430,12 +471,16 @@ class DetMCD(RobustCovariance):
430
471
  ) -> HSubset:
431
472
  """Construct an HSubset from a set of data indices and calculate location, scale and
432
473
  determinant.
474
+
433
475
  Args:
434
- - indices: data indices
435
- - X: complete dataset
436
- - n_c_steps: will be passed directly to the HSubset
437
- - ensure_non_singular: whether to resample in case the determinant is 0 (relevant for
438
- sampling initial subsets)
476
+ - indices (np.ndarray): data indices.
477
+ - X (np.ndarray): complete dataset.
478
+ - n_c_steps (int): will be passed directly to the HSubset.
479
+ - ensure_non_singular (bool): whether to resample in case the determinant is 0
480
+ (relevant for sampling initial subsets).
481
+
482
+ Returns:
483
+ Hsubset.
439
484
  """
440
485
  mu = X[indices].mean(axis=0)
441
486
  cov = np.cov(X[indices], rowvar=False)
@@ -453,11 +498,11 @@ class DetMCD(RobustCovariance):
453
498
  """Perform a single C-step on the subset of the data
454
499
 
455
500
  Args:
456
- subset_idx: indices of the current subset
457
- X: data
501
+ subset (HSubset): indices of the current subset.
502
+ X (np.ndarray): data.
458
503
 
459
504
  Returns:
460
- indices for new h subset
505
+ HSubset: indices for new h subset.
461
506
  """
462
507
  # Calculate the Mahalanobis distances
463
508
  mahalanobis = mahalanobis_distance(X, subset.location, subset.scale)
@@ -18,29 +18,34 @@ class OGK(RobustCovariance):
18
18
  reweighting: bool = False,
19
19
  reweighting_beta: float = 0.9
20
20
  ):
21
- """Implementation of the Orthogonalized Gnanadesikan-Kettenring estimator for location
22
- dispersion proposed in Maronna, R. A., & Zamar, R. H. (2002)
21
+ """
22
+ Implementation of the Orthogonalized Gnanadesikan-Kettenring estimator for location and
23
+ dispersion proposed in Maronna, R. A., & Zamar, R. H. (2002).
23
24
 
24
25
  Args:
25
- store_precision (boolean, optional): whether to store the precision matrix
26
- assume_centered (boolean, optional): whether the data is already centered
27
- location_estimator (LocationOrScaleEstimator, optional): function to estimate the
28
- location of the data, should accept an array like input as first value and a named
29
- argument axis
30
- scale_estimator (LocationOrScaleEstimator, optional): function to estimate the scale
31
- of the data, should accept an array like input as first value and a named argument
32
- axis
33
- n_iterations (int, optional): number of iteration for orthogonalization step
34
- reweighting (boolean, optional): whether to apply reweighting at the end
35
- (i.e. calculating regular location and covariance after filtering outliers based on
36
- Mahalanobis distance using OGK estimates)
37
- reweighting_beta (float, optional): quantile of chi2 distribution to use as cutoff for
38
- reweighting
26
+ store_precision (boolean, optional):
27
+ Whether to store the precision matrix. Defaults to True.
28
+ assume_centered (boolean, optional):
29
+ Whether the data is already centered. Defaults to False.
30
+ location_estimator (LocationOrScaleEstimator, optional):
31
+ Function to estimate the location of the data, should accept an array like input as
32
+ first value and a named argument axis. Defaults to np.median.
33
+ scale_estimator (LocationOrScaleEstimator, optional):
34
+ Function to estimate the scale of the data, should accept an array like input as
35
+ first value and a named argument axis. Defaults to median_abs_deviation.
36
+ n_iterations (int, optional):
37
+ Number of iterations for the orthogonalization step. Defaults to 2.
38
+ reweighting (boolean, optional):
39
+ Whether to apply reweighting at the end (i.e. calculating regular location and
40
+ covariance after filtering outliers based on Mahalanobis distance using OGK
41
+ estimates). Defaults to False.
42
+ reweighting_beta (float, optional):
43
+ Quantile of chi-squared distribution to use as cutoff for the reweighting. Defaults
44
+ to 0.9.
39
45
 
40
46
  References:
41
- Maronna, R. A., & Zamar, R. H. (2002).
42
- Robust Estimates of Location and Dispersion for High-Dimensional Datasets.
43
- Technometrics, 44(4), 307–317. http://www.jstor.org/stable/1271538
47
+ - Maronna, R. A., & Zamar, R. H. (2002). Robust estimates of location and dispersion for
48
+ high-dimensional datasets. Technometrics, 44(4), 307-317.
44
49
 
45
50
  """
46
51
  super().__init__(store_precision=store_precision, assume_centered=assume_centered)
@@ -51,9 +56,6 @@ class OGK(RobustCovariance):
51
56
  self.reweighting_beta = reweighting_beta
52
57
 
53
58
  def calculate_covariance(self, X) -> np.ndarray:
54
- """Calculate location and covariance with the algorithm described in Maronna & Zamar (2002).
55
- Covariance is returned, location is overwritten.
56
- """
57
59
  p = X.shape[1]
58
60
  Z = np.copy(X)
59
61
  DE = []