robpy 0.0.3__tar.gz → 0.0.5__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 (61) hide show
  1. {robpy-0.0.3 → robpy-0.0.5}/PKG-INFO +4 -3
  2. {robpy-0.0.3 → robpy-0.0.5}/README.rst +2 -1
  3. {robpy-0.0.3 → robpy-0.0.5}/pyproject.toml +1 -1
  4. {robpy-0.0.3 → robpy-0.0.5}/robpy/covariance/base.py +26 -2
  5. {robpy-0.0.3 → robpy-0.0.5}/robpy/covariance/cellmcd.py +41 -28
  6. {robpy-0.0.3 → robpy-0.0.5}/robpy/covariance/initial_ddcw.py +22 -15
  7. {robpy-0.0.3 → robpy-0.0.5}/robpy/covariance/kendall.py +5 -1
  8. {robpy-0.0.3 → robpy-0.0.5}/robpy/covariance/mcd.py +107 -57
  9. {robpy-0.0.3 → robpy-0.0.5}/robpy/covariance/ogk.py +24 -22
  10. robpy-0.0.5/robpy/covariance/wrapping.py +81 -0
  11. {robpy-0.0.3 → robpy-0.0.5}/robpy/datasets/base.py +45 -40
  12. robpy-0.0.5/robpy/datasets/data/animals.csv +29 -0
  13. {robpy-0.0.3 → robpy-0.0.5}/robpy/datasets/descr/animals.rst +4 -5
  14. {robpy-0.0.3 → robpy-0.0.5}/robpy/outliers/ddc.py +15 -20
  15. {robpy-0.0.3 → robpy-0.0.5}/robpy/pca/base.py +12 -12
  16. {robpy-0.0.3 → robpy-0.0.5}/robpy/pca/robpca.py +43 -15
  17. {robpy-0.0.3 → robpy-0.0.5}/robpy/pca/spca.py +8 -3
  18. {robpy-0.0.3 → robpy-0.0.5}/robpy/preprocessing/data_cleaner.py +12 -12
  19. {robpy-0.0.3 → robpy-0.0.5}/robpy/preprocessing/scaling.py +10 -2
  20. {robpy-0.0.3 → robpy-0.0.5}/robpy/preprocessing/transfo.py +36 -28
  21. robpy-0.0.5/robpy/preprocessing/utils.py +80 -0
  22. {robpy-0.0.3 → robpy-0.0.5}/robpy/regression/base.py +29 -12
  23. {robpy-0.0.3 → robpy-0.0.5}/robpy/regression/lts.py +87 -71
  24. {robpy-0.0.3 → robpy-0.0.5}/robpy/regression/mm.py +18 -7
  25. {robpy-0.0.3 → robpy-0.0.5}/robpy/regression/s.py +23 -27
  26. {robpy-0.0.3 → robpy-0.0.5}/robpy/univariate/adjusted_boxplot.py +16 -10
  27. {robpy-0.0.3 → robpy-0.0.5}/robpy/univariate/base.py +2 -4
  28. {robpy-0.0.3 → robpy-0.0.5}/robpy/univariate/mcd.py +23 -11
  29. {robpy-0.0.3 → robpy-0.0.5}/robpy/univariate/onestep_m.py +17 -23
  30. {robpy-0.0.3 → robpy-0.0.5}/robpy/univariate/qn.py +23 -18
  31. {robpy-0.0.3 → robpy-0.0.5}/robpy/univariate/tau.py +10 -10
  32. {robpy-0.0.3 → robpy-0.0.5}/robpy/utils/distance.py +3 -3
  33. {robpy-0.0.3 → robpy-0.0.5}/robpy/utils/general.py +3 -3
  34. {robpy-0.0.3 → robpy-0.0.5}/robpy/utils/logging.py +3 -3
  35. {robpy-0.0.3 → robpy-0.0.5}/robpy/utils/median.py +12 -6
  36. robpy-0.0.5/robpy/utils/outlyingness.py +81 -0
  37. {robpy-0.0.3 → robpy-0.0.5}/robpy/utils/rho.py +18 -0
  38. robpy-0.0.3/robpy/covariance/wrapping.py +0 -72
  39. robpy-0.0.3/robpy/datasets/data/animals.csv +0 -66
  40. robpy-0.0.3/robpy/preprocessing/utils.py +0 -63
  41. robpy-0.0.3/robpy/utils/outlyingness.py +0 -61
  42. {robpy-0.0.3 → robpy-0.0.5}/LICENSE +0 -0
  43. {robpy-0.0.3 → robpy-0.0.5}/robpy/__init__.py +0 -0
  44. {robpy-0.0.3 → robpy-0.0.5}/robpy/covariance/__init__.py +0 -0
  45. {robpy-0.0.3 → robpy-0.0.5}/robpy/covariance/utils/alter_covariance.py +0 -0
  46. {robpy-0.0.3 → robpy-0.0.5}/robpy/covariance/utils/cellmcd_utils.py +0 -0
  47. {robpy-0.0.3 → robpy-0.0.5}/robpy/covariance/utils/cellmcd_visualization_utils.py +0 -0
  48. {robpy-0.0.3 → robpy-0.0.5}/robpy/datasets/__init__.py +0 -0
  49. {robpy-0.0.3 → robpy-0.0.5}/robpy/datasets/data/glass.csv +0 -0
  50. {robpy-0.0.3 → robpy-0.0.5}/robpy/datasets/data/stars.csv +0 -0
  51. {robpy-0.0.3 → robpy-0.0.5}/robpy/datasets/data/telephone.csv +0 -0
  52. {robpy-0.0.3 → robpy-0.0.5}/robpy/datasets/data/topgear.csv +0 -0
  53. {robpy-0.0.3 → robpy-0.0.5}/robpy/datasets/descr/glass.rst +0 -0
  54. {robpy-0.0.3 → robpy-0.0.5}/robpy/datasets/descr/stars.rst +0 -0
  55. {robpy-0.0.3 → robpy-0.0.5}/robpy/datasets/descr/telephone.rst +0 -0
  56. {robpy-0.0.3 → robpy-0.0.5}/robpy/datasets/descr/topgear.rst +0 -0
  57. {robpy-0.0.3 → robpy-0.0.5}/robpy/outliers/__init__.py +0 -0
  58. {robpy-0.0.3 → robpy-0.0.5}/robpy/pca/__init__.py +0 -0
  59. {robpy-0.0.3 → robpy-0.0.5}/robpy/preprocessing/__init__.py +0 -0
  60. {robpy-0.0.3 → robpy-0.0.5}/robpy/regression/__init__.py +0 -0
  61. {robpy-0.0.3 → robpy-0.0.5}/robpy/univariate/__init__.py +0 -0
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.1
1
+ Metadata-Version: 2.3
2
2
  Name: robpy
