robpy 0.1.0__py3-none-any.whl

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.

Potentially problematic release.


This version of robpy might be problematic. Click here for more details.

Files changed (55) hide show
  1. robpy/__init__.py +0 -0
  2. robpy/covariance/__init__.py +6 -0
  3. robpy/covariance/base.py +82 -0
  4. robpy/covariance/cellmcd.py +621 -0
  5. robpy/covariance/initial_ddcw.py +133 -0
  6. robpy/covariance/kendall.py +21 -0
  7. robpy/covariance/mcd.py +470 -0
  8. robpy/covariance/ogk.py +95 -0
  9. robpy/covariance/utils/alter_covariance.py +31 -0
  10. robpy/covariance/utils/cellmcd_utils.py +38 -0
  11. robpy/covariance/utils/cellmcd_visualization_utils.py +96 -0
  12. robpy/covariance/wrapping.py +72 -0
  13. robpy/datasets/__init__.py +4 -0
  14. robpy/datasets/base.py +389 -0
  15. robpy/datasets/data/animals.csv +66 -0
  16. robpy/datasets/data/glass.csv +181 -0
  17. robpy/datasets/data/stars.csv +48 -0
  18. robpy/datasets/data/telephone.csv +25 -0
  19. robpy/datasets/data/topgear.csv +298 -0
  20. robpy/datasets/descr/animals.rst +26 -0
  21. robpy/datasets/descr/glass.rst +20 -0
  22. robpy/datasets/descr/stars.rst +28 -0
  23. robpy/datasets/descr/telephone.rst +23 -0
  24. robpy/datasets/descr/topgear.rst +51 -0
  25. robpy/outliers/__init__.py +4 -0
  26. robpy/outliers/ddc.py +296 -0
  27. robpy/pca/__init__.py +3 -0
  28. robpy/pca/base.py +97 -0
  29. robpy/pca/robpca.py +89 -0
  30. robpy/pca/spca.py +48 -0
  31. robpy/preprocessing/__init__.py +3 -0
  32. robpy/preprocessing/data_cleaner.py +214 -0
  33. robpy/preprocessing/scaling.py +57 -0
  34. robpy/preprocessing/transfo.py +591 -0
  35. robpy/preprocessing/utils.py +63 -0
  36. robpy/regression/__init__.py +3 -0
  37. robpy/regression/base.py +116 -0
  38. robpy/regression/lts.py +408 -0
  39. robpy/regression/mm_estimator.py +57 -0
  40. robpy/regression/s_estimator.py +188 -0
  41. robpy/univariate/__init__.py +9 -0
  42. robpy/univariate/base.py +53 -0
  43. robpy/univariate/mcd.py +84 -0
  44. robpy/univariate/onestep_m.py +143 -0
  45. robpy/univariate/qn.py +112 -0
  46. robpy/univariate/tau.py +63 -0
  47. robpy/utils/distance.py +24 -0
  48. robpy/utils/general.py +31 -0
  49. robpy/utils/logging.py +22 -0
  50. robpy/utils/median.py +62 -0
  51. robpy/utils/outlyingness.py +61 -0
  52. robpy/utils/rho.py +35 -0
  53. robpy-0.1.0.dist-info/METADATA +31 -0
  54. robpy-0.1.0.dist-info/RECORD +55 -0
  55. robpy-0.1.0.dist-info/WHEEL +4 -0
