robpy 0.0.6__tar.gz → 0.1.2__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.6 → robpy-0.1.2}/PKG-INFO +6 -3
- {robpy-0.0.6 → robpy-0.1.2}/pyproject.toml +2 -2
- {robpy-0.0.6 → robpy-0.1.2}/robpy/covariance/base.py +24 -1
- {robpy-0.0.6 → robpy-0.1.2}/robpy/covariance/cellmcd.py +158 -20
- {robpy-0.0.6 → robpy-0.1.2}/robpy/covariance/mcd.py +28 -16
- {robpy-0.0.6 → robpy-0.1.2}/robpy/outliers/ddc.py +198 -60
- {robpy-0.0.6 → robpy-0.1.2}/robpy/preprocessing/transfo.py +242 -142
- {robpy-0.0.6 → robpy-0.1.2}/LICENSE +0 -0
- {robpy-0.0.6 → robpy-0.1.2}/README.rst +0 -0
- {robpy-0.0.6 → robpy-0.1.2}/robpy/__init__.py +0 -0
- {robpy-0.0.6 → robpy-0.1.2}/robpy/covariance/__init__.py +0 -0
- {robpy-0.0.6 → robpy-0.1.2}/robpy/covariance/initial_ddcw.py +0 -0
- {robpy-0.0.6 → robpy-0.1.2}/robpy/covariance/kendall.py +0 -0
- {robpy-0.0.6 → robpy-0.1.2}/robpy/covariance/ogk.py +0 -0
- {robpy-0.0.6 → robpy-0.1.2}/robpy/covariance/utils/alter_covariance.py +0 -0
- {robpy-0.0.6 → robpy-0.1.2}/robpy/covariance/utils/cellmcd_utils.py +0 -0
- {robpy-0.0.6 → robpy-0.1.2}/robpy/covariance/utils/cellmcd_visualization_utils.py +0 -0
- {robpy-0.0.6 → robpy-0.1.2}/robpy/covariance/wrapping.py +0 -0
- {robpy-0.0.6 → robpy-0.1.2}/robpy/datasets/__init__.py +0 -0
- {robpy-0.0.6 → robpy-0.1.2}/robpy/datasets/base.py +0 -0
- {robpy-0.0.6 → robpy-0.1.2}/robpy/datasets/data/animals.csv +0 -0
- {robpy-0.0.6 → robpy-0.1.2}/robpy/datasets/data/glass.csv +0 -0
- {robpy-0.0.6 → robpy-0.1.2}/robpy/datasets/data/stars.csv +0 -0
- {robpy-0.0.6 → robpy-0.1.2}/robpy/datasets/data/telephone.csv +0 -0
- {robpy-0.0.6 → robpy-0.1.2}/robpy/datasets/data/topgear.csv +0 -0
- {robpy-0.0.6 → robpy-0.1.2}/robpy/datasets/descr/animals.rst +0 -0
- {robpy-0.0.6 → robpy-0.1.2}/robpy/datasets/descr/glass.rst +0 -0
- {robpy-0.0.6 → robpy-0.1.2}/robpy/datasets/descr/stars.rst +0 -0
- {robpy-0.0.6 → robpy-0.1.2}/robpy/datasets/descr/telephone.rst +0 -0
- {robpy-0.0.6 → robpy-0.1.2}/robpy/datasets/descr/topgear.rst +0 -0
- {robpy-0.0.6 → robpy-0.1.2}/robpy/outliers/__init__.py +0 -0
- {robpy-0.0.6 → robpy-0.1.2}/robpy/pca/__init__.py +0 -0
- {robpy-0.0.6 → robpy-0.1.2}/robpy/pca/base.py +0 -0
- {robpy-0.0.6 → robpy-0.1.2}/robpy/pca/robpca.py +0 -0
- {robpy-0.0.6 → robpy-0.1.2}/robpy/pca/spca.py +0 -0
- {robpy-0.0.6 → robpy-0.1.2}/robpy/preprocessing/__init__.py +0 -0
- {robpy-0.0.6 → robpy-0.1.2}/robpy/preprocessing/data_cleaner.py +0 -0
- {robpy-0.0.6 → robpy-0.1.2}/robpy/preprocessing/scaling.py +0 -0
- {robpy-0.0.6 → robpy-0.1.2}/robpy/preprocessing/utils.py +0 -0
- {robpy-0.0.6 → robpy-0.1.2}/robpy/regression/__init__.py +0 -0
- {robpy-0.0.6 → robpy-0.1.2}/robpy/regression/base.py +0 -0
- {robpy-0.0.6 → robpy-0.1.2}/robpy/regression/lts.py +0 -0
- {robpy-0.0.6 → robpy-0.1.2}/robpy/regression/mm.py +0 -0
- {robpy-0.0.6 → robpy-0.1.2}/robpy/regression/s.py +0 -0
- {robpy-0.0.6 → robpy-0.1.2}/robpy/univariate/__init__.py +0 -0
- {robpy-0.0.6 → robpy-0.1.2}/robpy/univariate/adjusted_boxplot.py +0 -0
- {robpy-0.0.6 → robpy-0.1.2}/robpy/univariate/base.py +0 -0
- {robpy-0.0.6 → robpy-0.1.2}/robpy/univariate/mcd.py +0 -0
- {robpy-0.0.6 → robpy-0.1.2}/robpy/univariate/onestep_m.py +0 -0
- {robpy-0.0.6 → robpy-0.1.2}/robpy/univariate/qn.py +0 -0
- {robpy-0.0.6 → robpy-0.1.2}/robpy/univariate/tau.py +0 -0
- {robpy-0.0.6 → robpy-0.1.2}/robpy/utils/distance.py +0 -0
- {robpy-0.0.6 → robpy-0.1.2}/robpy/utils/general.py +0 -0
- {robpy-0.0.6 → robpy-0.1.2}/robpy/utils/logging.py +0 -0
- {robpy-0.0.6 → robpy-0.1.2}/robpy/utils/median.py +0 -0
- {robpy-0.0.6 → robpy-0.1.2}/robpy/utils/outlyingness.py +0 -0
- {robpy-0.0.6 → robpy-0.1.2}/robpy/utils/rho.py +0 -0
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
Metadata-Version: 2.
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
2
|
Name: robpy
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.1.2
|
|
4
4
|
Summary:
|
|
5
|
+
License-File: LICENSE
|
|
5
6
|
Author: Thomas Servotte
|
|
6
7
|
Author-email: servottethomas@gmail.com
|
|
7
8
|
Requires-Python: >=3.10,<4.0
|
|
@@ -10,8 +11,10 @@ Classifier: Programming Language :: Python :: 3.10
|
|
|
10
11
|
Classifier: Programming Language :: Python :: 3.11
|
|
11
12
|
Classifier: Programming Language :: Python :: 3.12
|
|
12
13
|
Classifier: Programming Language :: Python :: 3.13
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.15
|
|
13
16
|
Requires-Dist: matplotlib (>=3.8.2,<4.0.0)
|
|
14
|
-
Requires-Dist: scikit-learn (>=1.3
|
|
17
|
+
Requires-Dist: scikit-learn (>=1.3)
|
|
15
18
|
Requires-Dist: scipy (>=1.11.4,<2.0.0)
|
|
16
19
|
Requires-Dist: seaborn (>=0.13.2,<0.14.0)
|
|
17
20
|
Requires-Dist: statsmodels (>=0.14.1,<0.15.0)
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[tool.poetry]
|
|
2
2
|
name = "robpy"
|
|
3
|
-
version = "0.
|
|
3
|
+
version = "0.1.2" # 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"
|
|
41
41
|
matplotlib = "^3.8.2"
|
|
42
42
|
scipy = "^1.11.4"
|
|
43
43
|
tqdm = "^4.66.1"
|
|
@@ -9,6 +9,23 @@ from sklearn.covariance import EmpiricalCovariance
|
|
|
9
9
|
from sklearn.exceptions import NotFittedError
|
|
10
10
|
from robpy.utils.distance import mahalanobis_distance
|
|
11
11
|
|
|
12
|
+
try:
|
|
13
|
+
from sklearn.utils.validation import validate_data
|
|
14
|
+
|
|
15
|
+
_HAS_PUBLIC_VALIDATE_DATA = True
|
|
16
|
+
except ImportError:
|
|
17
|
+
_HAS_PUBLIC_VALIDATE_DATA = False
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _safe_validate_data(estimator, X, **kwargs):
|
|
21
|
+
"""Version-safe data validation wrapper."""
|
|
22
|
+
if _HAS_PUBLIC_VALIDATE_DATA:
|
|
23
|
+
return validate_data(estimator, X, **kwargs)
|
|
24
|
+
else:
|
|
25
|
+
if "ensure_all_finite" in kwargs:
|
|
26
|
+
kwargs["force_all_finite"] = kwargs.pop("ensure_all_finite")
|
|
27
|
+
return estimator._validate_data(X, **kwargs)
|
|
28
|
+
|
|
12
29
|
|
|
13
30
|
class RobustCovariance(EmpiricalCovariance):
|
|
14
31
|
def __init__(
|
|
@@ -49,7 +66,13 @@ class RobustCovariance(EmpiricalCovariance):
|
|
|
49
66
|
if self.nans_allowed:
|
|
50
67
|
self.n_features_in_ = X.shape[1]
|
|
51
68
|
else:
|
|
52
|
-
X =
|
|
69
|
+
X = _safe_validate_data(
|
|
70
|
+
self,
|
|
71
|
+
X,
|
|
72
|
+
reset=True,
|
|
73
|
+
ensure_2d=True,
|
|
74
|
+
ensure_all_finite=not self.nans_allowed,
|
|
75
|
+
)
|
|
53
76
|
|
|
54
77
|
if self.assume_centered:
|
|
55
78
|
self.location_ = np.zeros(X.shape[1])
|
|
@@ -1,5 +1,8 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
1
3
|
import logging
|
|
2
4
|
import numpy as np
|
|
5
|
+
import pandas as pd
|
|
3
6
|
import matplotlib.pyplot as plt
|
|
4
7
|
|
|
5
8
|
from scipy.stats import chi2, median_abs_deviation
|
|
@@ -56,6 +59,20 @@ class CellMCD(RobustCovariance):
|
|
|
56
59
|
on the standardized data. Should be at least 1e-6.
|
|
57
60
|
Defaults to 1e-4.
|
|
58
61
|
|
|
62
|
+
Attributes (after fit):
|
|
63
|
+
location_ (np.ndarray): Robust location estimate.
|
|
64
|
+
covariance_ (np.ndarray): Robust covariance estimate.
|
|
65
|
+
cellwise_outliers_ (np.ndarray): Boolean array of shape (n_samples, n_features), True
|
|
66
|
+
for a cell of the training data that is flagged as outlying. Missing cells are
|
|
67
|
+
False.
|
|
68
|
+
W (np.ndarray): Weight matrix of the training data, 1 for a kept cell and 0 for a
|
|
69
|
+
flagged or missing cell (so W == 0 also includes the missing cells).
|
|
70
|
+
predictions, conditional_stds, residuals, X_imputed (np.ndarray): Per-cell
|
|
71
|
+
predictions given the unflagged cells of the same row, their conditional standard
|
|
72
|
+
deviations, the standardized residuals and the imputed training data.
|
|
73
|
+
|
|
74
|
+
Use `predict` and `impute` to flag and impute cells of new data.
|
|
75
|
+
|
|
59
76
|
References:
|
|
60
77
|
- Raymaekers, J., & Rousseeuw, P. J. (2024). The cellwise minimum covariance determinant
|
|
61
78
|
estimator. Journal of the American Statistical Association, 119(548), 2610-2621.
|
|
@@ -103,10 +120,13 @@ class CellMCD(RobustCovariance):
|
|
|
103
120
|
initial_cov = ddcw.covariance_
|
|
104
121
|
initial_cov_inv = ddcw.precision_
|
|
105
122
|
X_scaled[np.abs(X_scaled) > 3] = np.nan
|
|
123
|
+
q = (
|
|
124
|
+
chi2.ppf(self.quantile, 1) - np.log(np.diag(initial_cov_inv)) + np.log(2 * np.pi)
|
|
125
|
+
) # equation (21)
|
|
106
126
|
|
|
107
127
|
# Step 3: MCD iterations (we work with X_scaled)
|
|
108
128
|
location, cov, cov_inv, W = self._C_steps_until_convergence(
|
|
109
|
-
X_scaled, initial_location, initial_cov, initial_cov_inv
|
|
129
|
+
X_scaled, initial_location, initial_cov, initial_cov_inv, q
|
|
110
130
|
)
|
|
111
131
|
# Step 4: make prediction
|
|
112
132
|
predictions, conditional_variances = self._make_predictions(
|
|
@@ -114,6 +134,7 @@ class CellMCD(RobustCovariance):
|
|
|
114
134
|
)
|
|
115
135
|
|
|
116
136
|
# Step 5: transform back
|
|
137
|
+
location_scaled, cov_scaled = location, cov
|
|
117
138
|
cov = np.diag(scaler.scales_) @ cov @ np.diag(scaler.scales_)
|
|
118
139
|
location = scaler.locations_ + location * scaler.scales_
|
|
119
140
|
predictions = scaler.locations_ + predictions * scaler.scales_
|
|
@@ -125,7 +146,16 @@ class CellMCD(RobustCovariance):
|
|
|
125
146
|
scaler_residuals.fit(residuals, ignore_nan=True)
|
|
126
147
|
residuals = residuals / scaler_residuals.scales_
|
|
127
148
|
|
|
149
|
+
# state needed to flag and impute new data (all in the robustly scaled space)
|
|
150
|
+
self._scaler = scaler
|
|
151
|
+
self._location_scaled = location_scaled
|
|
152
|
+
self._covariance_scaled = cov_scaled
|
|
153
|
+
self._precision_scaled = cov_inv
|
|
154
|
+
self._q = q
|
|
155
|
+
self._column_order = np.argsort(np.sum(W, axis=0), kind="stable")
|
|
156
|
+
|
|
128
157
|
self.W = W
|
|
158
|
+
self.cellwise_outliers_ = (W == 0) & ~np.isnan(X)
|
|
129
159
|
self.location_ = location
|
|
130
160
|
self.predictions = predictions
|
|
131
161
|
self.conditional_stds = conditional_stds
|
|
@@ -136,6 +166,118 @@ class CellMCD(RobustCovariance):
|
|
|
136
166
|
|
|
137
167
|
return cov
|
|
138
168
|
|
|
169
|
+
def predict(self, X: np.ndarray | pd.DataFrame) -> np.ndarray:
|
|
170
|
+
"""Flag the cellwise outliers in (new) data using the fitted location and covariance.
|
|
171
|
+
|
|
172
|
+
For each row, the flag pattern is found by minimizing that row's contribution to the
|
|
173
|
+
cellMCD objective while keeping the fitted location and covariance fixed. This is the
|
|
174
|
+
W-update of the C-step (without re-estimating location and covariance and without the
|
|
175
|
+
per-column constraint of at least h unflagged cells), iterated until no flag changes.
|
|
176
|
+
As during fitting, cells that lie more than 3 robust scales from the robust location
|
|
177
|
+
are always flagged, and the iterations start with all other observed cells unflagged.
|
|
178
|
+
This is the out-of-sample step of section 3.2 of Raymaekers and Rousseeuw (2026), except
|
|
179
|
+
that it starts from the same flags as fit does here instead of from the marginal rule;
|
|
180
|
+
on simulated data this reached a lower objective and reproduced the training flags more
|
|
181
|
+
closely. Each row is treated independently of the other rows. Applied to the training
|
|
182
|
+
data, the result agrees with `cellwise_outliers_` for almost all cells but not
|
|
183
|
+
necessarily all: during fitting, the per-column constraint of at least h unflagged
|
|
184
|
+
cells applies and the flags evolve together with location and covariance.
|
|
185
|
+
|
|
186
|
+
Args:
|
|
187
|
+
X (np.ndarray | pd.DataFrame): Data of shape (n_samples, n_features), with the same
|
|
188
|
+
features as the data used in fit. May contain missing values (nan).
|
|
189
|
+
|
|
190
|
+
Returns:
|
|
191
|
+
np.ndarray: Boolean array of shape (n_samples, n_features), True for a flagged cell.
|
|
192
|
+
Missing cells are not flagged (False), as in `cellwise_outliers_`.
|
|
193
|
+
|
|
194
|
+
References:
|
|
195
|
+
- Raymaekers, J., & Rousseeuw, P. J. (2026). Least trimmed squares regression with
|
|
196
|
+
missing values and cellwise outliers. arXiv:2603.04632.
|
|
197
|
+
"""
|
|
198
|
+
X = self._check_new_data(X)
|
|
199
|
+
W = self._flag_cells(self._scaler.transform(X))
|
|
200
|
+
return (W == 0) & ~np.isnan(X)
|
|
201
|
+
|
|
202
|
+
def impute(self, X: np.ndarray | pd.DataFrame) -> np.ndarray | pd.DataFrame:
|
|
203
|
+
"""Impute the flagged and the missing cells of (new) data.
|
|
204
|
+
|
|
205
|
+
Cells are flagged as in `predict`. Flagged and missing cells are replaced by their
|
|
206
|
+
conditional expectation given the unflagged cells of the same row, under the fitted
|
|
207
|
+
location and covariance. All other cells are returned unchanged.
|
|
208
|
+
|
|
209
|
+
Args:
|
|
210
|
+
X (np.ndarray | pd.DataFrame): Data of shape (n_samples, n_features), with the same
|
|
211
|
+
features as the data used in fit. May contain missing values (nan).
|
|
212
|
+
|
|
213
|
+
Returns:
|
|
214
|
+
np.ndarray | pd.DataFrame: The imputed data, of the same type as X.
|
|
215
|
+
"""
|
|
216
|
+
X_input = X
|
|
217
|
+
X = self._check_new_data(X)
|
|
218
|
+
X_scaled = self._scaler.transform(X)
|
|
219
|
+
W = self._flag_cells(X_scaled)
|
|
220
|
+
predictions, _ = self._make_predictions(
|
|
221
|
+
X_scaled, self._covariance_scaled, self._precision_scaled, self._location_scaled, W
|
|
222
|
+
)
|
|
223
|
+
predictions = self._scaler.locations_ + predictions * self._scaler.scales_
|
|
224
|
+
X_imputed = np.where(W == 0, predictions, X)
|
|
225
|
+
if isinstance(X_input, pd.DataFrame):
|
|
226
|
+
return pd.DataFrame(X_imputed, index=X_input.index, columns=X_input.columns)
|
|
227
|
+
return X_imputed
|
|
228
|
+
|
|
229
|
+
def _check_new_data(self, X: np.ndarray | pd.DataFrame) -> np.ndarray:
|
|
230
|
+
"""Validate data passed to predict or impute and return it as a float array in which
|
|
231
|
+
infinite values are replaced by nan."""
|
|
232
|
+
if not hasattr(self, "_scaler"):
|
|
233
|
+
raise NotFittedError("This CellMCD instance is not fitted yet. Call fit first.")
|
|
234
|
+
X = np.array(X, dtype=float)
|
|
235
|
+
if X.ndim == 1:
|
|
236
|
+
X = X.reshape(1, -1)
|
|
237
|
+
if X.ndim != 2 or X.shape[1] != self.n_features_in_:
|
|
238
|
+
raise ValueError(
|
|
239
|
+
f"X has {X.shape[-1]} features, but CellMCD was fitted with "
|
|
240
|
+
f"{self.n_features_in_} features."
|
|
241
|
+
)
|
|
242
|
+
X[np.isinf(X)] = np.nan
|
|
243
|
+
return X
|
|
244
|
+
|
|
245
|
+
def _flag_cells(self, X_scaled: np.ndarray) -> np.ndarray:
|
|
246
|
+
"""Find the flag matrix W (1 = kept, 0 = flagged or missing) for robustly scaled data,
|
|
247
|
+
keeping the fitted location and covariance fixed.
|
|
248
|
+
|
|
249
|
+
Changing a single w_ij from 0 to 1 changes row i's contribution to the objective by
|
|
250
|
+
delta_ij - q_j (equation (20)), so setting w_ij = 1 if and only if delta_ij <= q_j never
|
|
251
|
+
increases the objective. Repeating this over all columns until no flag changes therefore
|
|
252
|
+
terminates, at a pattern where no single flag change lowers the objective."""
|
|
253
|
+
X_scaled = X_scaled.copy()
|
|
254
|
+
X_scaled[np.abs(X_scaled) > 3] = np.nan # as in fit: these cells are always flagged
|
|
255
|
+
mu, sigma, sigma_inv = (
|
|
256
|
+
self._location_scaled,
|
|
257
|
+
self._covariance_scaled,
|
|
258
|
+
self._precision_scaled,
|
|
259
|
+
)
|
|
260
|
+
|
|
261
|
+
# initialization as in fit: every observed cell (within 3 robust scales) is unflagged
|
|
262
|
+
W = np.where(np.isnan(X_scaled), 0.0, 1.0)
|
|
263
|
+
|
|
264
|
+
for _ in range(self.max_c_steps):
|
|
265
|
+
changed = False
|
|
266
|
+
for j in self._column_order:
|
|
267
|
+
delta = self._calculate_delta(X_scaled, W, sigma, sigma_inv, mu, j)
|
|
268
|
+
w_new = (delta <= self._q[j]).astype(float)
|
|
269
|
+
if np.any(w_new != W[:, j]):
|
|
270
|
+
changed = True
|
|
271
|
+
W[:, j] = w_new
|
|
272
|
+
if not changed:
|
|
273
|
+
break
|
|
274
|
+
else:
|
|
275
|
+
self.logger.warning(
|
|
276
|
+
f"Flagging cells did not converge within max_c_steps={self.max_c_steps} sweeps."
|
|
277
|
+
)
|
|
278
|
+
|
|
279
|
+
return W
|
|
280
|
+
|
|
139
281
|
def cell_MCD_plot(
|
|
140
282
|
self,
|
|
141
283
|
variable: int,
|
|
@@ -330,7 +472,7 @@ class CellMCD(RobustCovariance):
|
|
|
330
472
|
|
|
331
473
|
else: # all missings in the w-pattern
|
|
332
474
|
predictions, conditional_variances = self._predict_all_missing(
|
|
333
|
-
predictions, conditional_variances, row_idx_w, mu,
|
|
475
|
+
predictions, conditional_variances, row_idx_w, mu, sigma
|
|
334
476
|
)
|
|
335
477
|
|
|
336
478
|
return predictions, conditional_variances
|
|
@@ -341,6 +483,7 @@ class CellMCD(RobustCovariance):
|
|
|
341
483
|
initial_location: np.array,
|
|
342
484
|
initial_cov: np.ndarray,
|
|
343
485
|
initial_cov_inv: np.ndarray,
|
|
486
|
+
q: np.ndarray,
|
|
344
487
|
):
|
|
345
488
|
"""Perform C-steps (update W, location and covariance) until convergence.
|
|
346
489
|
|
|
@@ -349,6 +492,7 @@ class CellMCD(RobustCovariance):
|
|
|
349
492
|
- initial_location (np.array): initial location estimate
|
|
350
493
|
- initial_cov (np.ndarray): initial covariance estimate
|
|
351
494
|
- initial_cov_inv (np.ndarray): inverse of the initial covariance estimate
|
|
495
|
+
- q (np.ndarray): per-column penalties for flagging a cell, equation (21)
|
|
352
496
|
"""
|
|
353
497
|
n, p = X_scaled.shape
|
|
354
498
|
|
|
@@ -357,9 +501,6 @@ class CellMCD(RobustCovariance):
|
|
|
357
501
|
initial_W[np.isnan(X_scaled)] = 0
|
|
358
502
|
objective_values = np.full(self.max_c_steps + 1, np.nan)
|
|
359
503
|
step = 0
|
|
360
|
-
q = (
|
|
361
|
-
chi2.ppf(0.99, 1) - np.log(np.diag(initial_cov_inv)) + np.log(2 * np.pi)
|
|
362
|
-
) # equation (21)
|
|
363
504
|
penalty = np.sum(q * np.sum(1 - initial_W, axis=0))
|
|
364
505
|
objective_values[step] = (
|
|
365
506
|
objective_function(X_scaled, initial_W, initial_location, initial_cov, initial_cov_inv)
|
|
@@ -573,21 +714,17 @@ class CellMCD(RobustCovariance):
|
|
|
573
714
|
for obs in observed_col_idx:
|
|
574
715
|
other_observations = observed_col_idx[observed_col_idx != obs]
|
|
575
716
|
sigma_others_inv = inverse_submatrix(sigma, sigma_inv, other_observations)
|
|
717
|
+
regression_coefs = sigma_others_inv @ sigma[other_observations, obs]
|
|
576
718
|
conditional_variance_others = (
|
|
577
|
-
sigma[obs, obs]
|
|
578
|
-
- sigma[np.ix_([obs], other_observations)]
|
|
579
|
-
@ sigma_others_inv
|
|
580
|
-
@ sigma[np.ix_(other_observations, [obs])]
|
|
719
|
+
sigma[obs, obs] - sigma[obs, other_observations] @ regression_coefs
|
|
581
720
|
)
|
|
582
721
|
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
)
|
|
590
|
-
conditional_variances[index, obs] = conditional_variance_others
|
|
722
|
+
predictions[row_idx_w, obs] = (
|
|
723
|
+
mu[obs]
|
|
724
|
+
+ (X[np.ix_(row_idx_w, other_observations)] - mu[other_observations])
|
|
725
|
+
@ regression_coefs
|
|
726
|
+
)
|
|
727
|
+
conditional_variances[row_idx_w, obs] = conditional_variance_others
|
|
591
728
|
|
|
592
729
|
return predictions, conditional_variances
|
|
593
730
|
|
|
@@ -624,12 +761,13 @@ class CellMCD(RobustCovariance):
|
|
|
624
761
|
conditional_variances: np.ndarray,
|
|
625
762
|
row_idx_w: np.array,
|
|
626
763
|
mu: np.array,
|
|
627
|
-
|
|
764
|
+
sigma: np.ndarray,
|
|
628
765
|
):
|
|
629
|
-
"""Make predictions when all values in the w-pattern are missing
|
|
766
|
+
"""Make predictions when all values in the w-pattern are missing: with no unflagged
|
|
767
|
+
cells to condition on, these are the marginal means and variances."""
|
|
630
768
|
for index in row_idx_w:
|
|
631
769
|
predictions[index, :] = mu
|
|
632
|
-
conditional_variances[index, :] = np.diag(
|
|
770
|
+
conditional_variances[index, :] = np.diag(sigma)
|
|
633
771
|
|
|
634
772
|
return predictions, conditional_variances
|
|
635
773
|
|
|
@@ -144,6 +144,8 @@ class FastMCD(RobustCovariance):
|
|
|
144
144
|
self.logger.debug("Applying consistency correction to the raw covariance estimate")
|
|
145
145
|
scale = self._correct_covariance(X, best_subset)
|
|
146
146
|
if self.reweighting:
|
|
147
|
+
self.location_raw_ = self.location_
|
|
148
|
+
self.scale_raw_ = scale
|
|
147
149
|
self.logger.debug("Applying reweighting to the raw covariance estimate")
|
|
148
150
|
distances = mahalanobis_distance(X, best_subset.location, scale)
|
|
149
151
|
self._mask = distances < np.sqrt(chi2.ppf(0.975, X.shape[1]))
|
|
@@ -197,27 +199,31 @@ class FastMCD(RobustCovariance):
|
|
|
197
199
|
n, p = X.shape
|
|
198
200
|
if self.alpha is None:
|
|
199
201
|
return int((n + p + 1) / 2)
|
|
200
|
-
elif isinstance(self.alpha, int) and
|
|
202
|
+
elif isinstance(self.alpha, int) and 2 <= self.alpha <= n:
|
|
201
203
|
if self.alpha < int((n + p + 1) / 2):
|
|
202
204
|
warnings.warn(
|
|
203
|
-
f"h is too small and
|
|
205
|
+
f"h is too small and should be set to [(n+p+1)/2] ({int((n + p + 1) / 2)})"
|
|
206
|
+
f" or larger, unless you specifically want to emphasize a within-cluster "
|
|
207
|
+
f" covariance structure.",
|
|
204
208
|
category=UserWarning,
|
|
205
209
|
stacklevel=2,
|
|
206
210
|
)
|
|
207
|
-
return
|
|
208
|
-
elif (isinstance(self.alpha, float) and (0
|
|
211
|
+
return self.alpha
|
|
212
|
+
elif (isinstance(self.alpha, float) and (0 <= self.alpha <= 1)) or self.alpha == 1:
|
|
209
213
|
if int(self.alpha * n) < int((n + p + 1) / 2):
|
|
210
214
|
warnings.warn(
|
|
211
|
-
f"h = alpha*n is too small and
|
|
212
|
-
f" ({int((n + p + 1) / 2)})
|
|
215
|
+
f"h = alpha*n is too small and should be set to [(n+p+1)/2]"
|
|
216
|
+
f" ({int((n + p + 1) / 2)}) or larger, unless you specifically want to"
|
|
217
|
+
f" emphasize a within-cluster covariance structure.",
|
|
213
218
|
category=UserWarning,
|
|
214
219
|
stacklevel=2,
|
|
215
220
|
)
|
|
216
|
-
return
|
|
221
|
+
return int(self.alpha * n)
|
|
217
222
|
else:
|
|
218
223
|
raise ValueError(
|
|
219
224
|
f"alpha must be an integer between n/2 and n or"
|
|
220
|
-
f" a float between 0.5 and 1, but received {self.alpha}
|
|
225
|
+
f" a float between 0.5 and 1, but received {self.alpha}"
|
|
226
|
+
f" (or smaller for a within-cluster covariance structure)."
|
|
221
227
|
)
|
|
222
228
|
|
|
223
229
|
def _partition_data(self, X: np.ndarray) -> list[np.ndarray]:
|
|
@@ -355,6 +361,8 @@ class DetMCD(RobustCovariance):
|
|
|
355
361
|
self.logger.debug("Applying consistency correction to the raw covariance estimate")
|
|
356
362
|
scale = self._correct_covariance(X, best_subset)
|
|
357
363
|
if self.reweighting:
|
|
364
|
+
self.location_raw_ = self.location_
|
|
365
|
+
self.scale_raw_ = scale
|
|
358
366
|
self.logger.debug("Applying reweighting to the raw covariance estimate")
|
|
359
367
|
distances = mahalanobis_distance(X, best_subset.location, scale)
|
|
360
368
|
self._mask = distances < np.sqrt(chi2.ppf(0.975, X.shape[1]))
|
|
@@ -439,27 +447,31 @@ class DetMCD(RobustCovariance):
|
|
|
439
447
|
n, p = X.shape
|
|
440
448
|
if self.alpha is None:
|
|
441
449
|
return int((n + p + 1) / 2)
|
|
442
|
-
elif isinstance(self.alpha, int) and
|
|
450
|
+
elif isinstance(self.alpha, int) and 2 <= self.alpha <= n:
|
|
443
451
|
if self.alpha < int((n + p + 1) / 2):
|
|
444
452
|
warnings.warn(
|
|
445
|
-
f"h is too small and
|
|
453
|
+
f"h is too small and should be set to [(n+p+1)/2] ({int((n + p + 1) / 2)})"
|
|
454
|
+
f" or larger, unless you specifically want to emphasize a within-cluster "
|
|
455
|
+
f" covariance structure.",
|
|
446
456
|
category=UserWarning,
|
|
447
457
|
stacklevel=2,
|
|
448
458
|
)
|
|
449
|
-
return
|
|
450
|
-
elif (isinstance(self.alpha, float) and (0
|
|
459
|
+
return self.alpha
|
|
460
|
+
elif (isinstance(self.alpha, float) and (0 <= self.alpha <= 1)) or self.alpha == 1:
|
|
451
461
|
if int(self.alpha * n) < int((n + p + 1) / 2):
|
|
452
462
|
warnings.warn(
|
|
453
|
-
f"h = alpha*n is too small and
|
|
454
|
-
f" ({int((n + p + 1) / 2)})
|
|
463
|
+
f"h = alpha*n is too small and should be set to [(n+p+1)/2]"
|
|
464
|
+
f" ({int((n + p + 1) / 2)}) or larger, unless you specifically want to"
|
|
465
|
+
f" emphasize a within-cluster covariance structure.",
|
|
455
466
|
category=UserWarning,
|
|
456
467
|
stacklevel=2,
|
|
457
468
|
)
|
|
458
|
-
return
|
|
469
|
+
return int(self.alpha * n)
|
|
459
470
|
else:
|
|
460
471
|
raise ValueError(
|
|
461
472
|
f"alpha must be an integer between n/2 and n or"
|
|
462
|
-
f" a float between 0.5 and 1, but received {self.alpha}
|
|
473
|
+
f" a float between 0.5 and 1, but received {self.alpha}"
|
|
474
|
+
f" (or smaller for a within-cluster covariance structure)."
|
|
463
475
|
)
|
|
464
476
|
|
|
465
477
|
def _get_subset(
|