3
- Version: 0.0.3
3
+ Version: 0.0.5
4
4
  Summary:
5
5
  Author: Thomas Servotte
6
6
  Author-email: servottethomas@gmail.com
@@ -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.3" # versioning is done by poetry-dynamic-versioning
3
+ version = "0.0.5" # 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"
@@ -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
@@ -38,38 +39,48 @@ class FastMCD(RobustCovariance):
38
39
  verbosity: int = logging.WARNING,
39
40
  store_precision=True,
40
41
  assume_centered=False,
42
+ random_seed: int | None = None,
41
43
  ):
42
44
  """
43
- 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).
44
47
 
45
48
  Args:
46
49
  alpha (float | int | None, optional):
47
- size of the h subset.
48
- If an integer between n/2 and n is passed, it is interpreted as an absolute value.
49
- If a float between 0.5 and 1 is passed, it is interpreted as a proportation
50
- of n (the training set size).
51
- 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].
52
55
  Defaults to None.
53
56
  n_initial_subsets (int, optional):
54
- number of initial random subsets of size p+1
57
+ Number of initial random subsets of size p+1.
58
+ Defaults to 500.
55
59
  n_initial_c_steps (int, optional):
56
- 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.
57
62
  n_best_subsets (int, optional):
58
- 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.
59
65
  n_partitions (int, optional):
60
66
  Number of partitions to split the data into.
61
- 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).
62
68
  If None, 5 partitions are used if n > 600, otherwise 1 partition is used.
63
69
  tolerance (float, optional):
64
- 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.
65
72
  correct_covariance (bool, optional):
66
- 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.
67
75
  reweighting (bool, optional):
68
- Whether to apply reweighting to the raw covariance estimate
76
+ Whether to apply reweighting to the raw covariance estimate.
77
+ Defaults to True.
78
+ random_seed (int | None, optional):
79
+ Can be used to provide a random seed. Defaults to None.
80
+
69
81
  References:
70
- Rousseeuw and Van Driessen, A Fast Algorithm for the Minimum Covariance Determinant
71
- Estimator, 1999, American Statistical Association and
72
- 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.
73
84
 
74
85
  """
