robpy 0.1.1__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.
Files changed (57) hide show
  1. {robpy-0.1.1 → robpy-0.1.2}/PKG-INFO +1 -1
  2. {robpy-0.1.1 → robpy-0.1.2}/pyproject.toml +1 -1
  3. {robpy-0.1.1 → robpy-0.1.2}/robpy/outliers/ddc.py +169 -48
  4. {robpy-0.1.1 → robpy-0.1.2}/robpy/preprocessing/transfo.py +242 -142
  5. {robpy-0.1.1 → robpy-0.1.2}/LICENSE +0 -0
  6. {robpy-0.1.1 → robpy-0.1.2}/README.rst +0 -0
  7. {robpy-0.1.1 → robpy-0.1.2}/robpy/__init__.py +0 -0
  8. {robpy-0.1.1 → robpy-0.1.2}/robpy/covariance/__init__.py +0 -0
  9. {robpy-0.1.1 → robpy-0.1.2}/robpy/covariance/base.py +0 -0
  10. {robpy-0.1.1 → robpy-0.1.2}/robpy/covariance/cellmcd.py +0 -0
  11. {robpy-0.1.1 → robpy-0.1.2}/robpy/covariance/initial_ddcw.py +0 -0
  12. {robpy-0.1.1 → robpy-0.1.2}/robpy/covariance/kendall.py +0 -0
  13. {robpy-0.1.1 → robpy-0.1.2}/robpy/covariance/mcd.py +0 -0
  14. {robpy-0.1.1 → robpy-0.1.2}/robpy/covariance/ogk.py +0 -0
  15. {robpy-0.1.1 → robpy-0.1.2}/robpy/covariance/utils/alter_covariance.py +0 -0
  16. {robpy-0.1.1 → robpy-0.1.2}/robpy/covariance/utils/cellmcd_utils.py +0 -0
  17. {robpy-0.1.1 → robpy-0.1.2}/robpy/covariance/utils/cellmcd_visualization_utils.py +0 -0
  18. {robpy-0.1.1 → robpy-0.1.2}/robpy/covariance/wrapping.py +0 -0
  19. {robpy-0.1.1 → robpy-0.1.2}/robpy/datasets/__init__.py +0 -0
  20. {robpy-0.1.1 → robpy-0.1.2}/robpy/datasets/base.py +0 -0
  21. {robpy-0.1.1 → robpy-0.1.2}/robpy/datasets/data/animals.csv +0 -0
  22. {robpy-0.1.1 → robpy-0.1.2}/robpy/datasets/data/glass.csv +0 -0
  23. {robpy-0.1.1 → robpy-0.1.2}/robpy/datasets/data/stars.csv +0 -0
  24. {robpy-0.1.1 → robpy-0.1.2}/robpy/datasets/data/telephone.csv +0 -0
  25. {robpy-0.1.1 → robpy-0.1.2}/robpy/datasets/data/topgear.csv +0 -0
  26. {robpy-0.1.1 → robpy-0.1.2}/robpy/datasets/descr/animals.rst +0 -0
  27. {robpy-0.1.1 → robpy-0.1.2}/robpy/datasets/descr/glass.rst +0 -0
  28. {robpy-0.1.1 → robpy-0.1.2}/robpy/datasets/descr/stars.rst +0 -0
  29. {robpy-0.1.1 → robpy-0.1.2}/robpy/datasets/descr/telephone.rst +0 -0
  30. {robpy-0.1.1 → robpy-0.1.2}/robpy/datasets/descr/topgear.rst +0 -0
  31. {robpy-0.1.1 → robpy-0.1.2}/robpy/outliers/__init__.py +0 -0
  32. {robpy-0.1.1 → robpy-0.1.2}/robpy/pca/__init__.py +0 -0
  33. {robpy-0.1.1 → robpy-0.1.2}/robpy/pca/base.py +0 -0
  34. {robpy-0.1.1 → robpy-0.1.2}/robpy/pca/robpca.py +0 -0
  35. {robpy-0.1.1 → robpy-0.1.2}/robpy/pca/spca.py +0 -0
  36. {robpy-0.1.1 → robpy-0.1.2}/robpy/preprocessing/__init__.py +0 -0
  37. {robpy-0.1.1 → robpy-0.1.2}/robpy/preprocessing/data_cleaner.py +0 -0
  38. {robpy-0.1.1 → robpy-0.1.2}/robpy/preprocessing/scaling.py +0 -0
  39. {robpy-0.1.1 → robpy-0.1.2}/robpy/preprocessing/utils.py +0 -0
  40. {robpy-0.1.1 → robpy-0.1.2}/robpy/regression/__init__.py +0 -0
  41. {robpy-0.1.1 → robpy-0.1.2}/robpy/regression/base.py +0 -0
  42. {robpy-0.1.1 → robpy-0.1.2}/robpy/regression/lts.py +0 -0
  43. {robpy-0.1.1 → robpy-0.1.2}/robpy/regression/mm.py +0 -0
  44. {robpy-0.1.1 → robpy-0.1.2}/robpy/regression/s.py +0 -0
  45. {robpy-0.1.1 → robpy-0.1.2}/robpy/univariate/__init__.py +0 -0
  46. {robpy-0.1.1 → robpy-0.1.2}/robpy/univariate/adjusted_boxplot.py +0 -0
  47. {robpy-0.1.1 → robpy-0.1.2}/robpy/univariate/base.py +0 -0
  48. {robpy-0.1.1 → robpy-0.1.2}/robpy/univariate/mcd.py +0 -0
  49. {robpy-0.1.1 → robpy-0.1.2}/robpy/univariate/onestep_m.py +0 -0
  50. {robpy-0.1.1 → robpy-0.1.2}/robpy/univariate/qn.py +0 -0
  51. {robpy-0.1.1 → robpy-0.1.2}/robpy/univariate/tau.py +0 -0
  52. {robpy-0.1.1 → robpy-0.1.2}/robpy/utils/distance.py +0 -0
  53. {robpy-0.1.1 → robpy-0.1.2}/robpy/utils/general.py +0 -0
  54. {robpy-0.1.1 → robpy-0.1.2}/robpy/utils/logging.py +0 -0
  55. {robpy-0.1.1 → robpy-0.1.2}/robpy/utils/median.py +0 -0
  56. {robpy-0.1.1 → robpy-0.1.2}/robpy/utils/outlyingness.py +0 -0
  57. {robpy-0.1.1 → robpy-0.1.2}/robpy/utils/rho.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: robpy