@@ -0,0 +1,26 @@
1
+ .. _animals_dataset:
2
+
3
+ Animals dataset
4
+ --------------------
5
+
6
+ **Data Set Characteristics:**
7
+
8
+ - Number of Instances: 65
9
+ - Number of Attributes: 2 numeric
10
+ - Attribute Information:
11
+ * body: body weight in kg.
12
+ * brain: brain weight in g
13
+
14
+ - Source: https://rdrr.io/cran/robustbase/man/Animals2.html
15
+ **Data Set Description:**
16
+
17
+ Dataset with average brain and body weights for 62 species of land mammals and three others.
18
+ Combination of the Animals and mammals datasets in MASS (r package).
19
+
20
+ **References**
21
+ - Venables, W. N. and Ripley, B. D. (2002) Modern Applied Statistics with S-PLUS. Fourth Edition. Springer.
22
+ - P. J. Rousseeuw and A. M. Leroy (1987) Robust Regression and Outlier Detection. Wiley, p. 57.
23
+ - Allison, T. and Cicchetti, D. V. (1976) Sleep in mammals: ecological and constitutional correlates. Science 194, 732–734.
24
+ - Weisberg, S. (1985) Applied Linear Regression. 2nd edition. Wiley, pp. 144–5.
25
+
26
+
@@ -0,0 +1,20 @@
1
+ .. _glass_dataset:
2
+
3
+ Glass dataset
4
+ --------------------
5
+
6
+ **Data Set Characteristics:**
7
+
8
+ - Number of Instances: 180
9
+ - Number of Attributes: 750 (numeric)
10
+ - Attribute Information:
11
+ * V1-750 (float) wavelength spectra
12
+ - Source: https://rdrr.io/cran/cellWise/man/data_glass.html
13
+
14
+ **Data Set Description:**
15
+ A dataset containing spectra with d = 750 wavelengths collected on n = 180 archeological glass samples.
16
+
17
+ **References**
18
+ - Lemberge, P., De Raedt, I., Janssens, K.H., Wei, F., and Van Espen, P.J. (2000). Quantitative Z-analysis of 16th-17th century archaeological glass vessels using PLS regression of EPXMA and \mu-XRF data. Journal of Chemometrics, 14, 751–763.
19
+
20
+
@@ -0,0 +1,28 @@
1
+ .. _stars_dataset:
2
+
3
+ Stars dataset
4
+ --------------------
5
+
6
+ **Data Set Characteristics:**
7
+
8
+ - Number of Instances: 47
9
+ - Number of Attributes: 2 numeric
10
+ - Attribute Information:
11
+ * Te: Logarithm of the effective temperature at the surface of the star (Te).
12
+ * light: Logarithm of its light intensity (L/L_0)
13
+
14
+
15
+ - Creator: Vanisma and Greve 1972
16
+ - Source: https://rdrr.io/cran/robustbase/man/starsCYG.html
17
+
18
+ **Data Set Description:**
19
+ Data for the Hertzsprung-Russell Diagram of the Star Cluster CYG OB1, which contains 47 stars in the direction of Cygnus, from C.Doom. The first variable is the logarithm of the effective temperature at the surface of the star (Te) and the second one is the logarithm of its light intencity (L/L_0).
20
+
21
+ In the Hertzsprung-Russell diagram, which is the scatterplot of these data points, where the log temperature is plotted from left to right, two groups of points are seen:
22
+ the majority which tend to follow a steep band and four stars in the upper corner. In the astronomy the 43 stars are said to lie on the main sequence and the four remaining stars are called “giants” (the points 11, 20, 30, 34).
23
+
24
+ **References**
25
+ - P. J. Rousseeuw and A. M. Leroy (1987) Robust Regression and Outlier Detection; Wiley, p.27, table 3.
26
+ - F. Vanisma and J. P. De Greve (1972), Close binary systems before and after mass transfer. Astrophysics and Space Science, 87, 377–401.
27
+ - D. J. Hand, F. Daly, A. D. Lunn, K. J. McConway and E. Ostrowski (1994). A Handbook of Small Datasets, Chapman and Hall/CRC, London.
28
+
@@ -0,0 +1,23 @@
1
+ .. _telephone_dataset:
2
+
3
+ Telephone dataset
4
+ --------------------
5
+
6
+ **Data Set Characteristics:**
7
+
8
+ - Number of Instances: 24
9
+ - Number of Attributes: 2 numeric
10
+ - Attribute Information:
11
+ * Year (1950 - 1973)
12
+ * Calls (in tens of millions)
13
+
14
+ - Missing Attribute Values: None
15
+ - Creator: Ministry of Economy, Belgium
16
+ - Source: https://rdrr.io/cran/robustbase/man/telef.html
17
+
18
+ **Data Set Description:**
19
+ Number of international calls from Belgium, taken from the Belgian Statistical Survey, published by the Ministry of Economy.
20
+
21
+ **References**
22
+ - P. J. Rousseeuw and A. M. Leroy (1987) Robust Regression and Outlier Detection; Wiley, page 26, table 2.
23
+
@@ -0,0 +1,51 @@
1
+ .. _topgear_dataset:
2
+
3
+ TopGear dataset
4
+ --------------------
5
+
6
+ **Data Set Characteristics:**
7
+
8
+ - Number of Instances: 297
9
+ - Number of Attributes: 32 (13 numeric, 19 categorical)
10
+ - Attribute Information:
11
+ * Maker (str): the car maker.
12
+ * Model (str): the car model.
13
+ * Type (str): the exact model type.
14
+ * Fuel (str): the type of fuel ("Diesel" or "Petrol").
15
+ * Price (float): the list price (in UK pounds)
16
+ * Cylinders (float): the number of cylinders in the engine.
17
+ * Displacement (float): the displacement of the engine (in cc).
18
+ * DriveWheel (str): the type of drive wheel ("4WD", "Front" or "Rear").
19
+ * BHP (float): the power of the engine (in bhp).
20
+ * Torque (float): the torque of the engine (in lb/ft).
21
+ * Acceleration (float): the time it takes the car to get from 0 to 62 mph (in seconds).
22
+ * TopSpeed (float): the car's top speed (in mph).
23
+ * MPG (float): the combined fuel consuption (urban + extra urban; in miles per gallon).
24
+ * Weight (float): the car's curb weight (in kg).
25
+ * Length (float): the car's length (in mm).
26
+ * Width (float): the car's width (in mm).
27
+ * Height (float): the car's height (in mm).
28
+ * AdaptiveHeadlights (str): whether the car has adaptive headlights ("no", "optional" or "standard").
29
+ * AdjustableSteering (str): whether the car has adjustable steering ("no" or "standard").
30
+ * AlarmSystem (str) whether the car has an alarm system ("no/optional" or "standard").
31
+ * Automatic (str) whether the car has an automatic transmission ("no", "optional" or "standard").
32
+ * Bluetooth (str) whether the car has bluetooth ("no", "optional" or "standard").
33
+ * ClimateControl (str) whether the car has climate control ("no", "optional" or "standard").
34
+ * CruiseControl (str) whether the car has cruise control ("no", "optional" or "standard").
35
+ * ElectricSeats (str) whether the car has electric seats ("no", "optional" or "standard").
36
+ * Leather (str) whether the car has a leather interior ("no", "optional" or "standard").
37
+ * ParkingSensors (str) whether the car has parking sensors ("no", "optional" or "standard").
38
+ * PowerSteering (str) whether the car has power steering ("no" or "standard").
39
+ * SatNav (str) whether the car has a satellite navigation system ("no", "optional" or "standard").
40
+ * ESP (str) whether the car has ESP ("no", "optional" or "standard").
41
+ * Verdict (float) review score between 1 (lowest) and 10 (highest).
42
+ * Origin (str) the origin of the car maker ("Asia", "Europe" or "USA").
43
+
44
+ - Creator: BBC TopGear
45
+ - Source: https://rdrr.io/cran/robustHD/man/TopGear.html
46
+
47
+ **Data Set Description:**
48
+ The data set contains information on cars featured on the website of the popular BBC television show Top Gear.
49
+ The data were scraped from http://www.topgear.com/uk/ on 2014-02-24. Variable Origin was added based on the car maker information.
50
+
51
+
@@ -0,0 +1,4 @@
1
+ """Module containing all algorithms related to outlier detection.
2
+ """
3
+
4
+ from robpy.outliers.ddc import DDCEstimator
robpy/outliers/ddc.py ADDED
@@ -0,0 +1,296 @@
1
+ import numpy as np
2
+ import pandas as pd
3
+ import seaborn as sns
4
+ import matplotlib.pyplot as plt
5
+
6
+ from matplotlib.axes import Axes
7
+ from sklearn.base import OutlierMixin
8
+ from scipy.stats import chi2
9
+
10
+ from robpy.univariate import CellwiseOneStepMEstimator
11
+ from robpy.utils.distance import mahalanobis_distance
12
+ from robpy.univariate.base import RobustScaleEstimator
13
+
14
+
15
+ class DDCEstimator(OutlierMixin):
16
+ def __init__(
17
+ self,
18
+ chi2_quantile: float = 0.99,
19
+ min_correlation: float = 0.5,
20
+ scale_estimator: RobustScaleEstimator = CellwiseOneStepMEstimator(),
21
+ ):
22
+ """Implementation of the Detecting Deviating Cells (DDC) algorithm.
23
+
24
+ Args:
25
+ chi2_quantile (float, optional): Quantile of the chi-squared distribution to use as
26
+ threshold for univariate outlier detection in step 2.
27
+ Default is 0.99.
28
+ min_correlation (float, optional): Minimum correlation between variables to consider
29
+ them
30
+ scale_estimator (RobustScaleEstimator, optional) : robust scale estimator to scale the
31
+ initial data with. Defaults to CellwiseOneStepMEstimator().
32
+
33
+ References:
34
+ Rousseeuw, P. J., & Bossche, W. V. D. (2018). Detecting Deviating Data Cells.
35
+ Technometrics, 60(2), 135–145. https://doi.org/10.1080/00401706.2017.1340909
36
+
37
+ R Implementation:
38
+ https://www.rdocumentation.org/packages/cellWise/versions/2.5.3/topics/DDC
39
+
40
+ """
41
+ self.chi2_quantile = chi2_quantile
42
+ self.cutoff = np.sqrt(chi2.ppf(chi2_quantile, df=1))
43
+ self.min_correlation = min_correlation
44
+ self.scale_estimator = scale_estimator
45
+
46
+ def fit(self, X: pd.DataFrame, y=None, verbose: bool = False):
47
+ self._check_data_conditions(X)
48
+ X = X.replace([np.inf, -np.inf], np.nan)
49
+ # step 1: standardization
50
+ Z = self._standardize(X)
51
+ # step 2: univariate outlier detection
52
+ U = pd.DataFrame(
53
+ data=np.where(np.abs(Z) > self.cutoff, np.nan, Z),
54
+ columns=X.columns,
55
+ index=X.index,
56
+ )
57
+ # step 3: correlation matrix and slopes
58
+ self.robust_correlation_ = self._robust_correlation(U, verbose=verbose)
59
+ self.slopes_ = self._get_slopes(U)
60
+
61
+ # step 4: predicted values
62
+ self.raw_predictions_ = self._get_predicted_values(U)
63
+
64
+ # step 5: deshrinkage
65
+ self.deshrinkage_ = np.array(
66
+ [
67
+ self._robust_slope(
68
+ self.raw_predictions_[~np.isnan(Z.iloc[:, i]), i],
69
+ Z.to_numpy()[~np.isnan(Z.iloc[:, i]), i],
70
+ )
71
+ for i in range(X.shape[1])
72
+ ]
73
+ )
74
+ self.predictions_ = self.raw_predictions_ * self.deshrinkage_
75
+
76
+ # step 6: cellwise outliers
77
+ self.raw_residuals_ = Z.values - self.predictions_
78
+ self.residual_scales_ = np.array(
79
+ [
80
+ CellwiseOneStepMEstimator()
81
+ .fit(self.raw_residuals_[:, i][~np.isnan(self.raw_residuals_[:, i])])
82
+ .scale
83
+ for i in range(X.shape[1])
84
+ ]
85
+ )
86
+ self.standardized_residuals_ = self.raw_residuals_ / self.residual_scales_
87
+ self.cellwise_outliers_ = np.abs(self.standardized_residuals_) > self.cutoff
88
+ # step 7: rowwise outliers
89
+ self.raw_t_values_ = np.nanmean(chi2.cdf(self.standardized_residuals_**2, df=1), axis=1)
90
+ est = CellwiseOneStepMEstimator().fit(self.raw_t_values_)
91
+ self.standardized_t_values_ = (self.raw_t_values_ - est.location) / est.scale
92
+ self.row_outliers_ = self.standardized_t_values_ > self.cutoff
93
+ self.is_fitted_ = True
94
+ # step 8: rescale
95
+ self.rescaled_predictions_ = self.predictions_ * self.scale_ + self.location_
96
+ return self
97
+
98
+ def predict(self, X, rowwise: bool = False):
99
+ if not self.is_fitted_:
100
+ raise ValueError("Model not fitted yet.")
101
+ if X.shape != self.cellwise_outliers_.shape:
102
+ raise ValueError("Predict can only be called with the same data as fit.")
103
+ if rowwise:
104
+ return self.row_outliers_
105
+
106
+ return self.cellwise_outliers_
107
+
108
+ def impute(self, X, impute_outliers: bool = True):
109
+ if not self.is_fitted_:
110
+ raise ValueError("Model not fitted yet.")
111
+ if X.shape[1] != self.cellwise_outliers_.shape[1]:
112
+ raise ValueError("Impute can only be called with the same data as fit.")
113
+ if impute_outliers:
114
+ results = np.where(
115
+ self.cellwise_outliers_ | np.isnan(X.replace([-np.inf, np.inf], np.nan)),
116
+ self.rescaled_predictions_,
117
+ X,
118
+ )
119
+ else:
120
+ results = np.where(
121
+ np.isnan(X.replace([-np.inf, np.inf], np.nan)), self.rescaled_predictions_, X
122
+ )
123
+
124
+ if isinstance(X, pd.DataFrame):
125
+ return pd.DataFrame(results, index=X.index, columns=X.columns)
126
+ else:
127
+ return results
128
+
129
+ def cellmap(
130
+ self,
131
+ X: pd.DataFrame,
132
+ annotate: bool = False,
133
+ only_color_outliers: bool = False,
134
+ fmt: str = ".1f",
135
+ figsize: tuple[int, int] = (7, 10),
136
+ row_zoom: tuple[int, int] | pd.Index | None = None,
137
+ col_zoom: tuple[int, int] | pd.Index | None = None,
138
+ vmax_clip: int = 10,
139
+ cmap: str = "Spectral",
140
+ ) -> Axes:
141
+ """Visualize the standardized residuals of the DDC model as a heatmap.
142
+
143
+ Args:
144
+ X (pd.DataFrame): The original data used to fit the model.
145
+ annotate (bool, optional): Whether to annotate the heatmap cells
146
+ with the original values. Defaults to False.
147
+ only_color_outliers (bool, optional):
148
+ If True, all none-outliers will be displayed as having 0 standardized residual.
149
+ Defaults to False.
150
+ fmt (str, optional): Format to use for annotations. Defaults to ".1f".
151
+ figsize (tuple[int, int], optional): Figure size. Defaults to (7, 10).
152
+ row_zoom (tuple[int, int] | pd.Index | None, optional):
153
+ If not None, a subset of the rows is selected for visualization.
154
+ A tuple is interpreted as a slice, a pd.Index as a selection.
155
+ Defaults to None.
156
+ col_zoom (tuple[int, int] | pd.Index | None, optional):
157
+ Similar to row_zoom but for columns. Defaults to None.
158
+
159
+ Returns:
160
+ Axes: the matplotlib axes with the heatmap
161
+ """
162
+ if not self.is_fitted_:
163
+ raise ValueError("Model not fitted yet.")
164
+ plot_data = pd.DataFrame(self.standardized_residuals_, index=X.index, columns=X.columns)
165
+ if only_color_outliers:
166
+ plot_data = pd.DataFrame(
167
+ np.where(self.cellwise_outliers_ | plot_data.isna(), plot_data, 0),
168
+ index=X.index,
169
+ columns=X.columns,
170
+ )
171
+ X_annot = X
172
+ if row_zoom is not None:
173
+ if isinstance(row_zoom, tuple):
174
+ plot_data = plot_data.iloc[row_zoom[0] : row_zoom[1], :]
175
+ X_annot = X_annot.iloc[row_zoom[0] : row_zoom[1], :]
176
+ else:
177
+ plot_data = plot_data.loc[row_zoom, :]
178
+ X_annot = X.loc[row_zoom, :]
179
+ if col_zoom is not None:
180
+ if isinstance(col_zoom, tuple):
181
+ plot_data = plot_data.iloc[:, col_zoom[0] : col_zoom[1]]
182
+ X_annot = X_annot.iloc[:, col_zoom[0] : col_zoom[1]]
183
+ else:
184
+ plot_data = plot_data.loc[:, col_zoom]
185
+ X_annot = X_annot.loc[:, col_zoom]
186
+ if annotate:
187
+ annotate = X_annot
188
+ _, ax = plt.subplots(1, 1, figsize=figsize)
189
+ vmax = min(np.nanmax(np.abs(plot_data)), vmax_clip)
190
+ ax = sns.heatmap(
191
+ plot_data,
192
+ cmap=cmap,
193
+ annot=annotate,
194
+ cbar_kws={"label": "Standardized residuals"},
195
+ fmt=fmt,
196
+ ax=ax,
197
+ vmin=-vmax,
198
+ vmax=vmax,
199
+ )
200
+ return ax
201
+
202
+ def _check_data_conditions(self, X: pd.DataFrame):
203
+ if X.select_dtypes(include=np.number).shape != X.shape:
204
+ raise ValueError("Only numerical data is supported.")
205
+ if any(X.nunique() <= 3):
206
+ raise ValueError("Columns with less than 3 unique values are not supported.")
207
+
208
+ def _standardize(self, X: pd.DataFrame):
209
+ self.location_, self.scale_ = [], []
210
+ for i in range(X.shape[1]):
211
+ est = self.scale_estimator.fit(X.iloc[:, i].to_numpy()[~np.isnan(X.iloc[:, i])])
212
+ self.location_.append(est.location)
213
+ self.scale_.append(est.scale)
214
+ return (X - self.location_) / self.scale_
215
+
216
+ def _robust_correlation(self, X: pd.DataFrame, verbose: bool = False) -> np.ndarray:
217
+ correlation = np.ones((X.shape[1], X.shape[1]))
218
+ for i in range(X.shape[1]):
219
+ if verbose and i % (X.shape[1] // 10) == 0:
220
+ print(
221
+ f"Correlation: Processing column {i + 1} of {X.shape[1]} "
222
+ f"({((i + 1) / X.shape[1]):.1%})"
223
+ )
224
+ for j in range(i + 1, X.shape[1]):
225
+ xy = X.iloc[:, [i, j]].values
226
+ xy = xy[~(np.isnan(xy).any(axis=1)), :]
227
+ if xy.size == 0:
228
+ correlation[i, j] = correlation[j, i] = 0
229
+ continue
230
+ x, y = xy.T
231
+ xy_corr = np.clip(
232
+ (
233
+ (
234
+ CellwiseOneStepMEstimator().fit(x + y).scale ** 2
235
+ - CellwiseOneStepMEstimator().fit(x - y).scale ** 2
236
+ )
237
+ / 4
238
+ ),
239
+ -0.99,
240
+ 0.99,
241
+ )
242
+ distances = mahalanobis_distance(
243
+ xy, np.array([0, 0]), np.array([[1, xy_corr], [xy_corr, 1]])
244
+ )
245
+ xy_subset = xy[distances < self.cutoff, :]
246
+ correlation[i, j] = correlation[j, i] = np.corrcoef(xy_subset, rowvar=False)[0, 1]
247
+ return correlation
248
+
249
+ def _robust_slope(self, x: np.ndarray, y: np.ndarray) -> float:
250
+ if np.all(x == 0):
251
+ return 0
252
+ init_slope = np.median(y[x != 0] / x[x != 0])
253
+ residuals = y - init_slope * x
254
+ r_cutoff = self.cutoff * CellwiseOneStepMEstimator().fit(residuals).scale
255
+ mask = np.abs(residuals) <= r_cutoff
256
+
257
+ return np.linalg.lstsq(x[mask].reshape(-1, 1), y[mask], rcond=None)[0][0]
258
+
259
+ def _get_slopes(self, X: pd.DataFrame) -> np.ndarray:
260
+ slopes = np.full((X.shape[1], X.shape[1]), np.nan)
261
+ for i in range(X.shape[1]):
262
+ for j in range(X.shape[1]):
263
+ if i == j:
264
+ continue
265
+ xy = X.iloc[:, [i, j]].values
266
+ xy = xy[(~np.isnan(xy).any(axis=1)), :].T
267
+ x, y = xy
268
+ xy_corr = self.robust_correlation_[i, j]
269
+ if np.abs(xy_corr) < self.min_correlation:
270
+ continue
271
+ slopes[i, j] = self._robust_slope(x, y)
272
+ return slopes
273
+
274
+ def _get_predicted_values(self, X: pd.DataFrame) -> np.ndarray:
275
+ predictions = np.zeros(X.shape)
276
+ for i in range(X.shape[1]):
277
+ weights = np.repeat(
278
+ [
279
+ [
280
+ np.abs(r) * (np.abs(r) >= 0.5) * (idx != i)
281
+ for idx, r in enumerate(self.robust_correlation_[:, i])
282
+ ]
283
+ ],
284
+ X.shape[0],
285
+ axis=0,
286
+ ) * ~np.isnan(X.values)
287
+
288
+ weights_sum = weights.sum(axis=1).reshape(-1, 1)
289
+ weights = np.divide(
290
+ weights, weights_sum, out=np.zeros_like(weights), where=weights_sum != 0
291
+ )
292
+ for j in range(X.shape[1]):
293
+ if np.isnan(self.slopes_[j, i]):
294
+ continue
295
+ predictions[:, i] += weights[:, j] * self.slopes_[j, i] * X.iloc[:, j].fillna(0)
296
+ return predictions
robpy/pca/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ from robpy.pca.base import get_od_cutoff
2
+ from robpy.pca.robpca import ROBPCAEstimator
3
+ from robpy.pca.spca import PCALocantoreEstimator
robpy/pca/base.py ADDED
@@ -0,0 +1,97 @@
1
+ import numpy as np
2
+ import pandas as pd
3
+ import matplotlib.pyplot as plt
4
+ from abc import abstractmethod
5
+ from sklearn.decomposition._base import _BasePCA
6
+ from scipy.stats import chi2, norm
7
+ from robpy.univariate import UnivariateMCDEstimator
8
+
9
+
10
+ class RobustPCAEstimator(_BasePCA):
11
+ def __init__(self, *, n_components: int | None = None):
12
+ """Base class for robust PCA estimators
13
+
14
+ Args:
15
+ n_components (int | None, optional):
16
+ Number of components to select. If None, it is set during fit to min (X.shape)
17
+
18
+ """
19
+ self.n_components = n_components
20
+
21
+ @abstractmethod
22
+ def fit(self, X: np.ndarray):
23
+ """Fit the robust PCA model to the data
24
+
25
+ Args:
26
+ X (np.ndarray): Data to fit the model to
27
+ """
28
+ pass
29
+
30
+ def transform(self, X: np.ndarray) -> np.ndarray:
31
+ """Apply dimensionality reduction to X.
32
+
33
+ X is projected on the first principal components previously extracted
34
+ from a training set.
35
+
36
+ Parameters
37
+ ----------
38
+ X : {array-like, sparse matrix} of shape (n_samples, n_features)
39
+ New data, where `n_samples` is the number of samples
40
+ and `n_features` is the number of features.
41
+
42
+ Returns
43
+ -------
44
+ X_new : array-like of shape (n_samples, n_components)
45
+ Projection of X in the first principal components, where `n_samples`
46
+ is the number of samples and `n_components` is the number of the components.
47
+ """
48
+ if self.location_ is None:
49
+ self.location_ = np.mean(X, axis=0)
50
+ return (X - self.location_) @ self.components_
51
+
52
+ def project(self, X: np.ndarray) -> np.ndarray:
53
+ """Project the data onto the subspace spanned by the principal components.
54
+
55
+ Args:
56
+ X (np.ndarray): Data to project
57
+
58
+ Returns:
59
+ np.ndarray: Projected data
60
+ """
61
+ return self.transform(X) @ self.components_.T
62
+
63
+ def plot_outlier_map(
64
+ self,
65
+ X: np.ndarray | pd.DataFrame,
66
+ figsize: tuple[int, int] = (10, 4),
67
+ return_distances: bool = False,
68
+ ) -> None | tuple[np.ndarray, np.ndarray, float, float]:
69
+ """Plot Orthogonal distances vs Score distances to identify different types of outliers
70
+
71
+ Args:
72
+ X (np.ndarray): Data matrix (n x p)
73
+ figsize (tuple[int, int], optional): Size of the plot. Defaults to (10, 4).
74
+ return_distances (bool, optional):
75
+ Whether to return the distances and cutoff values. Defaults to False.
76
+ """
77
+ if isinstance(X, pd.DataFrame):
78
+ X = X.values
79
+ orthogonal_distances = np.linalg.norm((X - self.location_) - self.project(X), axis=1)
80
+ score_distances = np.sqrt(
81
+ np.sum(np.square(self.transform(X)) / self.explained_variance_, axis=1)
82
+ )
83
+ _, ax = plt.subplots(1, 1, figsize=figsize)
84
+ ax.scatter(score_distances, orthogonal_distances)
85
+ ax.set_xlabel("Score distance")
86
+ ax.set_ylabel("Orthogonal distance")
87
+ score_cutoff = np.sqrt(float(chi2.ppf(0.975, self.n_components)))
88
+ od_cutoff = get_od_cutoff(orthogonal_distances)
89
+ ax.axvline(score_cutoff, color="r", linestyle="--")
90
+ ax.axhline(od_cutoff, color="r", linestyle="--")
91
+ if return_distances:
92
+ return (score_distances, orthogonal_distances, score_cutoff, od_cutoff)
93
+
94
+
95
+ def get_od_cutoff(orthogonal_distances: np.ndarray) -> float:
96
+ mcd = UnivariateMCDEstimator().fit(orthogonal_distances ** (2 / 3))
97
+ return float(mcd.location + mcd.scale * norm.ppf(0.975)) ** (3 / 2)
robpy/pca/robpca.py ADDED
@@ -0,0 +1,89 @@
1
+ from __future__ import annotations
2
+
3
+ import numpy as np
4
+
5
+ from sklearn.decomposition import PCA
6
+ from robpy.pca.base import RobustPCAEstimator, get_od_cutoff
7
+ from robpy.utils.outlyingness import stahel_donoho
8
+ from robpy.covariance import FastMCDEstimator
9
+
10
+
11
+ class ROBPCAEstimator(RobustPCAEstimator):
12
+ def __init__(
13
+ self,
14
+ *,
15
+ n_components: int | None = None,
16
+ k_min_var_explained: float = 0.8,
17
+ alpha: float = 0.75,
18
+ final_MCD_step: bool = True,
19
+ ):
20
+ """Implementation of ROBPCA algorithm as described in
21
+ Hubert, Rousseeuw & Vanden Branden (2005) and Hubert, Rousseeuw & Verdonck (2009)
22
+
23
+
24
+ Args:
25
+ n_components (int | None, optional):
26
+ Number of components to select. If None, it is set during fit to min (X.shape)
27
+ k_min_var_explained (float, optional): minimum variance explained by the n_components
28
+ Only used if n_components is None
29
+ alpha (float, optional): coverage parameter, determines the robustness and efficiency
30
+ trade off of the estimator.
31
+ Smaller alpha gives more robust but less accurate estimates
32
+ final_MCD_step (bool, optional): whether to apply the final MCD step to get maximally
33
+ robust estimates. If False, the eigenvectors after projection onto V1 (subspace
34
+ determined by points with OD < cutoff) are used as the final estimates.
35
+ Defaults to True.
36
+
37
+ References:
38
+ - Hubert, Rousseeuw & Vanden Branden (2005),
39
+ ROBPCA: A new approach to robust principal component analysis
40
+ - Hubert, Rousseeuw & Verdonck (2009) Robust PCA for skewed data and its outlier map
41
+
42
+ """
43
+ super().__init__(n_components=n_components)
44
+ self.k_min_var_explained = k_min_var_explained
45
+ self.alpha = alpha
46
+ self.final_MCD_step = final_MCD_step
47
+
48
+ def fit(self, X: np.ndarray) -> ROBPCAEstimator:
49
+ # step 1: singular value decomposition = applying standard PCA
50
+ pca = PCA()
51
+ X = pca.fit_transform(X)
52
+ self.location_ = np.mean(X, axis=0)
53
+ loadings = pca.components_.T
54
+ # step 2: stahel donoho outlyingness --> h subset
55
+ outlyingness = stahel_donoho(X)
56
+ h_index = np.argsort(outlyingness)[: int(self.alpha * X.shape[0])]
57
+ h_cov = np.cov(X[h_index], rowvar=False)
58
+ # step 3: project on k-dimensional subspace
59
+ eigvals_h, eigvecs_h = np.linalg.eigh(h_cov)
60
+ sorted_eig_h_idx = np.argsort(eigvals_h)[::-1]
61
+ var_explained_ratio = eigvals_h[sorted_eig_h_idx].cumsum() / eigvals_h.sum()
62
+ if self.n_components is None:
63
+ k = np.argmax(var_explained_ratio >= self.k_min_var_explained) + 1
64
+ else:
65
+ k = self.n_components
66
+ self.explained_variance_ = eigvals_h[sorted_eig_h_idx[:k]]
67
+ self.explained_variance_ratio = self.explained_variance_[:k].cumsum() / eigvals_h.sum()
68
+ h_components = eigvecs_h[:, sorted_eig_h_idx[:k]] # (p, k)
69
+ X_proj = (X - self.location_) @ h_components @ h_components.T
70
+ # step 4: orthogonal distance
71
+ orth_dist = np.linalg.norm((X - self.location_) - X_proj, axis=1)
72
+ v_index = np.argwhere(orth_dist < get_od_cutoff(orth_dist)).flatten()
73
+ cov_v = np.cov(X[v_index], rowvar=False)
74
+ eigvals_v, eigvecs_v = np.linalg.eigh(cov_v)
75
+ k = min(k, np.linalg.matrix_rank(cov_v, hermitian=True))
76
+ sorted_eig_v_idx = np.argsort(eigvals_v)[::-1]
77
+ self.components_ = eigvecs_v[:, sorted_eig_v_idx[:k]]
78
+ if self.final_MCD_step and k > 1:
79
+ # step 5: final MCD step
80
+ mcd = FastMCDEstimator().fit(self.transform(X))
81
+ _, eigvecs_mcd = np.linalg.eigh(mcd.covariance)
82
+ k = min(k, np.linalg.matrix_rank(mcd.covariance, hermitian=True))
83
+ self.components_ = self.components_ @ np.flip(eigvecs_mcd[:, -k:], axis=1)
84
+ # step 6: transform back to original X
85
+ self.n_components = k
86
+ X = pca.inverse_transform(X)
87
+ self.components_ = loadings @ self.components_
88
+ self.location_ = np.mean(X, axis=0)
89
+ return self