75
86
  super().__init__(store_precision=store_precision, assume_centered=assume_centered)
@@ -83,12 +94,14 @@ class FastMCD(RobustCovariance):
83
94
  self.reweighting = reweighting
84
95
  self.logger = get_logger("FastMCD", level=verbosity)
85
96
  self.verbosity = verbosity
97
+ self.random_seed = random_seed
86
98
 
87
99
  def calculate_covariance(self, X) -> np.ndarray:
88
100
  if self.alpha == 1 or self.alpha == X.shape[0]:
89
101
  self.logger.warning(f"Default covariance is returned as alpha is {self.alpha}.")
90
102
  self.location_ = X.mean(0)
91
103
  return np.cov(X, rowvar=False)
104
+ self.rng = np.random.default_rng(self.random_seed)
92
105
  # partition data (n_partitions > 1 can speed up algorithm for large datasets)
93
106
  partitions = self._partition_data(X)
94
107
  self.logger.info(f"Partitioned data into {len(partitions)} partitions")
@@ -166,11 +179,11 @@ class FastMCD(RobustCovariance):
166
179
  Perform a single C-step on the subset of the data
167
180
 
168
181
  Args:
169
- subset_idx: indices of the current subset
170
- X: data
182
+ subset (HSubset): indices of the current subset.
183
+ X (np.ndarray): data.
171
184
 
172
185
  Returns:
173
- indices for new h subset
186
+ HSubset: indices for new h subset.
174
187
  """
175
188
  # Calculate the Mahalanobis distances
176
189
  mahalanobis = mahalanobis_distance(X, subset.location, subset.scale)
@@ -181,15 +194,29 @@ class FastMCD(RobustCovariance):
181
194
  return self._get_subset(indices=idx, X=X, n_c_steps=subset.n_c_steps + 1)
182
195
 
183
196
  def _get_h(self, X: np.ndarray) -> int:
197
+ n, p = X.shape
184
198
  if self.alpha is None:
185
- return int((X.shape[0] + X.shape[1] + 1) / 2)
186
- elif isinstance(self.alpha, int) and (X.shape[0] / 2 <= self.alpha <= X.shape[0]):
187
- 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)])
188
208
  elif (isinstance(self.alpha, float) and (0.5 <= self.alpha <= 1)) or self.alpha == 1:
189
- 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)])
190
217
  else:
191
218
  raise ValueError(
192
- 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"
193
220
  f" a float between 0.5 and 1, but received {self.alpha}."
194
221
  )
195
222
 
@@ -213,18 +240,19 @@ class FastMCD(RobustCovariance):
213
240
  determinant.
214
241
 
215
242
  Args:
216
- - indices: data indices
217
- - X: complete dataset
218
- - n_c_steps: will be passed directly to the HSubset
219
- - ensure_non_singular: whether to resample in case the determinant is 0 (relevant for
220
- 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
+
221
249
  """
222
250
  mu = X[indices].mean(axis=0)
223
251
  cov = np.cov(X[indices], rowvar=False)
224
252
  det = np.linalg.det(cov)
225
253
  if ensure_non_singular:
226
254
  while math.isclose(det, 0):