3
- Version: 0.1.1
3
+ Version: 0.1.2
4
4
  Summary:
5
5
  License-File: LICENSE
6
6
  Author: Thomas Servotte
@@ -1,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "robpy"
3
- version = "0.1.1" # versioning is done by poetry-dynamic-versioning
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"
@@ -32,6 +32,9 @@ class DDC(OutlierMixin):
32
32
  chi2_quantile: float = 0.99,
33
33
  min_correlation: float = 0.5,
34
34
  scale_estimator: RobustScale = CellwiseOneStepM(),
35
+ min_unique_values: int = 3,
36
+ predictor_columns: list | None = None,
37
+ predictor_min_correlation: float | None = None,
35
38
  ):
36
39
  """
37
40
  Implementation of the Detecting Deviating Cells (DDC) algorithm. Based on the R
@@ -41,10 +44,41 @@ class DDC(OutlierMixin):
41
44
  chi2_quantile (float, optional): Quantile of the chi-squared distribution to use as
42
45
  threshold for univariate outlier detection in step 2.
43
46
  Default is 0.99.
44
- min_correlation (float, optional): Minimum correlation between variables to consider
45
- them. Default is 0.5.
47
+ min_correlation (float, optional): Minimum absolute correlation between two
48
+ variables for one to be used in the prediction of the other. Default is 0.5.
46
49
  scale_estimator (RobustScale, optional) : robust scale estimator to scale the
47
50
  initial data with. Defaults to CellwiseOneStepM().
51
+ min_unique_values (int, optional): Columns with this many or fewer distinct values
52
+ are considered discrete and are not supported (as ``numDiscrete`` in cellWise),
53
+ except as predictor columns. Defaults to 3.
54
+ predictor_columns (list | None, optional): Labels of columns of X that are known to
55
+ be clean and only serve to predict the other (target) columns, e.g. a binary
56
+ treatment indicator. These columns are never flagged or imputed and may be
57
+ discrete, but must be numeric, non-constant and without missing values. They are
58
+ standardized with their mean and standard deviation instead of
59
+ ``scale_estimator``, are not subject to the univariate outlier detection of step
60
+ 2, and their correlation with a target column is the Pearson correlation over the
61
+ cells of the target column that survive step 2. Their standardized residuals and
62
+ predictions are nan, and they are blank in ``cellmap``. This is an extension of
63
+ DDC, not part of the published algorithm or of cellWise. Defaults to None (no
64
+ predictor columns), which gives the original DDC.
65
+ predictor_min_correlation (float | None, optional): Minimum absolute correlation
66
+ between a predictor column and a target column for the predictor column to be
67
+ used in the prediction of the target column. A discrete predictor is typically
68
+ less correlated with a continuous variable than continuous variables are among
69
+ each other, so a lower value than ``min_correlation`` can be appropriate.
70
+ Defaults to None, which uses ``min_correlation``.
71
+
72
+ Attributes:
73
+ cellwise_outliers_ (np.ndarray): Boolean array (n_samples, n_features), True for
74
+ flagged cells.
75
+ standardized_residuals_ (np.ndarray): Standardized residuals of the cells of the
76
+ training data.
77
+ row_outliers_ (np.ndarray): Boolean array (n_samples,), True for flagged rows.
78
+ robust_correlation_ (np.ndarray): Robust correlation matrix of the variables (nan
79
+ for pairs of predictor columns, which are not needed).
80
+ predictor_mask_ (np.ndarray): Boolean array (n_features,), True for the predictor
81
+ columns.
48
82
 
49
83
  References:
50
84
  - Rousseeuw, P. J., & Van den Bossche, W. (2018). Detecting deviating data cells.
@@ -55,19 +89,19 @@ class DDC(OutlierMixin):
55
89
  self.cutoff = np.sqrt(chi2.ppf(chi2_quantile, df=1))
56
90
  self.min_correlation = min_correlation
57
91
  self.scale_estimator = scale_estimator
92
+ self.min_unique_values = min_unique_values
93
+ self.predictor_columns = predictor_columns
94
+ self.predictor_min_correlation = predictor_min_correlation
58
95
 
59
96
  def fit(self, X: pd.DataFrame, y=None, verbose: bool = False):
60
- self._check_data_conditions(X)
61
97
  X = X.replace([np.inf, -np.inf], np.nan)
98
+ self._check_data_conditions(X)
99
+ self.feature_names_in_ = np.asarray(X.columns, dtype=object)
62
100
  # step 1: standardization
63
101
  self._fit_scaler(X)
64
102
  Z = self._standardize(X)
65
103
  # step 2: univariate outlier detection
66
- U = pd.DataFrame(
67
- data=np.where(np.abs(Z) > self.cutoff, np.nan, Z),
68
- columns=X.columns,
69
- index=X.index,
70
- )
104
+ U = self._univariate_outliers(Z)
71
105
  # step 3: correlation matrix and slopes
72
106
  self.robust_correlation_ = self._robust_correlation(U, verbose=verbose)
73
107
  self.slopes_ = self._get_slopes(U)
@@ -78,9 +112,13 @@ class DDC(OutlierMixin):
78
112
  # step 5: deshrinkage
79
113
  self.deshrinkage_ = np.array(
80
114
  [
81
- self._robust_slope(
82
- self.raw_predictions_[~np.isnan(Z.iloc[:, i]), i],
83
- Z.to_numpy()[~np.isnan(Z.iloc[:, i]), i],
115
+ (
116
+ np.nan
117
+ if self.predictor_mask_[i]
118
+ else self._robust_slope(
119
+ self.raw_predictions_[~np.isnan(Z.iloc[:, i]), i],
120
+ Z.to_numpy()[~np.isnan(Z.iloc[:, i]), i],
121
+ )
84
122
  )
85
123
  for i in range(X.shape[1])
86
124
  ]
@@ -138,25 +176,45 @@ class DDC(OutlierMixin):
138
176
 
139
177
  def _predict_cells(self, X: pd.DataFrame) -> tuple[np.ndarray, np.ndarray]:
140
178
  """Cellwise outlier flags and standardized residuals for (new) data."""
141
- if not self.is_fitted_:
179
+ X = self._check_new_data(X, "Predict")
180
+ # step 1: standardization
181
+ Z = self._standardize(X)
182
+ U = self._univariate_outliers(Z)
183
+ predictions = self._get_predicted_values(U) * self.deshrinkage_
184
+ return self._cellwise_outliers(Z, predictions)
185
+
186
+ def _check_new_data(self, X: pd.DataFrame, method: str) -> pd.DataFrame:
187
+ """Check new data passed to predict / impute and replace infinite values by nan."""
188
+ if not getattr(self, "is_fitted_", False):
142
189
  raise ValueError("Model not fitted yet.")
143
190
  if not X.shape[1] == self.cellwise_outliers_.shape[1]:
144
191
  raise ValueError(
145
- f"Predict can only be called with the same data as fit. "
192
+ f"{method} can only be called with the same data as fit. "
146
193
  f"Received {X.shape[1]} columns, expected {self.cellwise_outliers_.shape[1]}"
147
194
  )
148
195
  if X.select_dtypes(include=np.number).shape != X.shape:
149
196
  raise ValueError("Only numerical data is supported.")
150
197
  X = X.replace([np.inf, -np.inf], np.nan)
151
- # step 1: standardization
152
- Z = self._standardize(X)
153
- U = pd.DataFrame(
154
- data=np.where(np.abs(Z) > self.cutoff, np.nan, Z),
155
- columns=X.columns,
156
- index=X.index,
198
+ if self.predictor_mask_.any():
199
+ if list(X.columns) != list(self.feature_names_in_):
200
+ raise ValueError(
201
+ "With predictor_columns, X must have the same columns as in fit, in the "
202
+ "same order."
203
+ )
204
+ missing = X.columns[self.predictor_mask_ & X.isna().any(axis=0).to_numpy()]
205
+ if len(missing) > 0:
206
+ raise ValueError(
207
+ f"Predictor columns cannot contain missing values: {list(missing)}."
208
+ )
209
+ return X
210
+
211
+ def _univariate_outliers(self, Z: pd.DataFrame) -> pd.DataFrame:
212
+ """Step 2: set standardized cells beyond the cutoff to nan (not in predictor columns)."""
213
+ return pd.DataFrame(
214
+ data=np.where((np.abs(Z) > self.cutoff) & ~self.predictor_mask_, np.nan, Z),
215
+ columns=Z.columns,
216
+ index=Z.index,
157
217
  )
158
- predictions = self._get_predicted_values(U) * self.deshrinkage_
159
- return self._cellwise_outliers(Z, predictions)
160
218
 
161
219
  def _cellwise_outliers(
162
220
  self, Z: pd.DataFrame, predictions: np.ndarray, fit: bool = False
@@ -177,9 +235,13 @@ class DDC(OutlierMixin):
177
235
  if fit:
178
236
  self.residual_scales = np.array(
179
237
  [
180
- CellwiseOneStepM()
181
- .fit(raw_residuals[:, i][~np.isnan(raw_residuals[:, i])])
182
- .scale
238
+ (
239
+ np.nan
240
+ if self.predictor_mask_[i]
241
+ else CellwiseOneStepM()
242
+ .fit(raw_residuals[:, i][~np.isnan(raw_residuals[:, i])])
243
+ .scale
244
+ )
183
245
  for i in range(raw_residuals.shape[1])
184
246
  ]
185
247
  )
@@ -210,21 +272,20 @@ class DDC(OutlierMixin):
210
272
  return row_outliers
211
273
 
212
274
  def impute(self, X: pd.DataFrame, impute_outliers: bool = True) -> pd.DataFrame:
213
- if not self.is_fitted_:
214
- raise ValueError("Model not fitted yet.")
215
- if X.shape[1] != self.cellwise_outliers_.shape[1]:
216
- raise ValueError(
217
- f"Impute can only be called with the same data as fit. "
218
- f"Received {X.shape[1]} columns, expected {self.cellwise_outliers_.shape[1]}"
219
- )
220
- X = X.replace([np.inf, -np.inf], np.nan)
275
+ """Replace missing (and, optionally, flagged) cells by their DDC predictions.
276
+
277
+ Args:
278
+ X (pd.DataFrame): Data with the same columns as the data used in fit.
279
+ impute_outliers (bool, optional): Whether to also impute the cells flagged by
280
+ `predict`. Defaults to True.
281
+
282
+ Returns:
283
+ pd.DataFrame: X with imputed cells. Predictor columns are returned unchanged.
284
+ """
285
+ X = self._check_new_data(X, "Impute")
221
286
  Z = self._standardize(X)
222
287
  # step 2: univariate outlier detection
223
- U = pd.DataFrame(
224
- data=np.where(np.abs(Z) > self.cutoff, np.nan, Z),
225
- columns=X.columns,
226
- index=X.index,
227
- )
288
+ U = self._univariate_outliers(Z)
228
289
  raw_predictions = self._get_predicted_values(U)
229
290
  predictions = raw_predictions * self.deshrinkage_
230
291
  rescaled_predictions = predictions * self.scale_ + self.location_
@@ -256,7 +317,8 @@ class DDC(OutlierMixin):
256
317
  cmap: str | matplotlib.colors.Colormap = "custom",
257
318
  ) -> Axes:
258
319
  """
