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.
- robpy/__init__.py +0 -0
- robpy/covariance/__init__.py +6 -0
- robpy/covariance/base.py +82 -0
- robpy/covariance/cellmcd.py +621 -0
- robpy/covariance/initial_ddcw.py +133 -0
- robpy/covariance/kendall.py +21 -0
- robpy/covariance/mcd.py +470 -0
- robpy/covariance/ogk.py +95 -0
- robpy/covariance/utils/alter_covariance.py +31 -0
- robpy/covariance/utils/cellmcd_utils.py +38 -0
- robpy/covariance/utils/cellmcd_visualization_utils.py +96 -0
- robpy/covariance/wrapping.py +72 -0
- robpy/datasets/__init__.py +4 -0
- robpy/datasets/base.py +389 -0
- robpy/datasets/data/animals.csv +66 -0
- robpy/datasets/data/glass.csv +181 -0
- robpy/datasets/data/stars.csv +48 -0
- robpy/datasets/data/telephone.csv +25 -0
- robpy/datasets/data/topgear.csv +298 -0
- robpy/datasets/descr/animals.rst +26 -0
- robpy/datasets/descr/glass.rst +20 -0
- robpy/datasets/descr/stars.rst +28 -0
- robpy/datasets/descr/telephone.rst +23 -0
- robpy/datasets/descr/topgear.rst +51 -0
- robpy/outliers/__init__.py +4 -0
- robpy/outliers/ddc.py +296 -0
- robpy/pca/__init__.py +3 -0
- robpy/pca/base.py +97 -0
- robpy/pca/robpca.py +89 -0
- robpy/pca/spca.py +48 -0
- robpy/preprocessing/__init__.py +3 -0
- robpy/preprocessing/data_cleaner.py +214 -0
- robpy/preprocessing/scaling.py +57 -0
- robpy/preprocessing/transfo.py +591 -0
- robpy/preprocessing/utils.py +63 -0
- robpy/regression/__init__.py +3 -0
- robpy/regression/base.py +116 -0
- robpy/regression/lts.py +408 -0
- robpy/regression/mm_estimator.py +57 -0
- robpy/regression/s_estimator.py +188 -0
- robpy/univariate/__init__.py +9 -0
- robpy/univariate/base.py +53 -0
- robpy/univariate/mcd.py +84 -0
- robpy/univariate/onestep_m.py +143 -0
- robpy/univariate/qn.py +112 -0
- robpy/univariate/tau.py +63 -0
- robpy/utils/distance.py +24 -0
- robpy/utils/general.py +31 -0
- robpy/utils/logging.py +22 -0
- robpy/utils/median.py +62 -0
- robpy/utils/outlyingness.py +61 -0
- robpy/utils/rho.py +35 -0
- robpy-0.1.0.dist-info/METADATA +31 -0
- robpy-0.1.0.dist-info/RECORD +55 -0
- robpy-0.1.0.dist-info/WHEEL +4 -0
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
import pandas as pd
|
|
3
|
+
|
|
4
|
+
from robpy.covariance.base import RobustCovarianceEstimator
|
|
5
|
+
from robpy.utils.distance import mahalanobis_distance
|
|
6
|
+
from robpy.covariance.utils.alter_covariance import truncated_covariance, covariance_to_correlation
|
|
7
|
+
from robpy.preprocessing.scaling import RobustScaler
|
|
8
|
+
from robpy.univariate.onestep_m import OneStepWrappingEstimator
|
|
9
|
+
from robpy.outliers.ddc import DDCEstimator
|
|
10
|
+
from robpy.preprocessing.utils import wrapping_transformation
|
|
11
|
+
from scipy.stats import chi2
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class InitialDDCWEstimator(RobustCovarianceEstimator):
|
|
15
|
+
def __init__(
|
|
16
|
+
self,
|
|
17
|
+
*,
|
|
18
|
+
alpha: float = 0.75,
|
|
19
|
+
min_eigenvalue: float = 1e-4,
|
|
20
|
+
):
|
|
21
|
+
"""
|
|
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
|
|
26
|
+
|
|
27
|
+
Parameters:
|
|
28
|
+
alpha (float, optional):
|
|
29
|
+
Percentage indicating how much cells must remain unflagged in each column.
|
|
30
|
+
Defaults to 0.75.
|
|
31
|
+
min_eigenvalue (float, optional):
|
|
32
|
+
Lower bound on the minimum eigenvalue of the covariance estimator
|
|
33
|
+
on the standardized data. Should be at least 1e-6.
|
|
34
|
+
Defaults to 1e-4.
|
|
35
|
+
|
|
36
|
+
References:
|
|
37
|
+
- Raymaekers and Rousseeuw, The Cellwise Minimum Covariance Determinant Estimator, 2023,
|
|
38
|
+
Journal of the American Statistical Association.
|
|
39
|
+
"""
|
|
40
|
+
super().__init__(store_precision=True, assume_centered=False, nans_allowed=True)
|
|
41
|
+
self.alpha = alpha
|
|
42
|
+
self.min_eigenvalue = min_eigenvalue
|
|
43
|
+
|
|
44
|
+
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
|
+
n, p = X.shape
|
|
54
|
+
|
|
55
|
+
# DDC with constraint -> imputed and rescaled Zimp:
|
|
56
|
+
DDC = DDCEstimator(chi2_quantile=0.9, scale_estimator=OneStepWrappingEstimator()).fit(
|
|
57
|
+
pd.DataFrame(X)
|
|
58
|
+
)
|
|
59
|
+
W = np.copy(DDC.cellwise_outliers_)
|
|
60
|
+
flagged_too_many = np.where(np.sum(W, axis=0) / X.shape[0] > 1 - self.alpha)[0]
|
|
61
|
+
for i in flagged_too_many:
|
|
62
|
+
ordering = np.argsort(np.abs(DDC.standardized_residuals_[:, i]))[::-1]
|
|
63
|
+
W[:, i] = [False for _ in range(n)]
|
|
64
|
+
W[ordering[0 : int(n * 0.25)], i] = True
|
|
65
|
+
Zimp = np.copy(X)
|
|
66
|
+
Zimp[np.logical_or(W, np.isnan(X))] = DDC.impute(
|
|
67
|
+
pd.DataFrame(X), impute_outliers=True
|
|
68
|
+
).to_numpy()[np.logical_or(W, np.isnan(X))]
|
|
69
|
+
Z = (X - DDC.location_) / DDC.scale_
|
|
70
|
+
Zimp = (Zimp - DDC.location_) / DDC.scale_
|
|
71
|
+
Zimp_original = np.copy(Zimp)
|
|
72
|
+
Zimp = np.delete(Zimp, np.where(DDC.row_outliers_)[0], axis=0)
|
|
73
|
+
|
|
74
|
+
# project data on eigenvectors
|
|
75
|
+
eigvals, eigvecs = np.linalg.eigh(np.cov(Zimp, rowvar=False))
|
|
76
|
+
eigenvectors = eigvecs[:, np.where(eigvals > self.min_eigenvalue)[0][::-1]]
|
|
77
|
+
Zimp_proj = Zimp @ eigenvectors
|
|
78
|
+
|
|
79
|
+
# wrapped location and covariance
|
|
80
|
+
Zimp_proj_scaler = RobustScaler(scale_estimator=OneStepWrappingEstimator()).fit(
|
|
81
|
+
Zimp_proj, ignore_nan=True
|
|
82
|
+
)
|
|
83
|
+
Zimp_proj_scaler.scales_[
|
|
84
|
+
Zimp_proj_scaler.scales_ < self.min_eigenvalue
|
|
85
|
+
] = self.min_eigenvalue
|
|
86
|
+
Zimp_proj_wrapped_cov = np.cov(
|
|
87
|
+
wrapping_transformation(
|
|
88
|
+
Zimp_proj,
|
|
89
|
+
location_estimator=lambda *args, **kwargs: Zimp_proj_scaler.locations_,
|
|
90
|
+
scale_estimator=lambda *args, **kwargs: Zimp_proj_scaler.scales_,
|
|
91
|
+
rescale=True,
|
|
92
|
+
),
|
|
93
|
+
rowvar=False,
|
|
94
|
+
)
|
|
95
|
+
cov = eigenvectors @ Zimp_proj_wrapped_cov @ eigenvectors.T # back to original axis system
|
|
96
|
+
cov = covariance_to_correlation(cov)
|
|
97
|
+
cov = (truncated_covariance(cov, self.min_eigenvalue) * DDC.scale_).T * DDC.scale_
|
|
98
|
+
|
|
99
|
+
# temporary points: delete casewise outliers
|
|
100
|
+
U = np.minimum(np.maximum(Z, -2), 2)
|
|
101
|
+
RD = mahalanobis_distance(U, np.zeros(p), cov) ** 2
|
|
102
|
+
U_outlying_cases = np.where(RD / np.median(RD) * chi2.ppf(0.5, p) > chi2.ppf(0.99, p))[0]
|
|
103
|
+
Z = np.delete(Z, U_outlying_cases, axis=0)
|
|
104
|
+
Zimp = np.delete(Zimp_original, U_outlying_cases, axis=0)
|
|
105
|
+
|
|
106
|
+
# project data on eigenvectors
|
|
107
|
+
eigvals, eigvecs = np.linalg.eigh(np.cov(Zimp, rowvar=False))
|
|
108
|
+
eigenvectors = eigvecs[:, np.where(eigvals > self.min_eigenvalue)[0][::-1]]
|
|
109
|
+
Zimp_proj = Zimp @ eigenvectors
|
|
110
|
+
|
|
111
|
+
# wrapped location and covariance
|
|
112
|
+
Zimp_proj_scaler = RobustScaler(scale_estimator=OneStepWrappingEstimator()).fit(
|
|
113
|
+
Zimp_proj, ignore_nan=True
|
|
114
|
+
)
|
|
115
|
+
Zimp_proj_scaler.scales_[
|
|
116
|
+
Zimp_proj_scaler.scales_ < self.min_eigenvalue
|
|
117
|
+
] = self.min_eigenvalue
|
|
118
|
+
Zimp_proj_wrapped_cov = np.cov(
|
|
119
|
+
wrapping_transformation(
|
|
120
|
+
Zimp_proj,
|
|
121
|
+
location_estimator=lambda *args, **kwargs: Zimp_proj_scaler.locations_,
|
|
122
|
+
scale_estimator=lambda *args, **kwargs: Zimp_proj_scaler.scales_,
|
|
123
|
+
rescale=True,
|
|
124
|
+
),
|
|
125
|
+
rowvar=False,
|
|
126
|
+
)
|
|
127
|
+
cov = eigenvectors @ Zimp_proj_wrapped_cov @ eigenvectors.T # back to original axis system
|
|
128
|
+
cov = covariance_to_correlation(cov)
|
|
129
|
+
cov = (truncated_covariance(cov, self.min_eigenvalue) * DDC.scale_).T * DDC.scale_
|
|
130
|
+
|
|
131
|
+
self.location_ = np.array(DDC.location_)
|
|
132
|
+
|
|
133
|
+
return cov
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
from scipy.stats import kendalltau
|
|
3
|
+
from robpy.covariance.base import RobustCovarianceEstimator
|
|
4
|
+
from robpy.univariate import QnEstimator
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class KendallTauEstimator(RobustCovarianceEstimator):
|
|
8
|
+
"""Estimate the covariance matrix using Kendall's tau correlation."""
|
|
9
|
+
|
|
10
|
+
def calculate_covariance(self, X) -> np.ndarray:
|
|
11
|
+
p = X.shape[1]
|
|
12
|
+
scales = [QnEstimator().fit(col).scale for col in X.T]
|
|
13
|
+
cor = np.ones(shape=(p, p))
|
|
14
|
+
cov = np.ones(shape=(p, p))
|
|
15
|
+
for i in range(p):
|
|
16
|
+
for j in range(i):
|
|
17
|
+
cor[i, j] = cor[j, i] = kendalltau(X[:, i], X[:, j]).statistic
|
|
18
|
+
cov[i, j] = cov[j, i] = cor[i, j] * scales[i] * scales[j]
|
|
19
|
+
cov[i, i] = scales[i] ** 2
|
|
20
|
+
self.correlation_ = cor
|
|
21
|
+
return cov
|
robpy/covariance/mcd.py
ADDED
|
@@ -0,0 +1,470 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
import numpy as np
|
|
3
|
+
import math as math
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from scipy.linalg import sqrtm
|
|
7
|
+
from scipy.stats import chi2, gamma, rankdata, norm
|
|
8
|
+
|
|
9
|
+
from robpy.covariance.base import RobustCovarianceEstimator
|
|
10
|
+
from robpy.utils.distance import mahalanobis_distance
|
|
11
|
+
from robpy.utils.logging import get_logger
|
|
12
|
+
from robpy.univariate.qn import QnEstimator
|
|
13
|
+
from robpy.covariance.ogk import OGKEstimator
|
|
14
|
+
from robpy.univariate.tau import TauEstimator
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass
|
|
18
|
+
class HSubset:
|
|
19
|
+
indices: np.ndarray
|
|
20
|
+
location: np.ndarray
|
|
21
|
+
scale: np.ndarray
|
|
22
|
+
determinant: float
|
|
23
|
+
n_c_steps: int = 0
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class FastMCDEstimator(RobustCovarianceEstimator):
|
|
27
|
+
def __init__(
|
|
28
|
+
self,
|
|
29
|
+
*,
|
|
30
|
+
h_size: float | int | None = None,
|
|
31
|
+
n_initial_subsets: int = 500,
|
|
32
|
+
n_initial_c_steps: int = 2,
|
|
33
|
+
n_best_subsets: int = 10,
|
|
34
|
+
n_partitions: int | None = None,
|
|
35
|
+
tolerance: float = 1e-8,
|
|
36
|
+
correct_covariance: bool = True,
|
|
37
|
+
reweighting: bool = True,
|
|
38
|
+
verbosity: int = logging.WARNING,
|
|
39
|
+
store_precision=True,
|
|
40
|
+
assume_centered=False,
|
|
41
|
+
):
|
|
42
|
+
"""
|
|
43
|
+
Fast MCD estimator based on the algorithm proposed in Rousseeuw and Van Driessen (1999)
|
|
44
|
+
|
|
45
|
+
Args:
|
|
46
|
+
h_size (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.
|
|
52
|
+
Defaults to None.
|
|
53
|
+
n_initial_subsets (int, optional):
|
|
54
|
+
number of initial random subsets of size p+1
|
|
55
|
+
n_initial_c_steps (int, optional):
|
|
56
|
+
number of initial c steps to perform on all initial subsets
|
|
57
|
+
n_best_subsets (int, optional):
|
|
58
|
+
number of best subsets to keep and perform c steps on until convergence
|
|
59
|
+
n_partitions (int, optional):
|
|
60
|
+
Number of partitions to split the data into.
|
|
61
|
+
This can speed up the algorithm for large datasets (n > 600 suggested in paper)
|
|
62
|
+
If None, 5 partitions are used if n > 600, otherwise 1 partition is used.
|
|
63
|
+
tolerance (float, optional):
|
|
64
|
+
Minimum difference in determinant between two iterations to stop the C-step
|
|
65
|
+
correct_covariance (bool, optional):
|
|
66
|
+
Whether to apply a consistency correction to the raw covariance estimate
|
|
67
|
+
reweighting (bool, optional):
|
|
68
|
+
Whether to apply reweighting to the raw covariance estimate
|
|
69
|
+
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
|
|
73
|
+
|
|
74
|
+
"""
|
|
75
|
+
super().__init__(store_precision=store_precision, assume_centered=assume_centered)
|
|
76
|
+
self.h_size = h_size
|
|
77
|
+
self.n_initial_subsets = n_initial_subsets
|
|
78
|
+
self.n_initial_c_steps = n_initial_c_steps
|
|
79
|
+
self.n_best_subsets = n_best_subsets
|
|
80
|
+
self.n_partitions = n_partitions
|
|
81
|
+
self.tolerance = tolerance
|
|
82
|
+
self.correct_covariance = correct_covariance
|
|
83
|
+
self.reweighting = reweighting
|
|
84
|
+
self.logger = get_logger("FastMCDEstimator", level=verbosity)
|
|
85
|
+
self.verbosity = verbosity
|
|
86
|
+
|
|
87
|
+
def calculate_covariance(self, X) -> np.ndarray:
|
|
88
|
+
if self.h_size == 1 or self.h_size == X.shape[0]:
|
|
89
|
+
self.logger.warning(f"Default covariance is returned as h_size is {self.h_size}.")
|
|
90
|
+
self.location_ = X.mean(0)
|
|
91
|
+
return np.cov(X, rowvar=False)
|
|
92
|
+
# partition data (n_partitions > 1 can speed up algorithm for large datasets)
|
|
93
|
+
partitions = self._partition_data(X)
|
|
94
|
+
self.logger.info(f"Partitioned data into {len(partitions)} partitions")
|
|
95
|
+
n_initial_subsets = self.n_initial_subsets // len(partitions)
|
|
96
|
+
best_subsets = []
|
|
97
|
+
# perform initial c steps on all initial subsets
|
|
98
|
+
for data in partitions:
|
|
99
|
+
subsets = self._get_initial_subsets(data, n_initial_subsets)
|
|
100
|
+
subsets = [
|
|
101
|
+
self._perform_multiple_c_steps(subset, data, n_iterations=self.n_initial_c_steps)
|
|
102
|
+
for subset in subsets
|
|
103
|
+
]
|
|
104
|
+
best_subsets.extend(sorted(subsets, key=lambda x: x.determinant)[: self.n_best_subsets])
|
|
105
|
+
self.logger.info(f"Selecting {self.n_best_subsets} best subsets from {len(best_subsets)}")
|
|
106
|
+
# perform additional c-steps on the best subsets
|
|
107
|
+
best_subsets = [
|
|
108
|
+
self._perform_multiple_c_steps(subset, X, n_iterations=self.n_initial_c_steps)
|
|
109
|
+
for subset in best_subsets
|
|
110
|
+
]
|
|
111
|
+
best_subsets = sorted(best_subsets, key=lambda x: x.determinant)[: self.n_best_subsets]
|
|
112
|
+
best_subset = best_subsets[0] # reference subset
|
|
113
|
+
# perform c-steps until convergence
|
|
114
|
+
for subset in best_subsets:
|
|
115
|
+
while True:
|
|
116
|
+
new_subset = self._perform_c_step(subset, X)
|
|
117
|
+
if (
|
|
118
|
+
np.all(new_subset.indices == subset.indices)
|
|
119
|
+
or (new_subset.determinant - subset.determinant) < self.tolerance
|
|
120
|
+
):
|
|
121
|
+
break
|
|
122
|
+
subset = new_subset
|
|
123
|
+
if subset.determinant < best_subset.determinant:
|
|
124
|
+
best_subset = subset
|
|
125
|
+
self.best_subset = best_subset
|
|
126
|
+
|
|
127
|
+
# post processing
|
|
128
|
+
self.location_ = best_subset.location
|
|
129
|
+
scale = best_subset.scale
|
|
130
|
+
if self.correct_covariance:
|
|
131
|
+
self.logger.debug("Applying consistency correction to the raw covariance estimate")
|
|
132
|
+
scale = self._correct_covariance(X, best_subset)
|
|
133
|
+
if self.reweighting:
|
|
134
|
+
self.logger.debug("Applying reweighting to the raw covariance estimate")
|
|
135
|
+
distances = mahalanobis_distance(X, best_subset.location, scale)
|
|
136
|
+
self._mask = distances < np.sqrt(chi2.ppf(0.975, X.shape[1]))
|
|
137
|
+
self.location_ = X[self._mask].mean(axis=0)
|
|
138
|
+
scale = np.cov(X[self._mask], rowvar=False)
|
|
139
|
+
if self.correct_covariance:
|
|
140
|
+
# See Croux & Haesbroeck 1999 and R code for robustbase>covMcd>MCDCons
|
|
141
|
+
# (https://rdrr.io/cran/robustbase/src/R/covMcd.R)
|
|
142
|
+
self.logger.debug("Applying consistency correction after reweighting.")
|
|
143
|
+
factor = 1 / (
|
|
144
|
+
gamma.cdf((chi2.ppf(0.975, X.shape[1]) / 2), X.shape[1] / 2 + 1) / 0.975
|
|
145
|
+
)
|
|
146
|
+
scale *= factor
|
|
147
|
+
|
|
148
|
+
return scale
|
|
149
|
+
|
|
150
|
+
def _correct_covariance(self, X: np.ndarray, best_subset: HSubset) -> np.ndarray:
|
|
151
|
+
self._rescale_factor = np.median(
|
|
152
|
+
np.square(mahalanobis_distance(X, best_subset.location, best_subset.scale))
|
|
153
|
+
) / chi2.ppf(0.5, X.shape[1])
|
|
154
|
+
|
|
155
|
+
return self._rescale_factor * best_subset.scale
|
|
156
|
+
|
|
157
|
+
def _perform_multiple_c_steps(
|
|
158
|
+
self, subset: HSubset, X: np.ndarray, n_iterations: int
|
|
159
|
+
) -> HSubset:
|
|
160
|
+
for _ in range(n_iterations):
|
|
161
|
+
subset = self._perform_c_step(subset, X)
|
|
162
|
+
return subset
|
|
163
|
+
|
|
164
|
+
def _perform_c_step(self, subset: HSubset, X: np.ndarray) -> HSubset:
|
|
165
|
+
"""
|
|
166
|
+
Perform a single C-step on the subset of the data
|
|
167
|
+
|
|
168
|
+
Args:
|
|
169
|
+
subset_idx: indices of the current subset
|
|
170
|
+
X: data
|
|
171
|
+
|
|
172
|
+
Returns:
|
|
173
|
+
indices for new h subset
|
|
174
|
+
"""
|
|
175
|
+
# Calculate the Mahalanobis distances
|
|
176
|
+
mahalanobis = mahalanobis_distance(X, subset.location, subset.scale)
|
|
177
|
+
# Find the h_size smallest distances
|
|
178
|
+
h = self._get_h(X)
|
|
179
|
+
idx = np.argsort(mahalanobis)[:h]
|
|
180
|
+
|
|
181
|
+
return self._get_subset(indices=idx, X=X, n_c_steps=subset.n_c_steps + 1)
|
|
182
|
+
|
|
183
|
+
def _get_h(self, X: np.ndarray) -> int:
|
|
184
|
+
if self.h_size is None:
|
|
185
|
+
return int((X.shape[0] + X.shape[1] + 1) / 2)
|
|
186
|
+
elif isinstance(self.h_size, int) and (X.shape[0] / 2 <= self.h_size <= X.shape[0]):
|
|
187
|
+
return self.h_size
|
|
188
|
+
elif (isinstance(self.h_size, float) and (0.5 <= self.h_size <= 1)) or self.h_size == 1:
|
|
189
|
+
return int(self.h_size * X.shape[0])
|
|
190
|
+
else:
|
|
191
|
+
raise ValueError(
|
|
192
|
+
f"h_size must be an integer between n/2 ({X.shape[0] // 2}) and n ({X.shape[0]}) or"
|
|
193
|
+
f" a float between 0.5 and 1, but received {self.h_size}."
|
|
194
|
+
)
|
|
195
|
+
|
|
196
|
+
def _partition_data(self, X: np.ndarray) -> list[np.ndarray]:
|
|
197
|
+
if self.n_partitions is None:
|
|
198
|
+
n_partitions = 5 if X.shape[0] > 600 else 1
|
|
199
|
+
else:
|
|
200
|
+
n_partitions = self.n_partitions
|
|
201
|
+
|
|
202
|
+
return np.array_split(X, n_partitions)
|
|
203
|
+
|
|
204
|
+
def _get_subset(
|
|
205
|
+
self,
|
|
206
|
+
indices: np.ndarray,
|
|
207
|
+
X: np.ndarray,
|
|
208
|
+
n_c_steps: int = 0,
|
|
209
|
+
ensure_non_singular: bool = False,
|
|
210
|
+
) -> HSubset:
|
|
211
|
+
"""
|
|
212
|
+
Construct an HSubset from a set of data indices and calculate location, scale and
|
|
213
|
+
determinant.
|
|
214
|
+
|
|
215
|
+
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)
|
|
221
|
+
"""
|
|
222
|
+
mu = X[indices].mean(axis=0)
|
|
223
|
+
cov = np.cov(X[indices], rowvar=False)
|
|
224
|
+
det = np.linalg.det(cov)
|
|
225
|
+
if ensure_non_singular:
|
|
226
|
+
while math.isclose(det, 0):
|
|
227
|
+
new_index = np.random.choice(np.delete(np.arange(X.shape[0]), indices))
|
|
228
|
+
indices = np.append(indices, new_index)
|
|
229
|
+
mu = X[indices].mean(axis=0)
|
|
230
|
+
cov = np.cov(X[indices], rowvar=False)
|
|
231
|
+
det = np.linalg.det(cov)
|
|
232
|
+
return HSubset(indices, mu, cov, det, n_c_steps=n_c_steps)
|
|
233
|
+
|
|
234
|
+
def _get_initial_subsets(self, X: np.ndarray, n_subsets: int) -> list[HSubset]:
|
|
235
|
+
return [
|
|
236
|
+
self._get_subset(
|
|
237
|
+
indices=np.random.choice(X.shape[0], X.shape[1] + 1, replace=False),
|
|
238
|
+
X=X,
|
|
239
|
+
ensure_non_singular=True,
|
|
240
|
+
)
|
|
241
|
+
for _ in range(n_subsets)
|
|
242
|
+
]
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
class DetMCDEstimator(RobustCovarianceEstimator):
|
|
246
|
+
def __init__(
|
|
247
|
+
self,
|
|
248
|
+
*,
|
|
249
|
+
h_size: float | int | None = None,
|
|
250
|
+
tolerance: float = 1e-8,
|
|
251
|
+
correct_covariance: bool = True,
|
|
252
|
+
reweighting: bool = True,
|
|
253
|
+
verbosity: int = logging.WARNING,
|
|
254
|
+
):
|
|
255
|
+
"""
|
|
256
|
+
Deterministic MCD estimator (DetMCD) based on the algorithm proposed in
|
|
257
|
+
Hubert, Rousseeuw and Verdonck (2012)
|
|
258
|
+
|
|
259
|
+
Args:
|
|
260
|
+
h_size (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.
|
|
267
|
+
tolerance (float, optional):
|
|
268
|
+
Minimum difference in determinant between two iterations to stop the C-step
|
|
269
|
+
correct_covariance (bool, optional):
|
|
270
|
+
Whether to apply a consistency correction to the raw covariance estimate
|
|
271
|
+
reweighting (bool, optional):
|
|
272
|
+
Whether to apply reweighting to the raw covariance estimate
|
|
273
|
+
|
|
274
|
+
References:
|
|
275
|
+
Hubert, Rousseeuw and Verdonck, A deterministic algorithm for robust location
|
|
276
|
+
and scatter, 2012, Journal of Computational and Graphical Statistics
|
|
277
|
+
|
|
278
|
+
"""
|
|
279
|
+
super().__init__()
|
|
280
|
+
self.h_size = h_size
|
|
281
|
+
self.tolerance = tolerance
|
|
282
|
+
self.correct_covariance = correct_covariance
|
|
283
|
+
self.reweighting = reweighting
|
|
284
|
+
self.logger = get_logger("DetMCDEstimator", level=verbosity)
|
|
285
|
+
self.verbosity = verbosity
|
|
286
|
+
|
|
287
|
+
def calculate_covariance(self, X: np.ndarray) -> np.ndarray:
|
|
288
|
+
if self.h_size == 1 or self.h_size == X.shape[0]:
|
|
289
|
+
self.logger.warning(f"Default covariance is returned as h_size is {self.h_size}.")
|
|
290
|
+
self.location_ = X.mean(0)
|
|
291
|
+
return np.cov(X, rowvar=False)
|
|
292
|
+
|
|
293
|
+
n, p = X.shape
|
|
294
|
+
|
|
295
|
+
# Step 0: standardize X
|
|
296
|
+
if n < 1000:
|
|
297
|
+
Z = (X - np.median(X, axis=0)) / self._Qn_scale(X)
|
|
298
|
+
else:
|
|
299
|
+
Z = (X - np.median(X, axis=0)) / self._tau_scale(X)
|
|
300
|
+
|
|
301
|
+
# Steps 1-3:
|
|
302
|
+
best_subsets = self._get_initial_best_subsets(Z, X, n, p)
|
|
303
|
+
|
|
304
|
+
# Step 4: C-steps until convergence
|
|
305
|
+
best_subset = best_subsets[0] # reference subset
|
|
306
|
+
for subset in best_subsets:
|
|
307
|
+
while True:
|
|
308
|
+
new_subset = self._perform_c_step(subset, X)
|
|
309
|
+
if (
|
|
310
|
+
np.all(new_subset.indices == subset.indices)
|
|
311
|
+
or (new_subset.determinant - subset.determinant) < self.tolerance
|
|
312
|
+
):
|
|
313
|
+
break
|
|
314
|
+
subset = new_subset
|
|
315
|
+
if subset.determinant < best_subset.determinant:
|
|
316
|
+
best_subset = subset
|
|
317
|
+
self.best_subset = best_subset
|
|
318
|
+
|
|
319
|
+
# Step 5: post processing
|
|
320
|
+
self.location_ = best_subset.location
|
|
321
|
+
scale = best_subset.scale
|
|
322
|
+
if self.correct_covariance:
|
|
323
|
+
self.logger.debug("Applying consistency correction to the raw covariance estimate")
|
|
324
|
+
scale = self._correct_covariance(X, best_subset)
|
|
325
|
+
if self.reweighting:
|
|
326
|
+
self.logger.debug("Applying reweighting to the raw covariance estimate")
|
|
327
|
+
distances = mahalanobis_distance(X, best_subset.location, scale)
|
|
328
|
+
self._mask = distances < np.sqrt(chi2.ppf(0.975, X.shape[1]))
|
|
329
|
+
self.location_ = X[self._mask].mean(axis=0)
|
|
330
|
+
scale = np.cov(X[self._mask], rowvar=False)
|
|
331
|
+
if self.correct_covariance:
|
|
332
|
+
# See Croux & Haesbroeck 1999 and R code for robustbase>covMcd>MCDCons
|
|
333
|
+
# (https://rdrr.io/cran/robustbase/src/R/covMcd.R)
|
|
334
|
+
self.logger.debug("Applying consistency correction after reweighting.")
|
|
335
|
+
factor = 1 / (
|
|
336
|
+
gamma.cdf((chi2.ppf(0.975, X.shape[1]) / 2), X.shape[1] / 2 + 1) / 0.975
|
|
337
|
+
)
|
|
338
|
+
scale *= factor
|
|
339
|
+
|
|
340
|
+
return scale
|
|
341
|
+
|
|
342
|
+
def _Qn_scale(self, X: np.ndarray, axis=0):
|
|
343
|
+
if X.ndim == 1:
|
|
344
|
+
return QnEstimator().fit(X).scale
|
|
345
|
+
elif axis == 0:
|
|
346
|
+
return [QnEstimator().fit(col).scale for col in X.T]
|
|
347
|
+
elif axis == 1:
|
|
348
|
+
return [QnEstimator().fit(col).scale for col in X]
|
|
349
|
+
else:
|
|
350
|
+
raise ValueError(f"axis {axis} not supported")
|
|
351
|
+
|
|
352
|
+
def _tau_scale(self, X: np.ndarray, axis=0):
|
|
353
|
+
if X.ndim == 1:
|
|
354
|
+
return TauEstimator().fit(X).scale
|
|
355
|
+
elif axis == 0:
|
|
356
|
+
return [TauEstimator().fit(col).scale for col in X.T]
|
|
357
|
+
elif axis == 1:
|
|
358
|
+
return [TauEstimator().fit(col).scale for col in X]
|
|
359
|
+
else:
|
|
360
|
+
raise ValueError(f"axis {axis} not supported")
|
|
361
|
+
|
|
362
|
+
def _get_initial_best_subsets(self, Z: np.ndarray, X: np.ndarray, n: int, p: int):
|
|
363
|
+
# Step 1: construct 6 preliminary estimates Sk of covariance or correlation
|
|
364
|
+
Y = np.tanh(Z)
|
|
365
|
+
S1 = np.corrcoef(Y, rowvar=False)
|
|
366
|
+
R = rankdata(Z, axis=0)
|
|
367
|
+
S2 = np.corrcoef(R, rowvar=False)
|
|
368
|
+
S3 = np.corrcoef(norm.ppf((R - 1 / 3) / (n + 1 / 3)), rowvar=False)
|
|
369
|
+
znorm = np.sqrt(np.sum(Z * Z, axis=1))
|
|
370
|
+
w = 1 / znorm
|
|
371
|
+
S4 = np.dot((Z * w[:, np.newaxis]).T, (Z * w[:, np.newaxis])) / n
|
|
372
|
+
idx = np.argsort(znorm)[: math.ceil(n / 2)]
|
|
373
|
+
S5 = np.cov(Z[idx, :], rowvar=False)
|
|
374
|
+
S6 = OGKEstimator(
|
|
375
|
+
location_estimator=np.median, scale_estimator=self._Qn_scale, reweighting=False
|
|
376
|
+
).calculate_covariance(Z)
|
|
377
|
+
estimates_S = [S1, S2, S3, S4, S5, S6]
|
|
378
|
+
|
|
379
|
+
# Step 2: construct 6 initial location and scatter estimates
|
|
380
|
+
estimates_sigma = []
|
|
381
|
+
estimates_mu = []
|
|
382
|
+
for S in estimates_S:
|
|
383
|
+
_, E = np.linalg.eigh(S)
|
|
384
|
+
E = E[:, np.arange(p - 1, -1, -1)]
|
|
385
|
+
B = Z @ E
|
|
386
|
+
L = np.diag(np.power(self._Qn_scale(B), 2))
|
|
387
|
+
cov = E @ L @ E.T
|
|
388
|
+
estimates_sigma.append(cov)
|
|
389
|
+
root_cov = sqrtm(cov)
|
|
390
|
+
inv_root_cov = np.linalg.inv(root_cov)
|
|
391
|
+
mu = root_cov @ np.median(Z @ inv_root_cov, axis=0)
|
|
392
|
+
estimates_mu.append(mu)
|
|
393
|
+
|
|
394
|
+
# Step 3: calculate statistical distances
|
|
395
|
+
best_subsets = []
|
|
396
|
+
for mu, cov in zip(estimates_mu, estimates_sigma):
|
|
397
|
+
idx_h0 = np.argsort(mahalanobis_distance(Z, mu, cov))[: math.ceil(n / 2)]
|
|
398
|
+
H = self._get_subset(idx_h0, X) # h0
|
|
399
|
+
H = self._perform_c_step(H, X) # h
|
|
400
|
+
best_subsets.append(H)
|
|
401
|
+
|
|
402
|
+
return best_subsets
|
|
403
|
+
|
|
404
|
+
# TODO: de functies hieronder moeten nog naar ergens anders.
|
|
405
|
+
|
|
406
|
+
def _get_h(self, X: np.ndarray) -> int:
|
|
407
|
+
if self.h_size is None:
|
|
408
|
+
return int((X.shape[0] + X.shape[1] + 1) / 2)
|
|
409
|
+
elif isinstance(self.h_size, int) and (X.shape[0] / 2 <= self.h_size <= X.shape[0]):
|
|
410
|
+
return self.h_size
|
|
411
|
+
elif (isinstance(self.h_size, float) and (0.5 <= self.h_size <= 1)) or self.h_size == 1:
|
|
412
|
+
return int(self.h_size * X.shape[0])
|
|
413
|
+
else:
|
|
414
|
+
raise ValueError(
|
|
415
|
+
f"h_size must be an integer between n/2 ({X.shape[0] // 2}) and n ({X.shape[0]}) or"
|
|
416
|
+
f" a float between 0.5 and 1, but received {self.h_size}."
|
|
417
|
+
)
|
|
418
|
+
|
|
419
|
+
def _get_subset(
|
|
420
|
+
self,
|
|
421
|
+
indices: np.ndarray,
|
|
422
|
+
X: np.ndarray,
|
|
423
|
+
n_c_steps: int = 0,
|
|
424
|
+
ensure_non_singular: bool = False,
|
|
425
|
+
) -> HSubset:
|
|
426
|
+
"""Construct an HSubset from a set of data indices and calculate location, scale and
|
|
427
|
+
determinant.
|
|
428
|
+
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)
|
|
434
|
+
"""
|
|
435
|
+
mu = X[indices].mean(axis=0)
|
|
436
|
+
cov = np.cov(X[indices], rowvar=False)
|
|
437
|
+
det = np.linalg.det(cov)
|
|
438
|
+
if ensure_non_singular:
|
|
439
|
+
while math.isclose(det, 0):
|
|
440
|
+
new_index = np.random.choice(np.delete(np.arange(X.shape[0]), indices))
|
|
441
|
+
indices = np.append(indices, new_index)
|
|
442
|
+
mu = X[indices].mean(axis=0)
|
|
443
|
+
cov = np.cov(X[indices], rowvar=False)
|
|
444
|
+
det = np.linalg.det(cov)
|
|
445
|
+
return HSubset(indices, mu, cov, det, n_c_steps=n_c_steps)
|
|
446
|
+
|
|
447
|
+
def _perform_c_step(self, subset: HSubset, X: np.ndarray) -> HSubset:
|
|
448
|
+
"""Perform a single C-step on the subset of the data
|
|
449
|
+
|
|
450
|
+
Args:
|
|
451
|
+
subset_idx: indices of the current subset
|
|
452
|
+
X: data
|
|
453
|
+
|
|
454
|
+
Returns:
|
|
455
|
+
indices for new h subset
|
|
456
|
+
"""
|
|
457
|
+
# Calculate the Mahalanobis distances
|
|
458
|
+
mahalanobis = mahalanobis_distance(X, subset.location, subset.scale)
|
|
459
|
+
# Find the h_size smallest distances
|
|
460
|
+
h = self._get_h(X)
|
|
461
|
+
idx = np.argsort(mahalanobis)[:h]
|
|
462
|
+
|
|
463
|
+
return self._get_subset(indices=idx, X=X, n_c_steps=subset.n_c_steps + 1)
|
|
464
|
+
|
|
465
|
+
def _correct_covariance(self, X: np.ndarray, best_subset: HSubset) -> np.ndarray:
|
|
466
|
+
self._rescale_factor = np.median(
|
|
467
|
+
np.square(mahalanobis_distance(X, best_subset.location, best_subset.scale))
|
|
468
|
+
) / chi2.ppf(0.5, X.shape[1])
|
|
469
|
+
|
|
470
|
+
return self._rescale_factor * best_subset.scale
|