227
- new_index = np.random.choice(np.delete(np.arange(X.shape[0]), indices))
255
+ new_index = self.rng.choice(np.delete(np.arange(X.shape[0]), indices))
228
256
  indices = np.append(indices, new_index)
229
257
  mu = X[indices].mean(axis=0)
230
258
  cov = np.cov(X[indices], rowvar=False)
@@ -234,7 +262,7 @@ class FastMCD(RobustCovariance):
234
262
  def _get_initial_subsets(self, X: np.ndarray, n_subsets: int) -> list[HSubset]:
235
263
  return [
236
264
  self._get_subset(
237
- indices=np.random.choice(X.shape[0], X.shape[1] + 1, replace=False),
265
+ indices=self.rng.choice(X.shape[0], X.shape[1] + 1, replace=False),
238
266
  X=X,
239
267
  ensure_non_singular=True,
240
268
  )
@@ -253,27 +281,31 @@ class DetMCD(RobustCovariance):
253
281
  verbosity: int = logging.WARNING,
254
282
  ):
255
283
  """
256
- Deterministic MCD estimator (DetMCD) based on the algorithm proposed in
257
- 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).
258
286
 
259
287
  Args:
260
288
  alpha (float | int | None, optional):
261
- size of the h subset.
262
- If an integer between n/2 and n is passed, it is interpreted as an absolute value.
263
- If a float between 0.5 and 1 is passed, it is interpreted as a proportation
264
- of n (the training set size).
265
- If None, it is set to (n+p+1) / 2.
266
- 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.
267
295
  tolerance (float, optional):
268
- 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.
269
298
  correct_covariance (bool, optional):
270
- 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.
271
301
  reweighting (bool, optional):
272
- Whether to apply reweighting to the raw covariance estimate
302
+ Whether to apply reweighting to the raw covariance estimate.
303
+ Defaults to True.
273
304
 
274
305
  References:
275
- Hubert, Rousseeuw and Verdonck, A deterministic algorithm for robust location
276
- 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.
277
309
 
278
310
  """
279
311
  super().__init__()
@@ -404,15 +436,29 @@ class DetMCD(RobustCovariance):
404
436
  # TODO: de functies hieronder moeten nog naar ergens anders.
405
437
 
406
438
  def _get_h(self, X: np.ndarray) -> int:
439
+ n, p = X.shape
407
440
  if self.alpha is None:
408
- return int((X.shape[0] + X.shape[1] + 1) / 2)
409
- elif isinstance(self.alpha, int) and (X.shape[0] / 2 <= self.alpha <= X.shape[0]):
410
- 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)])
411
450
  elif (isinstance(self.alpha, float) and (0.5 <= self.alpha <= 1)) or self.alpha == 1:
412
- 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)])
413
459
  else:
414
460
  raise ValueError(
415
- 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"
416
462
  f" a float between 0.5 and 1, but received {self.alpha}."
417
463
  )
418
464
 
@@ -425,12 +471,16 @@ class DetMCD(RobustCovariance):
425
471
  ) -> HSubset:
426
472
  """Construct an HSubset from a set of data indices and calculate location, scale and
427
473
  determinant.
474
+
428
475
  Args:
429
- - indices: data indices
430
- - X: complete dataset
431
- - n_c_steps: will be passed directly to the HSubset
432
- - ensure_non_singular: whether to resample in case the determinant is 0 (relevant for
433
- 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.
434
484
  """
435
485
  mu = X[indices].mean(axis=0)
436
486
  cov = np.cov(X[indices], rowvar=False)
@@ -448,11 +498,11 @@ class DetMCD(RobustCovariance):
448
498
  """Perform a single C-step on the subset of the data
449
499
 
450
500
  Args:
451
- subset_idx: indices of the current subset
452
- X: data
501
+ subset (HSubset): indices of the current subset.
502
+ X (np.ndarray): data.
453
503
 
454
504
  Returns:
455
- indices for new h subset
505
+ HSubset: indices for new h subset.
456
506
  """
457
507
  # Calculate the Mahalanobis distances
458
508
  mahalanobis = mahalanobis_distance(X, subset.location, subset.scale)