259
- Visualize the standardized residuals of the DDC model as a heatmap.
320
+ Visualize the standardized residuals of the DDC model as a heatmap. Predictor columns
321
+ (see `predictor_columns`) have no residuals and are shown blank.
260
322
 
261
323
  Args:
262
324
  X (pd.DataFrame): The data used to predict the residuals.
@@ -281,7 +343,7 @@ class DDC(OutlierMixin):
281
343
  Returns:
282
344
  Axes: The matplotlib axes with the heatmap.
283
345
  """
284
- if not self.is_fitted_:
346
+ if not getattr(self, "is_fitted_", False):
285
347
  raise ValueError("Model not fitted yet.")
286
348
  if cmap == "custom":
287
349
  cmap = get_custom_cmap(vmax_clip)
@@ -323,13 +385,46 @@ class DDC(OutlierMixin):
323
385
  def _check_data_conditions(self, X: pd.DataFrame):
324
386
  if X.select_dtypes(include=np.number).shape != X.shape:
325
387
  raise ValueError("Only numerical data is supported.")
326
- if any(X.nunique() <= 3):
327
- raise ValueError("Columns with less than 3 unique values are not supported.")
388
+ self.predictor_mask_ = self._get_predictor_mask(X)
389
+ if self.predictor_mask_.all():
390
+ raise ValueError("At least one column must not be a predictor column.")
391
+ predictors = X.loc[:, self.predictor_mask_]
392
+ with_nan = predictors.columns[predictors.isna().any(axis=0)]
393
+ if len(with_nan) > 0:
394
+ raise ValueError(f"Predictor columns cannot contain missing values: {list(with_nan)}.")
395
+ constant = predictors.columns[predictors.nunique() <= 1]
396
+ if len(constant) > 0:
397
+ raise ValueError(f"Predictor columns cannot be constant: {list(constant)}.")
398
+ targets = X.loc[:, ~self.predictor_mask_]
399
+ discrete = targets.columns[targets.nunique() <= self.min_unique_values]
400
+ if len(discrete) > 0:
401
+ raise ValueError(
402
+ f"Columns with {self.min_unique_values} or fewer unique values are not supported "
403
+ f"(see min_unique_values), except as predictor columns: {list(discrete)}."
404
+ )
405
+
406
+ def _get_predictor_mask(self, X: pd.DataFrame) -> np.ndarray:
407
+ """Boolean array (n_features,) marking the predictor columns."""
408
+ names = self.predictor_columns
409
+ if names is None:
410
+ return np.zeros(X.shape[1], dtype=bool)
411
+ if isinstance(names, str) or not np.iterable(names):
412
+ names = [names]
413
+ unknown = [name for name in names if name not in X.columns]
414
+ if unknown:
415
+ raise ValueError(f"Unknown predictor columns: {unknown}.")
416
+ return np.asarray(X.columns.isin(names))
328
417
 
329
418
  def _fit_scaler(self, X: pd.DataFrame):
330
419
  self.location_, self.scale_ = [], []
331
420
  for i in range(X.shape[1]):
332
- est = self.scale_estimator.fit(X.iloc[:, i].to_numpy()[~np.isnan(X.iloc[:, i])])
421
+ x = X.iloc[:, i].to_numpy()
422
+ if self.predictor_mask_[i]:
423
+ # predictor columns are clean and may be discrete: classical standardization
424
+ self.location_.append(np.mean(x))
425
+ self.scale_.append(np.std(x, ddof=1))
426
+ continue
427
+ est = self.scale_estimator.fit(x[~np.isnan(x)])
333
428
  self.location_.append(est.location)
334
429
  self.scale_.append(est.scale)
335
430
 
@@ -351,17 +446,28 @@ class DDC(OutlierMixin):
351
446
  """
