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,621 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
import numpy as np
|
|
3
|
+
import matplotlib.pyplot as plt
|
|
4
|
+
|
|
5
|
+
from scipy.stats import chi2, median_abs_deviation
|
|
6
|
+
from typing import Literal, Optional
|
|
7
|
+
from robpy.covariance.utils.alter_covariance import truncated_covariance
|
|
8
|
+
from robpy.covariance.base import RobustCovarianceEstimator
|
|
9
|
+
from robpy.utils.logging import get_logger
|
|
10
|
+
from robpy.covariance.utils.cellmcd_utils import objective_function
|
|
11
|
+
from robpy.utils.general import inverse_submatrix
|
|
12
|
+
from robpy.covariance.utils.cellmcd_visualization_utils import (
|
|
13
|
+
annote_outliers,
|
|
14
|
+
annote_outliers_ellipse,
|
|
15
|
+
draw_ellipse,
|
|
16
|
+
draw_threshold_lines,
|
|
17
|
+
get_thresholds,
|
|
18
|
+
)
|
|
19
|
+
from robpy.preprocessing.scaling import RobustScaler
|
|
20
|
+
from robpy.univariate.onestep_m import OneStepWrappingEstimator
|
|
21
|
+
from robpy.covariance.initial_ddcw import InitialDDCWEstimator
|
|
22
|
+
from sklearn.exceptions import NotFittedError
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class CellMCDEstimator(RobustCovarianceEstimator):
|
|
26
|
+
def __init__(
|
|
27
|
+
self,
|
|
28
|
+
*,
|
|
29
|
+
alpha: float = 0.75,
|
|
30
|
+
quantile: float = 0.99,
|
|
31
|
+
crit: float = 1e-4,
|
|
32
|
+
max_c_steps: int = 100,
|
|
33
|
+
min_eigenvalue: float = 1e-4,
|
|
34
|
+
verbosity: int = logging.WARNING,
|
|
35
|
+
):
|
|
36
|
+
"""
|
|
37
|
+
Cell MCD estimator based on the algorithm proposed in Raymaekers and Rousseeuw (2023).
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
Args:
|
|
41
|
+
alpha (float, optional):
|
|
42
|
+
Percentage indicating how much cells must remain unflagged in each column.
|
|
43
|
+
Defaults to 0.75.
|
|
44
|
+
quantile (float, optional):
|
|
45
|
+
Cutoff value to flag cells.
|
|
46
|
+
Defaults to 0.99.
|
|
47
|
+
crit (float, optional):
|
|
48
|
+
Stop iterating when successive covariance matrices of the standardized data
|
|
49
|
+
differ by less than crit.
|
|
50
|
+
Defaults to 1e-4
|
|
51
|
+
max_c_steps (int, optional):
|
|
52
|
+
Maximum number of C-steps used in the algorithm.
|
|
53
|
+
Defaults to 100.
|
|
54
|
+
min_eigenvalue: (float, optional):
|
|
55
|
+
Lower bound on the minimum eigenvalue of the covariance estimator
|
|
56
|
+
on the standardized data. Should be at least 1e-6.
|
|
57
|
+
Defaults to 1e-4.
|
|
58
|
+
|
|
59
|
+
References:
|
|
60
|
+
- Raymaekers and Rousseeuw, The Cellwise Minimum Covariance Determinant Estimator, 2023,
|
|
61
|
+
Journal of the American Statistical Association.
|
|
62
|
+
"""
|
|
63
|
+
if min_eigenvalue < 1e-6:
|
|
64
|
+
raise ValueError("The lower bound on the eigenvalues should be at least 1e-6.")
|
|
65
|
+
super().__init__(store_precision=False, assume_centered=False, nans_allowed=True)
|
|
66
|
+
self.alpha = alpha
|
|
67
|
+
self.quantile = quantile
|
|
68
|
+
self.crit = crit
|
|
69
|
+
self.max_c_steps = max_c_steps
|
|
70
|
+
self.min_eigenvalue = min_eigenvalue
|
|
71
|
+
self.logger = get_logger("CellMCDEstimator", level=verbosity)
|
|
72
|
+
self.verbosity = verbosity
|
|
73
|
+
|
|
74
|
+
def calculate_covariance(self, X: np.ndarray) -> np.ndarray:
|
|
75
|
+
# Step 0: robustly standardize the data
|
|
76
|
+
mads = median_abs_deviation(X, nan_policy="omit", axis=0)
|
|
77
|
+
if np.min(mads) < 1e-8:
|
|
78
|
+
raise ValueError("At least one variable has an almost zero median absolute deviation.")
|
|
79
|
+
scaler = RobustScaler(scale_estimator=OneStepWrappingEstimator())
|
|
80
|
+
scaler.fit(X, ignore_nan=True)
|
|
81
|
+
X_scaled = scaler.transform(X)
|
|
82
|
+
|
|
83
|
+
# Step 1: Check that there aren't too many marginal outliers and too many nan's.
|
|
84
|
+
# Check that there are enough observations compared to variables.
|
|
85
|
+
self._check_data(X_scaled)
|
|
86
|
+
|
|
87
|
+
# Step 2: calculate the initial estimates
|
|
88
|
+
ddcw = InitialDDCWEstimator(alpha=self.alpha, min_eigenvalue=self.min_eigenvalue)
|
|
89
|
+
ddcw.fit(X_scaled)
|
|
90
|
+
initial_location = ddcw.location_
|
|
91
|
+
initial_cov = ddcw.covariance_
|
|
92
|
+
initial_cov_inv = ddcw.precision_
|
|
93
|
+
X_scaled[np.abs(X_scaled) > 3] = np.nan
|
|
94
|
+
|
|
95
|
+
# Step 3: MCD iterations (we work with X_scaled)
|
|
96
|
+
location, cov, cov_inv, W = self._C_steps_until_convergence(
|
|
97
|
+
X_scaled, initial_location, initial_cov, initial_cov_inv
|
|
98
|
+
)
|
|
99
|
+
# Step 4: make prediction
|
|
100
|
+
predictions, conditional_variances = self._make_predictions(
|
|
101
|
+
X_scaled, cov, cov_inv, location, W
|
|
102
|
+
)
|
|
103
|
+
|
|
104
|
+
# Step 5: transform back
|
|
105
|
+
cov = np.diag(scaler.scales_) @ cov @ np.diag(scaler.scales_)
|
|
106
|
+
location = scaler.locations_ + location * scaler.scales_
|
|
107
|
+
predictions = scaler.locations_ + predictions * scaler.scales_
|
|
108
|
+
conditional_stds = np.sqrt(conditional_variances) * scaler.scales_
|
|
109
|
+
X_imputed = X.copy()
|
|
110
|
+
X_imputed[W == 0] = predictions[W == 0]
|
|
111
|
+
residuals = (X - predictions) / conditional_stds
|
|
112
|
+
scaler_residuals = RobustScaler(scale_estimator=OneStepWrappingEstimator())
|
|
113
|
+
scaler_residuals.fit(residuals, ignore_nan=True)
|
|
114
|
+
residuals = residuals / scaler_residuals.scales_
|
|
115
|
+
|
|
116
|
+
self.W = W
|
|
117
|
+
self.location_ = location
|
|
118
|
+
self.predictions = predictions
|
|
119
|
+
self.conditional_stds = conditional_stds
|
|
120
|
+
self.X_imputed = X_imputed
|
|
121
|
+
self.residuals = residuals
|
|
122
|
+
self.covariance_ = cov
|
|
123
|
+
self.X = X
|
|
124
|
+
|
|
125
|
+
return cov
|
|
126
|
+
|
|
127
|
+
def cell_MCD_plot(
|
|
128
|
+
self,
|
|
129
|
+
variable: int,
|
|
130
|
+
variable_name: str = "variable",
|
|
131
|
+
row_names: Optional[list] = None,
|
|
132
|
+
second_variable: Optional[int] = None,
|
|
133
|
+
second_variable_name: str = "second variable",
|
|
134
|
+
plottype: Literal[
|
|
135
|
+
"indexplot",
|
|
136
|
+
"residuals_vs_variable",
|
|
137
|
+
"residuals_vs_predictions",
|
|
138
|
+
"variable_vs_predictions",
|
|
139
|
+
"bivariate",
|
|
140
|
+
] = "indexplot",
|
|
141
|
+
figsize: tuple[int, int] = (8, 8),
|
|
142
|
+
):
|
|
143
|
+
"""
|
|
144
|
+
Function to plot the results of a cellMCD analysis: 5 types of diagnostic plots.
|
|
145
|
+
|
|
146
|
+
Arguments:
|
|
147
|
+
plottype (Literal string, optional):
|
|
148
|
+
"indexplot": plots the residuals of a variable,
|
|
149
|
+
"residuals_vs_variable": plots a variable versus its residuals,
|
|
150
|
+
"residuals_vs_predictions": plots the predictions of a variable versus its
|
|
151
|
+
residuals,
|
|
152
|
+
"variable_vs_predictions": plots a variable against its predictions,
|
|
153
|
+
"bivariate": plots two variables against each other,
|
|
154
|
+
|
|
155
|
+
Defaults to "indexplot".
|
|
156
|
+
variable (int): Index of the variable under consideration.
|
|
157
|
+
variable_name (str, optional): Name of the variable of interest for the axis label.
|
|
158
|
+
Defaults to "variable".
|
|
159
|
+
second_variable (int): Index of the second variable under consideration,
|
|
160
|
+
only needed for plottype "bivariate".
|
|
161
|
+
second_variable_name (str, optional): Name of the second variable for the axis label,
|
|
162
|
+
only relevant for plottype "bivariate". Defaults to "second variable".
|
|
163
|
+
row_names (list of strings, optional): Row_names of the observations if you want
|
|
164
|
+
the outliers annoted with their name.
|
|
165
|
+
figsize (tuple[int,int], optional): Size of the figure. Defaults to (8,8).
|
|
166
|
+
"""
|
|
167
|
+
|
|
168
|
+
if not hasattr(self, "covariance_"):
|
|
169
|
+
raise NotFittedError()
|
|
170
|
+
|
|
171
|
+
fig, ax = plt.subplots(1, 1, figsize=figsize)
|
|
172
|
+
cutoff = np.sqrt(chi2.ppf(self.quantile, 1))
|
|
173
|
+
|
|
174
|
+
if plottype == "indexplot":
|
|
175
|
+
x, y = np.arange(self.W.shape[0]), self.residuals[:, variable]
|
|
176
|
+
h_thresholds, v_thresholds = (-cutoff, cutoff), None
|
|
177
|
+
xlabel, ylabel = "index", f"standardized residuals of {variable_name}"
|
|
178
|
+
title = "Indexplot: standardized residuals"
|
|
179
|
+
|
|
180
|
+
elif plottype == "residuals_vs_variable":
|
|
181
|
+
x, y = self.X[:, variable], self.residuals[:, variable]
|
|
182
|
+
h_thresholds, v_thresholds = (-cutoff, cutoff), get_thresholds(cutoff, x)
|
|
183
|
+
xlabel, ylabel = variable_name, f"standardized residuals of {variable_name}"
|
|
184
|
+
title = f"Standardized residuals versus the {variable_name}"
|
|
185
|
+
|
|
186
|
+
elif plottype == "residuals_vs_predictions":
|
|
187
|
+
x, y = self.predictions[:, variable], self.residuals[:, variable]
|
|
188
|
+
h_thresholds, v_thresholds = (-cutoff, cutoff), get_thresholds(cutoff, x)
|
|
189
|
+
xlabel, ylabel = (
|
|
190
|
+
f"predictions of {variable_name}",
|
|
191
|
+
f"standardized residuals of {variable_name}",
|
|
192
|
+
)
|
|
193
|
+
title = f"Standardized residuals versus the predictions of the {variable_name}"
|
|
194
|
+
|
|
195
|
+
elif plottype == "variable_vs_predictions":
|
|
196
|
+
x, y = self.predictions[:, variable], self.X[:, variable]
|
|
197
|
+
h_thresholds, v_thresholds = get_thresholds(cutoff, y), get_thresholds(cutoff, x)
|
|
198
|
+
xlabel, ylabel = f"predictions of {variable_name}", f"observed {variable_name}"
|
|
199
|
+
ax.axline((x[0], x[0]), slope=1, color="grey", linestyle="-.")
|
|
200
|
+
title = f"{variable_name} versus its predictions"
|
|
201
|
+
|
|
202
|
+
elif plottype == "bivariate":
|
|
203
|
+
if second_variable is None:
|
|
204
|
+
raise ValueError("second_variable must be provided for bivariate plot.")
|
|
205
|
+
x, y = self.X[:, variable], self.X[:, second_variable]
|
|
206
|
+
h_thresholds, v_thresholds = get_thresholds(cutoff, y), get_thresholds(cutoff, x)
|
|
207
|
+
xlabel, ylabel = variable_name, second_variable_name
|
|
208
|
+
draw_ellipse(
|
|
209
|
+
self.covariance_[np.ix_([variable, second_variable], [variable, second_variable])],
|
|
210
|
+
self.location_[[variable, second_variable]],
|
|
211
|
+
ax,
|
|
212
|
+
self.quantile,
|
|
213
|
+
)
|
|
214
|
+
title = f"{variable_name} versus {second_variable_name}"
|
|
215
|
+
|
|
216
|
+
ax.scatter(x=x, y=y)
|
|
217
|
+
ax.set(xlabel=xlabel, ylabel=ylabel, title=title)
|
|
218
|
+
|
|
219
|
+
if row_names is not None:
|
|
220
|
+
if plottype != "bivariate":
|
|
221
|
+
annote_outliers(ax, row_names, x, y, h_thresholds, v_thresholds)
|
|
222
|
+
else:
|
|
223
|
+
annote_outliers_ellipse(
|
|
224
|
+
ax,
|
|
225
|
+
row_names,
|
|
226
|
+
self.location_,
|
|
227
|
+
self.covariance_,
|
|
228
|
+
variable,
|
|
229
|
+
second_variable,
|
|
230
|
+
x,
|
|
231
|
+
y,
|
|
232
|
+
self.quantile,
|
|
233
|
+
)
|
|
234
|
+
|
|
235
|
+
draw_threshold_lines(ax, h_thresholds, v_thresholds)
|
|
236
|
+
|
|
237
|
+
return fig
|
|
238
|
+
|
|
239
|
+
def _make_predictions(
|
|
240
|
+
self, X: np.ndarray, sigma: np.ndarray, sigma_inv: np.ndarray, mu: np.ndarray, W: np.ndarray
|
|
241
|
+
) -> tuple[np.ndarray, np.ndarray]:
|
|
242
|
+
"""Calculate the predictions of the cells given the other clean cells in the same row"""
|
|
243
|
+
|
|
244
|
+
n, p = X.shape
|
|
245
|
+
predictions = np.zeros([n, p])
|
|
246
|
+
conditional_variances = np.zeros([n, p])
|
|
247
|
+
unique_rows = np.unique(W, axis=0)
|
|
248
|
+
|
|
249
|
+
for w in unique_rows: # iterate over all w patterns
|
|
250
|
+
row_idx_w = np.where(np.all(W == w, axis=1))[0] # rows with the corresponding w pattern
|
|
251
|
+
missing_col_idx = np.where(w == 0)[0]
|
|
252
|
+
observed_col_idx = np.where(w == 1)[0]
|
|
253
|
+
|
|
254
|
+
if len(missing_col_idx) < p and len(missing_col_idx) > 0:
|
|
255
|
+
# there are both observed and missing values
|
|
256
|
+
|
|
257
|
+
# predict the missing values
|
|
258
|
+
predictions, conditional_variances = self._predict_missing_values(
|
|
259
|
+
X,
|
|
260
|
+
predictions,
|
|
261
|
+
conditional_variances,
|
|
262
|
+
row_idx_w,
|
|
263
|
+
missing_col_idx,
|
|
264
|
+
observed_col_idx,
|
|
265
|
+
mu,
|
|
266
|
+
sigma,
|
|
267
|
+
sigma_inv,
|
|
268
|
+
)
|
|
269
|
+
|
|
270
|
+
# predict the observed values
|
|
271
|
+
predictions, conditional_variances = self._predict_observed_values(
|
|
272
|
+
X,
|
|
273
|
+
predictions,
|
|
274
|
+
conditional_variances,
|
|
275
|
+
row_idx_w,
|
|
276
|
+
observed_col_idx,
|
|
277
|
+
mu,
|
|
278
|
+
sigma,
|
|
279
|
+
sigma_inv,
|
|
280
|
+
)
|
|
281
|
+
|
|
282
|
+
elif len(missing_col_idx) == 0: # no missings in the w-pattern
|
|
283
|
+
predictions, conditional_variances = self._predict_no_missing(
|
|
284
|
+
X, predictions, conditional_variances, row_idx_w, mu, sigma, sigma_inv
|
|
285
|
+
)
|
|
286
|
+
|
|
287
|
+
else: # all missings in the w-pattern
|
|
288
|
+
predictions, conditional_variances = self._predict_all_missing(
|
|
289
|
+
predictions, conditional_variances, row_idx_w, mu, sigma_inv
|
|
290
|
+
)
|
|
291
|
+
|
|
292
|
+
return predictions, conditional_variances
|
|
293
|
+
|
|
294
|
+
def _C_steps_until_convergence(
|
|
295
|
+
self,
|
|
296
|
+
X_scaled: np.ndarray,
|
|
297
|
+
initial_location: np.array,
|
|
298
|
+
initial_cov: np.ndarray,
|
|
299
|
+
initial_cov_inv: np.ndarray,
|
|
300
|
+
):
|
|
301
|
+
"""Perform C-steps (update W, location and covariance) until convergence.
|
|
302
|
+
|
|
303
|
+
Arguments:
|
|
304
|
+
- X_scaled (np.ndarray): scaled data
|
|
305
|
+
- initial_location (np.array): initial location estimate
|
|
306
|
+
- initial_cov (np.ndarray): initial covariance estimate
|
|
307
|
+
- initial_cov_inv (np.ndarray): inverse of the initial covariance estimate
|
|
308
|
+
"""
|
|
309
|
+
n, p = X_scaled.shape
|
|
310
|
+
|
|
311
|
+
h = round(self.alpha * n)
|
|
312
|
+
initial_W = np.ones([n, p])
|
|
313
|
+
initial_W[np.isnan(X_scaled)] = 0
|
|
314
|
+
objective_values = np.full(self.max_c_steps + 1, np.nan)
|
|
315
|
+
step = 0
|
|
316
|
+
q = (
|
|
317
|
+
chi2.ppf(0.99, 1) - np.log(np.diag(initial_cov_inv)) + np.log(2 * np.pi)
|
|
318
|
+
) # equation (21)
|
|
319
|
+
penalty = np.sum(q * np.sum(1 - initial_W, axis=0))
|
|
320
|
+
objective_values[step] = (
|
|
321
|
+
objective_function(X_scaled, initial_W, initial_location, initial_cov, initial_cov_inv)
|
|
322
|
+
+ penalty
|
|
323
|
+
)
|
|
324
|
+
convergence_criteria = 1
|
|
325
|
+
W_old = initial_W
|
|
326
|
+
location_old = initial_location
|
|
327
|
+
cov_old = initial_cov
|
|
328
|
+
cov_inv_old = initial_cov_inv
|
|
329
|
+
while convergence_criteria > self.crit and step < self.max_c_steps:
|
|
330
|
+
W, location, cov = self._C_step(
|
|
331
|
+
X_scaled, W_old, location_old, cov_old, cov_inv_old, q, h
|
|
332
|
+
)
|
|
333
|
+
convergence_criteria = np.max(np.abs(cov - cov_old))
|
|
334
|
+
cov = truncated_covariance(cov, self.min_eigenvalue)
|
|
335
|
+
cov_inv = np.linalg.inv(cov)
|
|
336
|
+
penalty = np.sum(q * np.sum(1 - W, axis=0))
|
|
337
|
+
objective_value = objective_function(X_scaled, W, location, cov, cov_inv) + penalty
|
|
338
|
+
if objective_value > objective_values[step]:
|
|
339
|
+
return location_old, cov_old, cov_inv_old, W_old
|
|
340
|
+
step = step + 1
|
|
341
|
+
objective_values[step] = objective_value
|
|
342
|
+
W_old = W
|
|
343
|
+
location_old = location
|
|
344
|
+
cov_old = cov
|
|
345
|
+
cov_inv_old = cov_inv
|
|
346
|
+
|
|
347
|
+
return location, cov, cov_inv, W
|
|
348
|
+
|
|
349
|
+
def _C_step(
|
|
350
|
+
self,
|
|
351
|
+
X: np.ndarray,
|
|
352
|
+
W: np.ndarray,
|
|
353
|
+
mu: np.array,
|
|
354
|
+
sigma: np.ndarray,
|
|
355
|
+
sigma_inv: np.ndarray,
|
|
356
|
+
q: np.array,
|
|
357
|
+
h: int,
|
|
358
|
+
):
|
|
359
|
+
n, p = X.shape
|
|
360
|
+
|
|
361
|
+
# first update W
|
|
362
|
+
W = self._update_W(X, W, mu, sigma, sigma_inv, q, h)
|
|
363
|
+
|
|
364
|
+
# next: update mu & sigma
|
|
365
|
+
X_imputed = np.copy(X)
|
|
366
|
+
bias = np.zeros([p, p])
|
|
367
|
+
for i in range(n):
|
|
368
|
+
missing_col_idx = np.where(W[i, :] == 0)[0]
|
|
369
|
+
observed_col_idx = np.where(W[i, :] == 1)[0]
|
|
370
|
+
if len(missing_col_idx) > 0:
|
|
371
|
+
if len(missing_col_idx) == p: # if all are missing
|
|
372
|
+
X_imputed[i, :] = mu
|
|
373
|
+
bias = bias + sigma
|
|
374
|
+
else:
|
|
375
|
+
sigma_inv_mis_inv = np.linalg.inv(
|
|
376
|
+
sigma_inv[np.ix_(missing_col_idx, missing_col_idx)]
|
|
377
|
+
)
|
|
378
|
+
X_imputed[np.ix_([i], missing_col_idx)] = (
|
|
379
|
+
mu[missing_col_idx]
|
|
380
|
+
- (
|
|
381
|
+
sigma_inv_mis_inv
|
|
382
|
+
@ sigma_inv[np.ix_(missing_col_idx, observed_col_idx)]
|
|
383
|
+
@ (X[np.ix_([i], observed_col_idx)] - mu[observed_col_idx]).T
|
|
384
|
+
).flatten()
|
|
385
|
+
)
|
|
386
|
+
bias[np.ix_(missing_col_idx, missing_col_idx)] = (
|
|
387
|
+
bias[np.ix_(missing_col_idx, missing_col_idx)] + sigma_inv_mis_inv
|
|
388
|
+
)
|
|
389
|
+
mu = np.mean(X_imputed, axis=0)
|
|
390
|
+
bias = bias / n
|
|
391
|
+
sigma = np.cov(X_imputed, rowvar=False) * (n - 1) / n + bias
|
|
392
|
+
|
|
393
|
+
return W, mu, sigma
|
|
394
|
+
|
|
395
|
+
def _update_W(
|
|
396
|
+
self,
|
|
397
|
+
X: np.ndarray,
|
|
398
|
+
W: np.ndarray,
|
|
399
|
+
mu: np.array,
|
|
400
|
+
sigma: np.ndarray,
|
|
401
|
+
sigma_inv: np.ndarray,
|
|
402
|
+
q: np.array,
|
|
403
|
+
h: int,
|
|
404
|
+
) -> np.ndarray:
|
|
405
|
+
"""Part (a) of the C-step: updating the matrix W while keeping mu and sigma unchanged.
|
|
406
|
+
This is done per column."""
|
|
407
|
+
|
|
408
|
+
n = W.shape[0]
|
|
409
|
+
ordering = np.argsort(np.sum(W, axis=0), kind="stable")
|
|
410
|
+
for j in ordering:
|
|
411
|
+
delta = self._calculate_delta(X, W, sigma, sigma_inv, mu, j)
|
|
412
|
+
good_cells = np.where(delta <= q[j])[0]
|
|
413
|
+
if len(good_cells) < h: # cannot set less than h cells to 1
|
|
414
|
+
delta_rank = np.argsort(delta, kind="stable")
|
|
415
|
+
good_cells = delta_rank[:h]
|
|
416
|
+
w_new = np.zeros(n)
|
|
417
|
+
w_new[good_cells] = 1
|
|
418
|
+
W[:, j] = w_new
|
|
419
|
+
|
|
420
|
+
return W
|
|
421
|
+
|
|
422
|
+
def _calculate_delta(
|
|
423
|
+
self,
|
|
424
|
+
X: np.ndarray,
|
|
425
|
+
W: np.ndarray,
|
|
426
|
+
sigma: np.ndarray,
|
|
427
|
+
sigma_inv: np.ndarray,
|
|
428
|
+
mu: np.ndarray,
|
|
429
|
+
j,
|
|
430
|
+
):
|
|
431
|
+
"""Calculates the delta's from equation (20) for the column j (without q_j)"""
|
|
432
|
+
|
|
433
|
+
n = X.shape[0]
|
|
434
|
+
delta = np.full(n, np.inf)
|
|
435
|
+
unique_rows = np.unique(W, axis=0)
|
|
436
|
+
for w in unique_rows:
|
|
437
|
+
x = X[:, j]
|
|
438
|
+
row_idx_w = np.where(np.all(W == w, axis=1))[0] # rows with current w pattern
|
|
439
|
+
finite_rows = row_idx_w[np.isfinite(x[row_idx_w])] # row_idx_w with finite/not-nan x_j
|
|
440
|
+
if len(finite_rows) > 0: # if there are rows that aren't nans or infs
|
|
441
|
+
x = x[finite_rows] # the relevant entries
|
|
442
|
+
w1 = w.copy() # current W pattern
|
|
443
|
+
w0 = w.copy()
|
|
444
|
+
w0[j] = 0 # current W pattern, but W_ij is set to zero
|
|
445
|
+
if np.any(w0): # current W pattern contains nonzeros (without looking at j)
|
|
446
|
+
w1[j] = 1 # current W pattern, but W_ij is set to one
|
|
447
|
+
index_0 = np.nonzero(w0)[0] # ones in current W pattern (without j)
|
|
448
|
+
index_1 = np.nonzero(w1)[0]
|
|
449
|
+
mu_0 = mu[index_0]
|
|
450
|
+
mu_1 = mu[index_1]
|
|
451
|
+
sigma_1 = sigma[np.ix_(index_1, index_1)]
|
|
452
|
+
sigma_inv_0 = inverse_submatrix(sigma, sigma_inv, index_0)
|
|
453
|
+
|
|
454
|
+
jtemp = np.where(index_1 == j)[0] # current j in index 1
|
|
455
|
+
jtemp_n = np.where(index_1 != j)[0] # ones in index 1 (without j)
|
|
456
|
+
Xtemp = X[np.ix_(finite_rows, index_0)] - mu_0
|
|
457
|
+
x_hat = mu_1[jtemp] + (Xtemp @ sigma_inv_0 @ sigma_1[np.ix_(jtemp_n, jtemp)]).T
|
|
458
|
+
|
|
459
|
+
c = (
|
|
460
|
+
sigma_1[np.ix_(jtemp, jtemp)]
|
|
461
|
+
- sigma_1[np.ix_(jtemp, jtemp_n)]
|
|
462
|
+
@ sigma_inv_0
|
|
463
|
+
@ sigma_1[np.ix_(jtemp_n, jtemp)]
|
|
464
|
+
)
|
|
465
|
+
|
|
466
|
+
delta[finite_rows] = (x - x_hat) ** 2 / c + np.log(c) + np.log(2 * np.pi)
|
|
467
|
+
|
|
468
|
+
else: # current W pattern has zeros everywhere (except on j)
|
|
469
|
+
delta[finite_rows] = (
|
|
470
|
+
(x - mu[j]) ** 2 / sigma[j, j] + np.log(sigma[j, j]) + np.log(2 * np.pi)
|
|
471
|
+
)
|
|
472
|
+
|
|
473
|
+
return delta
|
|
474
|
+
|
|
475
|
+
def _predict_missing_values(
|
|
476
|
+
self,
|
|
477
|
+
X: np.ndarray,
|
|
478
|
+
predictions: np.ndarray,
|
|
479
|
+
conditional_variances: np.ndarray,
|
|
480
|
+
row_idx_w: np.array,
|
|
481
|
+
missing_col_idx: np.array,
|
|
482
|
+
observed_col_idx: np.array,
|
|
483
|
+
mu: np.array,
|
|
484
|
+
sigma: np.ndarray,
|
|
485
|
+
sigma_inv: np.ndarray,
|
|
486
|
+
):
|
|
487
|
+
"""Predict the missing values when there are both observed and missing values."""
|
|
488
|
+
|
|
489
|
+
sigma_observed_inv = inverse_submatrix(sigma, sigma_inv, observed_col_idx)
|
|
490
|
+
conditional_variance_missing = np.diag(
|
|
491
|
+
sigma[np.ix_(missing_col_idx, missing_col_idx)]
|
|
492
|
+
- sigma[np.ix_(missing_col_idx, observed_col_idx)]
|
|
493
|
+
@ sigma_observed_inv
|
|
494
|
+
@ sigma[np.ix_(observed_col_idx, missing_col_idx)]
|
|
495
|
+
)
|
|
496
|
+
|
|
497
|
+
# predict the missing values
|
|
498
|
+
for index in row_idx_w:
|
|
499
|
+
conditional_variances[np.ix_([index], missing_col_idx)] = conditional_variance_missing
|
|
500
|
+
predictions[np.ix_([index], missing_col_idx)] = (
|
|
501
|
+
mu[missing_col_idx]
|
|
502
|
+
+ (X[np.ix_([index], observed_col_idx)] - mu[observed_col_idx])
|
|
503
|
+
@ sigma_observed_inv
|
|
504
|
+
@ sigma[np.ix_(observed_col_idx, missing_col_idx)]
|
|
505
|
+
)
|
|
506
|
+
|
|
507
|
+
return predictions, conditional_variances
|
|
508
|
+
|
|
509
|
+
def _predict_observed_values(
|
|
510
|
+
self,
|
|
511
|
+
X: np.ndarray,
|
|
512
|
+
predictions: np.ndarray,
|
|
513
|
+
conditional_variances: np.ndarray,
|
|
514
|
+
row_idx_w: np.array,
|
|
515
|
+
observed_col_idx: np.array,
|
|
516
|
+
mu: np.array,
|
|
517
|
+
sigma: np.ndarray,
|
|
518
|
+
sigma_inv: np.ndarray,
|
|
519
|
+
):
|
|
520
|
+
"""Predict the observed values when there are both observed and missing values"""
|
|
521
|
+
|
|
522
|
+
if len(observed_col_idx) == 1: # only 1 observed value
|
|
523
|
+
for index in row_idx_w:
|
|
524
|
+
predictions[np.ix_([index], observed_col_idx)] = mu[observed_col_idx]
|
|
525
|
+
conditional_variances[np.ix_([index], observed_col_idx)] = sigma[
|
|
526
|
+
observed_col_idx, observed_col_idx
|
|
527
|
+
]
|
|
528
|
+
else: # multiple observed values
|
|
529
|
+
for obs in observed_col_idx:
|
|
530
|
+
other_observations = observed_col_idx[observed_col_idx != obs]
|
|
531
|
+
sigma_others_inv = inverse_submatrix(sigma, sigma_inv, other_observations)
|
|
532
|
+
conditional_variance_others = (
|
|
533
|
+
sigma[obs, obs]
|
|
534
|
+
- sigma[np.ix_([obs], other_observations)]
|
|
535
|
+
@ sigma_others_inv
|
|
536
|
+
@ sigma[np.ix_(other_observations, [obs])]
|
|
537
|
+
)
|
|
538
|
+
|
|
539
|
+
for index in row_idx_w:
|
|
540
|
+
predictions[index, obs] = (
|
|
541
|
+
mu[obs]
|
|
542
|
+
+ (X[np.ix_([index], other_observations)] - mu[other_observations])
|
|
543
|
+
@ sigma_others_inv
|
|
544
|
+
@ sigma[np.ix_(other_observations, [obs])]
|
|
545
|
+
)
|
|
546
|
+
conditional_variances[index, obs] = conditional_variance_others
|
|
547
|
+
|
|
548
|
+
return predictions, conditional_variances
|
|
549
|
+
|
|
550
|
+
def _predict_no_missing(
|
|
551
|
+
self,
|
|
552
|
+
X: np.ndarray,
|
|
553
|
+
predictions: np.ndarray,
|
|
554
|
+
conditional_variances: np.ndarray,
|
|
555
|
+
row_idx_w: np.array,
|
|
556
|
+
mu: np.array,
|
|
557
|
+
sigma: np.ndarray,
|
|
558
|
+
sigma_inv: np.ndarray,
|
|
559
|
+
):
|
|
560
|
+
"""Make predictions when no values in the w-pattern are missing."""
|
|
561
|
+
|
|
562
|
+
p = X.shape[1]
|
|
563
|
+
conditional_variance_nomissings = 1.0 / np.diag(sigma_inv)
|
|
564
|
+
for index in row_idx_w:
|
|
565
|
+
conditional_variances[index, :] = conditional_variance_nomissings
|
|
566
|
+
for j in range(p):
|
|
567
|
+
j_neg = np.arange(p)
|
|
568
|
+
j_neg = j_neg[j_neg != j]
|
|
569
|
+
sigma_jneg_inv = inverse_submatrix(sigma, sigma_inv, j_neg)
|
|
570
|
+
Xtemp = X[np.ix_(row_idx_w, j_neg)] - mu[j_neg]
|
|
571
|
+
predictions[np.ix_(row_idx_w, [j])] = (
|
|
572
|
+
mu[j] + Xtemp @ sigma_jneg_inv @ sigma[np.ix_(j_neg, [j])]
|
|
573
|
+
)
|
|
574
|
+
|
|
575
|
+
return predictions, conditional_variances
|
|
576
|
+
|
|
577
|
+
def _predict_all_missing(
|
|
578
|
+
self,
|
|
579
|
+
predictions: np.ndarray,
|
|
580
|
+
conditional_variances: np.ndarray,
|
|
581
|
+
row_idx_w: np.array,
|
|
582
|
+
mu: np.array,
|
|
583
|
+
sigma_inv: np.ndarray,
|
|
584
|
+
):
|
|
585
|
+
"""Make predictions when all values in the w-pattern are missing."""
|
|
586
|
+
for index in row_idx_w:
|
|
587
|
+
predictions[index, :] = mu
|
|
588
|
+
conditional_variances[index, :] = np.diag(sigma_inv)
|
|
589
|
+
|
|
590
|
+
return predictions, conditional_variances
|
|
591
|
+
|
|
592
|
+
def _check_data(self, X_scaled: np.ndarray):
|
|
593
|
+
"""Checks that there aren't too many nans or marginal outliers per column. Checks
|
|
594
|
+
that there are enough observations.
|
|
595
|
+
|
|
596
|
+
Arguments:
|
|
597
|
+
X_scaled (np.ndarray): robustly standardized data set."""
|
|
598
|
+
|
|
599
|
+
X = np.copy(X_scaled)
|
|
600
|
+
|
|
601
|
+
cutoff = np.sqrt(chi2.ppf(self.quantile, 1))
|
|
602
|
+
n_marginal_outliers = np.sum(np.abs(X) > cutoff, axis=0) / X.shape[0]
|
|
603
|
+
if np.max(n_marginal_outliers) > 1 - self.alpha:
|
|
604
|
+
raise ValueError(
|
|
605
|
+
f"\nAt least one variable has more than {100 * (1 - self.alpha)}% of "
|
|
606
|
+
"marginal outliers."
|
|
607
|
+
)
|
|
608
|
+
|
|
609
|
+
X[np.abs(X) > cutoff] = np.nan
|
|
610
|
+
n_bad_values = np.isnan(X).sum(axis=0) / X.shape[0]
|
|
611
|
+
if np.max(n_bad_values) > 1 - self.alpha:
|
|
612
|
+
raise ValueError(
|
|
613
|
+
f"\nAt least one variable has more than {100 * (1 - self.alpha)}% of nan's or "
|
|
614
|
+
"marginal outliers."
|
|
615
|
+
)
|
|
616
|
+
|
|
617
|
+
if X.shape[0] < 5 * X.shape[1]:
|
|
618
|
+
raise ValueError(
|
|
619
|
+
"There are not enough observations compared to the number of "
|
|
620
|
+
f"variables, n/p = {X.shape[0]/X.shape[1]} < 5."
|
|
621
|
+
)
|