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
robpy/pca/spca.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
|
|
5
|
+
from robpy.pca.base import RobustPCAEstimator
|
|
6
|
+
from robpy.utils.median import l1median
|
|
7
|
+
from scipy.stats import median_abs_deviation
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class PCALocantoreEstimator(RobustPCAEstimator):
|
|
11
|
+
def __init__(
|
|
12
|
+
self,
|
|
13
|
+
*,
|
|
14
|
+
n_components: int | None = None,
|
|
15
|
+
k_min_var_explained: float = 0.8,
|
|
16
|
+
):
|
|
17
|
+
"""Spherical PCA
|
|
18
|
+
|
|
19
|
+
Args:
|
|
20
|
+
n_components (int | None, optional):
|
|
21
|
+
Number of components to select. If None, it is set during fit to explain the
|
|
22
|
+
minimum variance.
|
|
23
|
+
k_min_var_explained (float, optional):
|
|
24
|
+
Minimum variance explained by the n_components
|
|
25
|
+
Only used if n_components is None.
|
|
26
|
+
"""
|
|
27
|
+
super().__init__(n_components=n_components)
|
|
28
|
+
self.k_min_var_explained = k_min_var_explained
|
|
29
|
+
|
|
30
|
+
def fit(self, X: np.ndarray) -> PCALocantoreEstimator:
|
|
31
|
+
n = len(X)
|
|
32
|
+
self.location_ = l1median(X)
|
|
33
|
+
centered_X = X - self.location_
|
|
34
|
+
d = np.sqrt(np.sum(centered_X * centered_X, axis=1))
|
|
35
|
+
w = 1 / d
|
|
36
|
+
spatial_sign_covariance = (
|
|
37
|
+
np.dot((centered_X * w[:, np.newaxis]).T, (centered_X * w[:, np.newaxis])) / n
|
|
38
|
+
)
|
|
39
|
+
_, eigenvectors = np.linalg.eigh(spatial_sign_covariance)
|
|
40
|
+
self.components_ = np.fliplr(eigenvectors)
|
|
41
|
+
eigenvalues = np.square(median_abs_deviation(self.transform(X), axis=0, scale="normal"))
|
|
42
|
+
var_explained_ratio = eigenvalues.cumsum() / eigenvalues.sum()
|
|
43
|
+
if self.n_components is None:
|
|
44
|
+
self.n_components = np.argmax(var_explained_ratio >= self.k_min_var_explained) + 1
|
|
45
|
+
self.components_ = self.components_[:, : self.n_components]
|
|
46
|
+
self.explained_variance_ = eigenvalues[: self.n_components]
|
|
47
|
+
self.explained_variance_ratio_ = var_explained_ratio[: self.n_components]
|
|
48
|
+
return self
|
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
import pandas as pd
|
|
3
|
+
import logging
|
|
4
|
+
|
|
5
|
+
from scipy.stats import median_abs_deviation
|
|
6
|
+
from sklearn.base import (
|
|
7
|
+
BaseEstimator,
|
|
8
|
+
OneToOneFeatureMixin,
|
|
9
|
+
TransformerMixin,
|
|
10
|
+
)
|
|
11
|
+
from sklearn.exceptions import NotFittedError
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class DataCleaner(OneToOneFeatureMixin, TransformerMixin, BaseEstimator):
|
|
15
|
+
"""Cleans a dataset before an analysis.
|
|
16
|
+
|
|
17
|
+
Typically used before DDC, cellMCD, transfo...
|
|
18
|
+
|
|
19
|
+
based on: [https://rdrr.io/cran/cellWise/man/checkDataSet.html]
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
def __init__(
|
|
23
|
+
self,
|
|
24
|
+
max_missing_frac_cols: float = 0.5,
|
|
25
|
+
max_missing_frac_rows: float = 0.5,
|
|
26
|
+
min_unique_values: int = 3,
|
|
27
|
+
min_abs_scale: float = 1e-12,
|
|
28
|
+
clean_na_first: str = "automatic",
|
|
29
|
+
min_n_rows: int = 3,
|
|
30
|
+
):
|
|
31
|
+
"""Initialize DataCleaner
|
|
32
|
+
|
|
33
|
+
Args:
|
|
34
|
+
max_missing_frac_cols (float, optional): Keep only the columns that have a
|
|
35
|
+
proportion of missing values lower than this threshold.
|
|
36
|
+
Defaults to 0.5.
|
|
37
|
+
max_missing_frac_rows (float, optional): Keep only the rows that have a
|
|
38
|
+
proportion of missing values lower than this threshold.
|
|
39
|
+
Defaults to 0.5.
|
|
40
|
+
min_unique_values (int, optional): Any column with min_unique_values or fewer unique
|
|
41
|
+
values will be classified as discrete and excluded from the cleaned
|
|
42
|
+
dataset.
|
|
43
|
+
Defaults to 3.
|
|
44
|
+
min_abs_scale (float, optional): Only columns whose scale is larger than min_abs_scale
|
|
45
|
+
will be considered (scale is measure by the mad).
|
|
46
|
+
Defaults to 1e-12.
|
|
47
|
+
clean_na_first (str, optional): One out of "automatic", "columns", "rows". Decides which
|
|
48
|
+
are first checked for NAs. If "automatic", columns are checked first if
|
|
49
|
+
if p >= 5n, else rows are checked first.
|
|
50
|
+
Defaults to "automatic".
|
|
51
|
+
min_n_rows (int, optional): Integer specifying the minimum number of rows/observations
|
|
52
|
+
wanted for the input data.
|
|
53
|
+
Defaults to 3.
|
|
54
|
+
"""
|
|
55
|
+
|
|
56
|
+
self.max_missing_frac_cols = max_missing_frac_cols
|
|
57
|
+
self.max_missing_frac_rows = max_missing_frac_rows
|
|
58
|
+
self.min_unique_values = min_unique_values
|
|
59
|
+
self.min_abs_scale = min_abs_scale
|
|
60
|
+
self.clean_na_first = clean_na_first
|
|
61
|
+
self.min_n_rows = min_n_rows
|
|
62
|
+
self.logger = logging.getLogger("DataCleaner")
|
|
63
|
+
|
|
64
|
+
def fit(self, X: pd.DataFrame):
|
|
65
|
+
"""
|
|
66
|
+
X (pd.DataFrame): input dataset.
|
|
67
|
+
"""
|
|
68
|
+
|
|
69
|
+
self._get_non_numeric_columns_to_drop(X)
|
|
70
|
+
|
|
71
|
+
self._get_discrete_columns_to_drop(X)
|
|
72
|
+
|
|
73
|
+
self._get_bad_scale_columns_to_drop(X)
|
|
74
|
+
|
|
75
|
+
return self
|
|
76
|
+
|
|
77
|
+
def transform(self, X: pd.DataFrame):
|
|
78
|
+
"""
|
|
79
|
+
X (pd.DataFrame): input dataset.
|
|
80
|
+
"""
|
|
81
|
+
|
|
82
|
+
n, p = X.shape
|
|
83
|
+
|
|
84
|
+
self._check_minimum_rows(n)
|
|
85
|
+
self.logger.info(f"The input data has {n} rows and {p} columns.")
|
|
86
|
+
X = X.replace([np.inf, -np.inf], np.nan)
|
|
87
|
+
self._set_row_numbers_cols(X)
|
|
88
|
+
self._set_missing_cols_and_rows(X)
|
|
89
|
+
|
|
90
|
+
X = X.drop(
|
|
91
|
+
columns=(
|
|
92
|
+
self.non_numeric_cols
|
|
93
|
+
+ self.cols_discrete
|
|
94
|
+
+ self.cols_bad_scale
|
|
95
|
+
+ self.cols_rownumbers
|
|
96
|
+
+ self.cols_missings
|
|
97
|
+
),
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
X = X.drop(index=self.rows_missings)
|
|
101
|
+
|
|
102
|
+
self.logger.info(f"The final data has {X.shape[0]} rows and {X.shape[1]} columns.")
|
|
103
|
+
|
|
104
|
+
return X
|
|
105
|
+
|
|
106
|
+
@property
|
|
107
|
+
def dropped_columns(self) -> dict[str, list]:
|
|
108
|
+
"""Return the columns names that were dropped during the cleaning process.
|
|
109
|
+
|
|
110
|
+
Returns:
|
|
111
|
+
dict[str, list]: Mapping from reason for dropping to list of column names.
|
|
112
|
+
|
|
113
|
+
Raises:
|
|
114
|
+
NotFittedError: if the dropped column attributes weren't set yet.
|
|
115
|
+
"""
|
|
116
|
+
if not all(
|
|
117
|
+
hasattr(self, attr)
|
|
118
|
+
for attr in [
|
|
119
|
+
"non_numeric_cols",
|
|
120
|
+
"cols_rownumbers",
|
|
121
|
+
"cols_discrete",
|
|
122
|
+
"cols_bad_scale",
|
|
123
|
+
"cols_missings",
|
|
124
|
+
]
|
|
125
|
+
):
|
|
126
|
+
raise NotFittedError()
|
|
127
|
+
return {
|
|
128
|
+
"non_numeric_cols": self.non_numeric_cols,
|
|
129
|
+
"cols_rownumbers": self.cols_rownumbers,
|
|
130
|
+
"cols_discrete": self.cols_discrete,
|
|
131
|
+
"cols_bad_scale": self.cols_bad_scale,
|
|
132
|
+
"cols_missings": self.cols_missings,
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
@property
|
|
136
|
+
def dropped_rows(self) -> dict[str, list]:
|
|
137
|
+
"""
|
|
138
|
+
Return the rows indices that were dropped during the cleaning process.
|
|
139
|
+
|
|
140
|
+
Returns:
|
|
141
|
+
dict[str, list]: mapping from reason for dropping to list of row indices.
|
|
142
|
+
|
|
143
|
+
Raises:
|
|
144
|
+
NotFittedError: if the dropped row attributes weren't set yet.
|
|
145
|
+
"""
|
|
146
|
+
if not hasattr(self, "rows_missings"):
|
|
147
|
+
raise NotFittedError()
|
|
148
|
+
return {"rows_missings": self.rows_missings}
|
|
149
|
+
|
|
150
|
+
def _check_minimum_rows(self, n: int) -> None:
|
|
151
|
+
"""Check if there are enough rows in the input dataset."""
|
|
152
|
+
if n < self.min_n_rows:
|
|
153
|
+
raise ValueError(
|
|
154
|
+
f"The input data must have at least {self.min_n_rows} rows, "
|
|
155
|
+
f"but received only {n}."
|
|
156
|
+
)
|
|
157
|
+
|
|
158
|
+
def _get_non_numeric_columns_to_drop(self, X: pd.DataFrame):
|
|
159
|
+
"""Store non-numeric columns to drop."""
|
|
160
|
+
self.non_numeric_cols = X.columns[
|
|
161
|
+
X.apply(lambda s: pd.to_numeric(s.fillna(0), errors="coerce")).isna().any()
|
|
162
|
+
].tolist()
|
|
163
|
+
|
|
164
|
+
def _set_row_numbers_cols(self, X: pd.DataFrame):
|
|
165
|
+
"""Check that no column consists of the row numbers."""
|
|
166
|
+
self.cols_rownumbers = [col for col in X.columns if np.all(X[col] == np.arange(0, len(X)))]
|
|
167
|
+
|
|
168
|
+
def _set_missing_cols_and_rows(self, X: pd.DataFrame):
|
|
169
|
+
"""Clean missing values."""
|
|
170
|
+
if self.clean_na_first == "automatic":
|
|
171
|
+
self.clean_na_first = "columns" if X.shape[1] >= 5 * X.shape[0] else "rows"
|
|
172
|
+
|
|
173
|
+
X = X.replace([np.inf, -np.inf], np.nan).drop(
|
|
174
|
+
columns=self.non_numeric_cols + self.cols_discrete + self.cols_bad_scale
|
|
175
|
+
)
|
|
176
|
+
if self.clean_na_first == "columns":
|
|
177
|
+
self._set_missing_cols(X)
|
|
178
|
+
self._set_missing_rows(X)
|
|
179
|
+
elif self.clean_na_first == "rows":
|
|
180
|
+
self._set_missing_rows(X)
|
|
181
|
+
self._set_missing_cols(X)
|
|
182
|
+
else:
|
|
183
|
+
raise ValueError(
|
|
184
|
+
'The argument clean_na_first should be "automatic", "rows" or "columns", '
|
|
185
|
+
f'but received "{self.clean_na_first}".'
|
|
186
|
+
)
|
|
187
|
+
|
|
188
|
+
def _get_discrete_columns_to_drop(self, X: pd.DataFrame):
|
|
189
|
+
"""Store columns with a small number of unique values (discrete columns) to drop."""
|
|
190
|
+
self.cols_discrete = X.columns[X.nunique() <= self.min_unique_values].tolist()
|
|
191
|
+
|
|
192
|
+
def _get_bad_scale_columns_to_drop(self, X: pd.DataFrame):
|
|
193
|
+
"""Store columns with a scale smaller than min_abs_scale to drop."""
|
|
194
|
+
X = X.drop(columns=self.non_numeric_cols + self.cols_discrete).astype(float)
|
|
195
|
+
self.cols_bad_scale = X.columns[
|
|
196
|
+
median_abs_deviation(
|
|
197
|
+
X.replace([np.inf, -np.inf, True, False], np.nan),
|
|
198
|
+
axis=0,
|
|
199
|
+
nan_policy="omit",
|
|
200
|
+
)
|
|
201
|
+
<= self.min_abs_scale
|
|
202
|
+
].tolist()
|
|
203
|
+
|
|
204
|
+
def _set_missing_cols(self, X: pd.DataFrame):
|
|
205
|
+
"""Remove columns with too many missings"""
|
|
206
|
+
if hasattr(self, "rows_missings"):
|
|
207
|
+
X = X.drop(index=self.rows_missings)
|
|
208
|
+
self.cols_missings = X.columns[X.isna().mean() >= self.max_missing_frac_cols].tolist()
|
|
209
|
+
|
|
210
|
+
def _set_missing_rows(self, X: pd.DataFrame):
|
|
211
|
+
"""Remove rows with too many missings"""
|
|
212
|
+
if hasattr(self, "cols_missings"):
|
|
213
|
+
X = X.drop(columns=self.cols_missings)
|
|
214
|
+
self.rows_missings = X.index[X.isna().mean(axis=1) >= self.max_missing_frac_rows].tolist()
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
import pandas as pd
|
|
3
|
+
from sklearn.base import (
|
|
4
|
+
BaseEstimator,
|
|
5
|
+
OneToOneFeatureMixin,
|
|
6
|
+
TransformerMixin,
|
|
7
|
+
)
|
|
8
|
+
|
|
9
|
+
from robpy.univariate.base import RobustScaleEstimator
|
|
10
|
+
from robpy.univariate.mcd import UnivariateMCDEstimator
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class RobustScaler(OneToOneFeatureMixin, TransformerMixin, BaseEstimator):
|
|
14
|
+
"""Scaling features using a RobustScaleEstimator"""
|
|
15
|
+
|
|
16
|
+
def __init__(
|
|
17
|
+
self,
|
|
18
|
+
scale_estimator: RobustScaleEstimator = UnivariateMCDEstimator(),
|
|
19
|
+
with_centering: bool = True,
|
|
20
|
+
with_scaling: bool = True,
|
|
21
|
+
):
|
|
22
|
+
self.scale_estimator = scale_estimator
|
|
23
|
+
self.with_centering = with_centering
|
|
24
|
+
self.with_scaling = with_scaling
|
|
25
|
+
|
|
26
|
+
def fit(self, X: np.ndarray | pd.DataFrame, ignore_nan: bool = False):
|
|
27
|
+
if isinstance(X, pd.DataFrame):
|
|
28
|
+
X = X.values
|
|
29
|
+
if len(X.shape) == 1:
|
|
30
|
+
X = X.reshape(-1, 1)
|
|
31
|
+
self.locations_ = np.zeros(X.shape[1])
|
|
32
|
+
self.scales_ = np.ones(X.shape[1])
|
|
33
|
+
|
|
34
|
+
for feature_idx in range(X.shape[1]):
|
|
35
|
+
fitted_estimator = self.scale_estimator.fit(X[:, feature_idx], ignore_nan)
|
|
36
|
+
if self.with_centering:
|
|
37
|
+
self.locations_[feature_idx] = fitted_estimator.location
|
|
38
|
+
if self.with_scaling:
|
|
39
|
+
self.scales_[feature_idx] = fitted_estimator.scale
|
|
40
|
+
|
|
41
|
+
return self
|
|
42
|
+
|
|
43
|
+
def transform(self, X: np.ndarray | pd.DataFrame):
|
|
44
|
+
if isinstance(X, pd.DataFrame):
|
|
45
|
+
X = X.values
|
|
46
|
+
if len(X.shape) == 1:
|
|
47
|
+
X = X.reshape(-1, 1)
|
|
48
|
+
|
|
49
|
+
return (X - self.locations_) / self.scales_
|
|
50
|
+
|
|
51
|
+
def inverse_transform(self, X: np.ndarray | pd.DataFrame):
|
|
52
|
+
if isinstance(X, pd.DataFrame):
|
|
53
|
+
X = X.values
|
|
54
|
+
if len(X.shape) == 1:
|
|
55
|
+
X = X.reshape(-1, 1)
|
|
56
|
+
|
|
57
|
+
return X * self.scales_ + self.locations_
|