352
447
  correlation = np.ones((X.shape[1], X.shape[1]))
353
448
  for i in range(X.shape[1]):
354
- if verbose and i % (X.shape[1] // 10) == 0:
449
+ if verbose and i % max(X.shape[1] // 10, 1) == 0:
355
450
  print(
356
451
  f"Correlation: Processing column {i + 1} of {X.shape[1]} "
357
452
  f"({((i + 1) / X.shape[1]):.1%})"
358
453
  )
359
454
  for j in range(i + 1, X.shape[1]):
455
+ if self.predictor_mask_[i] and self.predictor_mask_[j]:
456
+ # not needed: predictor columns are not predicted
457
+ correlation[i, j] = correlation[j, i] = np.nan
458
+ continue
360
459
  xy = X.iloc[:, [i, j]].values
361
460
  xy = xy[~(np.isnan(xy).any(axis=1)), :]
362
461
  if xy.size == 0:
363
462
  correlation[i, j] = correlation[j, i] = 0
364
463
  continue
464
+ if self.predictor_mask_[i] or self.predictor_mask_[j]:
465
+ # a predictor column can be discrete, so its joint distribution with a target
466
+ # column is not elliptical: Pearson correlation on the cells of the target
467
+ # column that survived step 2 (point-biserial for a binary predictor)
468
+ r = np.corrcoef(xy, rowvar=False)[0, 1] if len(xy) > 2 else np.nan
469
+ correlation[i, j] = correlation[j, i] = 0 if np.isnan(r) else r
470
+ continue
365
471
  x, y = xy.T
366
472
  xy_corr = np.clip(
367
473
  (
@@ -391,28 +497,43 @@ class DDC(OutlierMixin):
391
497
 
392
498
  return np.linalg.lstsq(x[mask].reshape(-1, 1), y[mask], rcond=None)[0][0]
393
499
 
500
+ def _min_correlations(self) -> np.ndarray:
501
+ """Per column: minimum absolute correlation for using it to predict another column."""
502
+ predictor_min_correlation = (
503
+ self.min_correlation
504
+ if self.predictor_min_correlation is None
505
+ else self.predictor_min_correlation
506
+ )
507
+ return np.where(self.predictor_mask_, predictor_min_correlation, self.min_correlation)
508
+
394
509
  def _get_slopes(self, X: pd.DataFrame) -> np.ndarray:
510
+ """slopes[i, j] is the slope for predicting column j from column i."""
395
511
  slopes = np.full((X.shape[1], X.shape[1]), np.nan)
512
+ min_correlations = self._min_correlations()
396
513
  for i in range(X.shape[1]):
397
514
  for j in range(X.shape[1]):
398
- if i == j:
515
+ if i == j or self.predictor_mask_[j]:
516
+ continue
517
+ xy_corr = self.robust_correlation_[i, j]
518
+ if np.abs(xy_corr) < min_correlations[i]:
399
519
  continue
400
520
  xy = X.iloc[:, [i, j]].values
401
521
  xy = xy[(~np.isnan(xy).any(axis=1)), :].T
402
522
  x, y = xy
403
- xy_corr = self.robust_correlation_[i, j]
404
- if np.abs(xy_corr) < self.min_correlation:
405
- continue
406
523
  slopes[i, j] = self._robust_slope(x, y)
407
524
  return slopes
408
525
 
409
526
  def _get_predicted_values(self, X: pd.DataFrame) -> np.ndarray:
527
+ """Raw predictions of all cells (0 for predictor columns, which are not predicted)."""
410
528
  predictions = np.zeros(X.shape)
529
+ min_correlations = self._min_correlations()
411
530
  for i in range(X.shape[1]):
531
+ if self.predictor_mask_[i]:
532
+ continue
412
533
  weights = np.repeat(
413
534
  [
414
535
  [
415
- np.abs(r) * (np.abs(r) >= 0.5) * (idx != i)
536
+ np.abs(r) * (np.abs(r) >= min_correlations[idx]) * (idx != i)
416
537
  for idx, r in enumerate(self.robust_correlation_[:, i])
417
538
  ]
418
539
  ],
@@ -20,21 +20,59 @@ class RobustPowerTransformer(OneToOneFeatureMixin, TransformerMixin, BaseEstimat
20
20
  lambda_range: tuple[float, float] = (-4.0, 6.0),
21
21
  quantile: float = 0.99,
22
22
  nsteps: int = 2,
23
+ rectified: bool = False,
23
24
  ):
24
25
  """
25
26
  Apply a robust power transformation using reweighted maximum likelihood to transform the
26
27
  features closer to normality. Uses the Box-Cox or the Yeo-Johnson transformation.
27
28
 
29
+ The transformation parameter lambda is estimated as in Raymaekers & Rousseeuw (2024): an
30
+ initial estimate from the rectified transformation, followed by ``nsteps`` steps of
31
+ reweighted maximum likelihood, in which observations whose robustly standardized
32
+ transformed value exceeds ``sqrt(chi2_1(quantile))`` get weight 0. This follows the
33
+ reference implementation ``transfo`` in the R package cellWise.
34
+
28
35
  Args:
29
36
  method (Literal str, optional): Method used for the power transformation.
30
37
  Can be "boxcox" for Box-Cox, "yeojohnson" for Yeo-Johnson, or "auto"
31
38
  for the solution with the lowest objective function. Box-Cox can only be used for
32
- strictly positive features. Defaults to "auto".
39
+ strictly positive features. Defaults to "yeojohnson".
33
40
  standardize (boolean, optional): Whether to standardize the features before and after
34
41
  the power transformation. Defaults to True.
42
+ lambda_range (tuple[float, float], optional): Initial search range for lambda; must
43
+ contain 1. If the estimate lies close to a bound, that bound is moved away from 1
44
+ (its distance to 1 is doubled) and the fit is repeated. Defaults to (-4.0, 6.0).
35
45
  quantile (float, optional): Quantile used to calculate the weights. Defaults to 0.99.
36
46
  nsteps (int, optional): Number of steps used in the reweighted maximum likelihood.
37
47
  Defaults to 2.
48
+ rectified (bool, optional): Whether ``transform`` and ``inverse_transform`` use the
49
+ rectified transformation with the fitted lambda instead of the classical one.
50
+ The rectified transformation equals the classical one up to a change point
51
+ (``changepoint_``, determined from the quartiles of the training data) and
52
+ continues linearly beyond it. For lambda < 1 the classical transformation
53
+ compresses the upper tail (and for lambda > 1 the lower tail), which can move
54
+ outliers into the bulk of the transformed data; the rectified version keeps
55
+ them outlying, which helps when outliers are detected after the
56
+ transformation (e.g. with DDC). The estimate of lambda does not depend on this
57
+ option. Note that the rectified transformation of the clean data is not
58
+ exactly the maximum likelihood transformation. Defaults to False, which gives
59
+ the transformation of the paper and of cellWise.
60
+
61
+ Attributes:
62
+ lambda_rew (float): The reweighted estimate of lambda.
63
+ method (str): The transformation used ("boxcox" or "yeojohnson"; "auto" is resolved
64
+ during fit).
65
+ changepoint_ (float | None): Change point of the rectified transformation for the
66
+ fitted lambda, on the scale of the (pre-standardized) data, or None when
67
+ lambda equals 1. Only set when ``rectified`` is True.
68
+ location_pre (float): Location (median) subtracted before the Yeo-Johnson
69
+ transformation (only when ``standardize`` is True).
70
+ scale_pre (float): Scale (MAD for Yeo-Johnson, median for Box-Cox) divided by
71
+ before the transformation (only when ``standardize`` is True).
72
+ location_post (float): Mean of the transformed observations with weight 1,
73
+ subtracted after the transformation (only when ``standardize`` is True).
74
+ scale_post (float): Standard deviation of the transformed observations with weight
75
+ 1, divided by after the transformation (only when ``standardize`` is True).
38
76
 
39
77
  References:
40
78
  - Raymaekers, J., & Rousseeuw, P. J. (2024). Transforming variables to central
@@ -42,9 +80,10 @@ class RobustPowerTransformer(OneToOneFeatureMixin, TransformerMixin, BaseEstimat
42
80
  """
43
81
  self.method = method
44
82
  self.standardize = standardize
45
- self.lambda_range = list(lambda_range)
83
+ self.lambda_range = lambda_range
46
84
  self.quantile = quantile
47
85
  self.nsteps = nsteps
86
+ self.rectified = rectified
48
87
  self.logger = logging.getLogger("RobustPowerTransformer")
49
88
 
50
89
  def fit(self, x: np.ndarray):
@@ -53,167 +92,200 @@ class RobustPowerTransformer(OneToOneFeatureMixin, TransformerMixin, BaseEstimat
53
92
  Args:
54
93
  x (np.ndarray): The data.
55
94
  """
56
-
95
+ x = np.asarray(x, dtype=float)
57
96
  self._get_method(x)
97
+ if not (len(self.lambda_range) == 2 and self.lambda_range[0] < 1 < self.lambda_range[1]):
98
+ raise ValueError("lambda_range must be a pair (low, high) with low < 1 < high.")
58
99
  x_sorted = np.sort(x)
59
100
 
60
101
  if self.method in ["boxcox", "auto"]:
61
- lambda_boxcox, mu_rew_boxcox, sd_rew_boxcox, scale_boxcox = self._fit_boxcox(x_sorted)
62
- if self.method == "auto":
63
- crit_val_boxcox = self._robnormality(x, "boxcox", lambda_boxcox)
64
-
102
+ fit_boxcox = self._fit_boxcox(x_sorted)
65
103
  if self.method in ["yeojohnson", "auto"]:
66
- (
67
- lambda_yeojohnson,
68
- mu_rew_yeojohnson,
69
- sd_rew_yeojohnson,
70
- loc_yeojohnson,
71
- scale_yeojohnson,
72
- ) = self._fit_yeojohnson(x_sorted)
73
- if self.method == "auto":
74
- crit_val_yeojohnson = self._robnormality(x, "yeojohnson", lambda_yeojohnson)
104
+ fit_yeojohnson = self._fit_yeojohnson(x_sorted)
75
105
 
76
106
  if self.method == "auto":
77
- if crit_val_boxcox < crit_val_yeojohnson:
78
- self.method = "boxcox"
79
- else:
80
- self.method = "yeojohnson"
81
-
82
- if self.method == "boxcox":
83
- if self.standardize:
84
- self.scale_pre = scale_boxcox
85
- self.location_post = mu_rew_boxcox
86
- self.scale_post = sd_rew_boxcox
87
- self.lambda_rew = lambda_boxcox
88
- else: # yeojohnson
89
- if self.standardize:
90
- self.location_pre = loc_yeojohnson
91
- self.scale_pre = scale_yeojohnson
92
- self.location_post = mu_rew_yeojohnson
93
- self.scale_post = sd_rew_yeojohnson
94
- self.lambda_rew = lambda_yeojohnson
107
+ crit_val_boxcox = self._robnormality(x, "boxcox", fit_boxcox["lambda"])
108
+ crit_val_yeojohnson = self._robnormality(x, "yeojohnson", fit_yeojohnson["lambda"])
109
+ self.method = "boxcox" if crit_val_boxcox < crit_val_yeojohnson else "yeojohnson"
110
+
111
+ result = fit_boxcox if self.method == "boxcox" else fit_yeojohnson
112
+ self.lambda_rew = result["lambda"]
113
+ if self.standardize:
114
+ if self.method == "yeojohnson":
115
+ self.location_pre = result["location_pre"]
116
+ self.scale_pre = result["scale_pre"]
117
+ self.location_post = result["location_post"]
118
+ self.scale_post = result["scale_post"]
119
+ if self.rectified:
120
+ self.changepoint_ = result["changepoint"]
95
121
 
96
122
  return self
97
123
 
98
124
  def transform(self, x: np.ndarray) -> np.ndarray:
99
125
  """Transforms the data using the calculated lambda estimate and the corresponding method.
100
126
 
127
+ Uses the rectified transformation if ``rectified`` is True.
128
+
101
129
  Args:
102
130
  x (np.ndarray): The data.
103
131
  """
104
-
105
- if self.method == "boxcox":
106
- if np.min(x) <= 0:
107
- raise ValueError(
108
- "The data is not strictly positive. Box-Cox transformation "
109
- "cannot be applied."
110
- )
111
- if self.standardize:
112
- x = x / self.scale_pre
113
- x = self._transf_boxcox(x, self.lambda_rew)[0]
114
- if self.standardize:
115
- x = (x - self.location_post) / self.scale_post
116
- else: # yeojohnson
117
- if self.standardize:
118
- x = (x - self.location_pre) / self.scale_pre
119
- x = self._transf_yeojohnson(x, self.lambda_rew)[0]
120
- if self.standardize:
121
- x = (x - self.location_post) / self.scale_post
122
-
132
+ x = np.asarray(x, dtype=float)
133
+ if self.method == "boxcox" and np.min(x) <= 0:
134
+ raise ValueError(
135
+ "The data is not strictly positive. Box-Cox transformation cannot be applied."
136
+ )
137
+ x = self._standardize_pre(x)
138
+ x = self._transform_standardized(
139
+ x, self.method, self.lambda_rew, self._fitted_changepoint()
140
+ )
141
+ if self.standardize:
142
+ x = (x - self.location_post) / self.scale_post
123
143
  return x
124
144
 
125
145
  def inverse_transform(self, x: np.ndarray) -> np.ndarray:
126
146
  """Transforms the data back using inverse Yeo-Johnson/Box-Cox. The previously fitted lambda
127
- estimate and the corresponding method are used.
147
+ estimate and the corresponding method are used (rectified if ``rectified`` is True).
128
148
 
129
149
  Args:
130
150
  x (np.ndarray): The data.
131
151
  """
152
+ x = np.asarray(x, dtype=float)
153
+ if self.standardize:
154
+ x = x * self.scale_post + self.location_post
132
155
 
156
+ changepoint = self._fitted_changepoint()
157
+ if changepoint is None:
158
+ classical = np.ones(x.shape, dtype=bool)
159
+ else:
160
+ changepoint_transf, slope, upper = self._rectified_linear_part(
161
+ changepoint, self.method, self.lambda_rew
162
+ )
163
+ classical = x <= changepoint_transf if upper else x >= changepoint_transf
164
+ xt = np.empty_like(x)
165
+ x_classical = self._handle_bounds(x[classical])
133
166
  if self.method == "boxcox":
134
- if self.standardize:
135
- x = x * self.scale_post + self.location_post
136
- x = self._handle_bounds(x)
137
- x = self._inv_transf_boxcox(x, self.lambda_rew)
138
- if self.standardize:
139
- x = x * self.scale_pre
140
-
141
- else: # yeojohnson
142
- if self.standardize:
143
- x = x * self.scale_post + self.location_post
144
- x = self._handle_bounds(x)
145
- x = self._inv_transf_yeojohnson(x, self.lambda_rew)
146
- if self.standardize:
147
- x = x * self.scale_pre + self.location_pre
167
+ xt[classical] = self._inv_transf_boxcox(x_classical, self.lambda_rew)
168
+ else:
169
+ xt[classical] = self._inv_transf_yeojohnson(x_classical, self.lambda_rew)
170
+ if changepoint is not None:
171
+ xt[~classical] = changepoint + (x[~classical] - changepoint_transf) / slope
148
172
 
149
- return x
173
+ if self.standardize:
174
+ if self.method == "boxcox":
175
+ xt = xt * self.scale_pre
176
+ else:
177
+ xt = xt * self.scale_pre + self.location_pre
150
178
 
151
- def _fit_boxcox(self, x: np.ndarray):
152
- """Fits the Box-Cox power transformation.
179
+ return xt
153
180
 
154
- Args:
155
- x (np.ndarray): The data.
156
- """
157
- lambdarange = self.lambda_range
158
- converged = False
159
- while not converged:
160
- if self.standardize:
161
- scale_boxcox = np.median(x)
162
- x = x / scale_boxcox
163
- else:
164
- scale_boxcox = None
165
- lambda_raw = self._calculate_lambda_0(x, "boxcox_rect", lambdarange)
166
- lambda_rew, mu_rew_boxcox, sd_rew_boxcox = self._reweighted_max_likelihood_robust(
167
- x,
168
- lambda_raw,
169
- "boxcox",
170
- lambdarange,
171
- self.quantile,
172
- self.nsteps,
173
- )
174
- converged = np.min(np.abs(lambda_rew - lambdarange)) > np.diff(lambdarange) * 0.05
175
- if not converged:
176
- lambdarange = 1 + (lambdarange - 1) * (
177
- 1 + (abs(lambda_rew - lambdarange) == min(abs(lambda_rew - lambdarange)))
178
- )
181
+ def _standardize_pre(self, x: np.ndarray) -> np.ndarray:
182
+ """Standardization applied before the power transformation."""
183
+ if not self.standardize:
184
+ return x
185
+ if self.method == "boxcox":
186
+ return x / self.scale_pre
187
+ return (x - self.location_pre) / self.scale_pre
179
188
 
180
- return lambda_rew, mu_rew_boxcox, sd_rew_boxcox, scale_boxcox
189
+ def _fitted_changepoint(self) -> float | None:
190
+ """Change point used by transform / inverse_transform (None: classical)."""
191
+ return getattr(self, "changepoint_", None) if self.rectified else None
181
192
 
182
- def _fit_yeojohnson(self, x: np.ndarray):
183
- """Fits the Yeo-Johnson power transformation.
193
+ def _transform_standardized(
194
+ self,
195
+ x: np.ndarray,
196
+ transf: Literal["boxcox", "yeojohnson"],
197
+ my_lambda: float,
198
+ changepoint: float | None = None,
199
+ ) -> np.ndarray:
200
+ """Classical transformation, or the rectified one with the given change point."""
201
+ if transf == "boxcox":
202
+ if changepoint is None:
203
+ return self._transf_boxcox(x, my_lambda)[0]
204
+ return self._transf_boxcox_rectified(x, my_lambda, changepoint=changepoint)[0]
205
+ if changepoint is None:
206
+ return self._transf_yeojohnson(x, my_lambda)[0]
207
+ return self._transf_yeojohnson_rectified(x, my_lambda, changepoint=changepoint)[0]
208
+
209
+ def _rectified_linear_part(
210
+ self, changepoint: float, transf: Literal["boxcox", "yeojohnson"], my_lambda: float
211
+ ) -> tuple[float, float, bool]:
212
+ """The linear part of the rectified transformation beyond the change point.
213
+
214
+ Returns:
215
+ tuple: the transformed change point, the slope of the linear part, and whether the
216
+ linear part lies above the change point (lambda < 1) or below it (lambda > 1).
217
+ """
218
+ c = np.array([changepoint], dtype=float)
219
+ if transf == "boxcox":
220
+ changepoint_transf = self._transf_boxcox(c, my_lambda)[0][0]
221
+ slope = changepoint ** (my_lambda - 1)
222
+ else:
223
+ changepoint_transf = self._transf_yeojohnson(c, my_lambda)[0][0]
224
+ exponent = my_lambda - 1 if my_lambda < 1 else 1 - my_lambda
225
+ slope = (1 + np.abs(changepoint)) ** exponent
226
+ return changepoint_transf, slope, my_lambda < 1
227
+
228
+ def _fit_transformation(
229
+ self,
230
+ x: np.ndarray,
231
+ transf: Literal["boxcox", "yeojohnson"],
232
+ ) -> dict:
233
+ """Fits the Box-Cox or Yeo-Johnson power transformation.
184
234
 
185
235
  Args:
186
- x (np.ndarray): The data.
236
+ x (np.ndarray): The data, sorted.
237
+ transf: The transformation.
238
+
239
+ Returns:
240
+ dict: lambda, standardization constants and (if rectified) the change point.
187
241
  """
188
- lambdarange = self.lambda_range
189
- converged = False
190
- while not converged:
191
- if self.standardize:
192
- loc_yeojohnson = np.median(x)
193
- scale_yeojohnson = median_abs_deviation(x, scale="normal")
194
- x = (x - loc_yeojohnson) / scale_yeojohnson
242
+ location_pre, scale_pre = None, None
243
+ if self.standardize:
244
+ if transf == "boxcox":
245
+ scale_pre = np.median(x)
246
+ x = x / scale_pre
195
247
  else:
196
- loc_yeojohnson, scale_yeojohnson = None, None
197
- lambda_raw = self._calculate_lambda_0(x, "yeojohnson_rect", lambdarange)
198
- (
199
- lambda_rew,
200
- mu_rew_yeojohnson,
201
- sd_rew_yeojohnson,
202
- ) = self._reweighted_max_likelihood_robust(
203
- x,
204
- lambda_raw,
205
- "yeojohnson",
206
- lambdarange,
207
- self.quantile,
208
- self.nsteps,
248
+ location_pre = np.median(x)
249
+ scale_pre = median_abs_deviation(x, scale="normal")
250
+ x = (x - location_pre) / scale_pre
251
+
252
+ # Widen the range of lambda when the estimate lies close to one of its bounds, as in
253
+ # cellWise::transfo.
254
+ lambdarange = np.asarray(self.lambda_range, dtype=float)
255
+ while True:
256
+ lambda_raw = self._calculate_lambda_0(x, f"{transf}_rect", lambdarange)
257
+ lambda_rew, weights = self._reweighted_max_likelihood_robust(
258
+ x, lambda_raw, transf, lambdarange, self.quantile, self.nsteps
209
259
  )
210
- converged = np.min(np.abs(lambda_rew - lambdarange)) > np.diff(lambdarange) * 0.05
211
- if not converged:
212
- lambdarange = 1 + (lambdarange - 1) * (
213
- 1 + (abs(lambda_rew - lambdarange) == min(abs(lambda_rew - lambdarange)))
214
- )
260
+ distance = np.abs(lambda_rew - lambdarange)
261
+ if np.min(distance) > np.diff(lambdarange)[0] * 0.05:
262
+ break
263
+ lambdarange = 1 + (lambdarange - 1) * (1 + (distance == np.min(distance)))
215
264
 
216
- return lambda_rew, mu_rew_yeojohnson, sd_rew_yeojohnson, loc_yeojohnson, scale_yeojohnson
265
+ changepoint = None
266
+ if self.rectified and lambda_rew != 1.0:
267
+ if transf == "boxcox":
268
+ changepoint = self._get_rectified_boxcox_changepoint(x, lambda_rew)
269
+ else:
270
+ changepoint = self._get_rectified_yeojohnson_changepoint(x, lambda_rew)
271
+ xt = self._transform_standardized(x, transf, lambda_rew, changepoint)
272
+
273
+ return {
274
+ "lambda": lambda_rew,
275
+ "location_pre": location_pre,
276
+ "scale_pre": scale_pre,
277
+ "location_post": np.mean(xt[weights]),
278
+ "scale_post": np.std(xt[weights], ddof=1),
279
+ "changepoint": changepoint,
280
+ }
281
+
282
+ def _fit_boxcox(self, x: np.ndarray) -> dict:
283
+ """Fits the Box-Cox power transformation (x sorted)."""
284
+ return self._fit_transformation(x, "boxcox")
285
+
286
+ def _fit_yeojohnson(self, x: np.ndarray) -> dict:
287
+ """Fits the Yeo-Johnson power transformation (x sorted)."""
288
+ return self._fit_transformation(x, "yeojohnson")
217
289
 
218
290
  def _calculate_bounds(self):
219
291
  """Calculates the bounds of the range of the power transformation."""
@@ -232,6 +304,8 @@ class RobustPowerTransformer(OneToOneFeatureMixin, TransformerMixin, BaseEstimat
232
304
  return lower_bound, upper_bound
233
305
 
234
306
  def _handle_bounds(self, x: np.ndarray):
307
+ if np.size(x) == 0:
308
+ return x
235
309
  lower_bound, upper_bound = self._calculate_bounds()
236
310
 
237
311
  if lower_bound is not None and np.min(x) < lower_bound:
@@ -255,9 +329,14 @@ class RobustPowerTransformer(OneToOneFeatureMixin, TransformerMixin, BaseEstimat
255
329
  return x
256
330
 
257
331
  def _transf_boxcox_rectified(
258
- self, x: np.ndarray, my_lambda: float, standardize_too: bool = False
332
+ self,
333
+ x: np.ndarray,
334
+ my_lambda: float,
335
+ standardize_too: bool = False,
336
+ changepoint: float | None = None,
259
337
  ):
260
- """Rectified Box-Cox transformation."""
338
+ """Rectified Box-Cox transformation. Without a change point, it is computed from x,
339
+ which must then be sorted."""
261
340
 
262
341
  if np.min(x) <= 0:
263
342
  raise ValueError(
@@ -268,7 +347,8 @@ class RobustPowerTransformer(OneToOneFeatureMixin, TransformerMixin, BaseEstimat
268
347
  if my_lambda == 1.0:
269
348
  xt = x - 1.0
270
349
  else:
271
- changepoint = self._get_rectified_boxcox_changepoint(x, my_lambda)
350
+ if changepoint is None:
351
+ changepoint = self._get_rectified_boxcox_changepoint(x, my_lambda)
272
352
 
273
353
  if my_lambda > 1.0:
274
354
  mask = x < changepoint
@@ -362,9 +442,14 @@ class RobustPowerTransformer(OneToOneFeatureMixin, TransformerMixin, BaseEstimat
362
442
  return xt, zt
363
443
 
364
444
  def _transf_yeojohnson_rectified(
365
- self, x: np.ndarray, my_lambda: float, standardize_too: bool = False
445
+ self,
446
+ x: np.ndarray,
447
+ my_lambda: float,
448
+ standardize_too: bool = False,
449
+ changepoint: float | None = None,
366
450
  ):
367
- """Rectified Yeo-Johnson transformation."""
451
+ """Rectified Yeo-Johnson transformation. Without a change point, it is computed from x,
452
+ which must then be sorted."""
368
453
 
369
454
  xt = np.zeros_like(x)
370
455
 
@@ -372,7 +457,8 @@ class RobustPowerTransformer(OneToOneFeatureMixin, TransformerMixin, BaseEstimat
372
457
  xt = x
373
458
 
374
459
  else:
375
- changepoint = self._get_rectified_yeojohnson_changepoint(x, my_lambda)
460
+ if changepoint is None:
461
+ changepoint = self._get_rectified_yeojohnson_changepoint(x, my_lambda)
376
462
  positive_mask = x >= 0.0
377
463
  negative_mask = x < 0.0
378
464
 
@@ -530,26 +616,40 @@ class RobustPowerTransformer(OneToOneFeatureMixin, TransformerMixin, BaseEstimat
530
616
  quantile: float = 0.99,
531
617
  nsteps: int = 2,
532
618
  ):
533
- """Computes the reweighted estimate for lambda by performing reweighted ML."""
619
+ """Computes the reweighted estimate for lambda by performing reweighted ML.
620
+
621
+ Starting from the rectified transformation with the initial lambda, each step estimates
622
+ lambda by maximum likelihood on the observations with weight 1, transforms all
623
+ observations with the new lambda and standardizes them robustly (Huber M-estimator of
624
+ location and scale, as ``YJ`` / ``BC`` in cellWise). Observations with an absolute
625
+ standardized value above ``sqrt(chi2_1(quantile))`` get weight 0.
534
626
 
627
+ Args:
628
+ x (np.ndarray): The (pre-standardized) data, sorted.
629
+
630
+ Returns:
631
+ tuple[float, np.ndarray]: the reweighted lambda and the final weights (boolean
632
+ array), computed after the last step.
633
+ """
634
+ if nsteps < 1:
635
+ raise ValueError("nsteps must be at least 1.")
636
+ cutoff = np.sqrt(chi2.ppf(quantile, 1))
535
637
  if transf == "boxcox":
536
638
  zt = self._transf_boxcox_rectified(x, lambda_raw, standardize_too=True)[1]
537
639
  elif transf == "yeojohnson":
538
640
  zt = self._transf_yeojohnson_rectified(x, lambda_raw, standardize_too=True)[1]
641
+ else:
642
+ raise NotImplementedError("Wrong transformation.")
539
643
 
540
644
  for _ in range(nsteps):
541
- w = np.abs(zt) <= np.sqrt(chi2.ppf(quantile, 1))
645
+ w = np.abs(zt) <= cutoff
542
646
  lambda_rew = self._estimate_max_likelihood(x[w], transf, lambdarange)
543
647
  if transf == "boxcox":
544
- xt = self._transf_boxcox(x, lambda_rew, standardize_too=False)[0]
545
- elif transf == "yeojohnson":
546
- xt = self._transf_yeojohnson(x, lambda_rew, standardize_too=False)[0]
547
- zt = (xt - np.mean(xt)) / np.std(xt)
548
-
549
- mu_rew = np.mean(xt[w])
550
- sd_rew = np.std(xt[w])
648
+ zt = self._transf_boxcox(x, lambda_rew, standardize_too=True)[1]
649
+ else:
650
+ zt = self._transf_yeojohnson(x, lambda_rew, standardize_too=True)[1]
551
651
 
552
- return lambda_rew, mu_rew, sd_rew
652
+ return lambda_rew, np.abs(zt) <= cutoff
553
653
 
554
654
  def _estimate_max_likelihood(
555
655
  self,
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes