Repository navigation
ENH: Outlier robust covariance - rebased - #8129
Conversation
|
Hello @josef-pkt! Thanks for updating this PR. We checked the lines you've touched for PEP 8 issues, and found: There are currently no PEP 8 issues detected in this Pull Request. Cheers! 🍻 Comment last updated at 2024-02-22 15:53:26 UTC |
|
This pull request introduces 3 alerts when merging 97d24cc into 8c67ccb - view on LGTM.com new alerts:
|
|
It would be useful to have some internal use cases to help in interface design. Maybe an |
| c_inv = np.linalg.pinv(c) | ||
| c_old = c | ||
| # this could be vectorized but could use a lot of memory | ||
| # TODO: try to work in vectorized batches | ||
| c = kn * sum(np.outer(xi, xi) / np.inner(xi, c_inv.dot(xi)) for xi in x) |
There was a problem hiding this comment.
Adding from scipy.linalg.lapack import dtrtri, this vectorized implementation is faster:
| c_inv = np.linalg.pinv(c) | |
| c_old = c | |
| # this could be vectorized but could use a lot of memory | |
| # TODO: try to work in vectorized batches | |
| c = kn * sum(np.outer(xi, xi) / np.inner(xi, c_inv.dot(xi)) for xi in x) | |
| c_old = c | |
| ichol, _ = dtrtri(linalg.cholesky(c, lower=False), lower=0) | |
| v = x @ ichol | |
| dist_mahal_2 = np.einsum('ij,ji->i', v, v.T) | |
| xw = np.sqrt(k_vars / dist_mahal_2[:, None]) * x | |
| c = xw.T @ xw / nobs |
There was a problem hiding this comment.
Thanks
I need to check this. I would like to get to this soonish, for sure for the next release.
Does the speed increase apply in different sizes of the arrays? I don't remember what the shapes are for those arrays/matrices.
One difference between pinv and cholesky is that the former also works if c is singular. I don't remember if this shows up here in non-negligible case.
There was a problem hiding this comment.
I guess this will always be much faster because of the vectorization in x if nobs is not very small.
looks good, AFAICS
There was a problem hiding this comment.
To reproduce this figure
n_obs = 100
maxiter = 10
generator = check_random_state(None)
dims = [2, 5, 7, 10, 15, 20, 30, 50]
n_dims, n_reps = len(dims), 10
t_old = np.zeros((n_dims, n_reps))
t_new = np.zeros((n_dims, n_reps))
for i, n_dim in enumerate(dims):
data = generator.uniform(size=(n_obs, n_dim))
for j in range(n_reps):
t0 = timeit.default_timer()
cov_tyler(data, maxiter=maxiter)
t_old[i, j] = timeit.default_timer() - t0
t0 = timeit.default_timer()
cov_tyler_new(data, maxiter=maxiter)
t_new[i, j] = timeit.default_timer() - t0
fig, ax = plt.subplots()
ax.errorbar(dims, t_old.mean(axis=-1), yerr=t_old.std(axis=-1), label='old')
ax.errorbar(dims, t_new.mean(axis=-1), yerr=t_new.std(axis=-1), label='new')
ax.set(xlabel='Number of variables', ylabel='Time')
plt.legend(loc='upper left')
plt.show()
|
This PR already includes |
|
similar performance improvement as above can be made in line 508 |
|
comment to possibly singular shape matrix If we start from a positive definite matrix (e.g. identity, diagonal(var) or shrinked to identity), then the updating should use only positive definite matrices, except that we might converge to a singular matrix if the "true" matrix is rank reduced. |
|
current Monte Carlo results for consistency at normal distribution looks good overall nobs, k_vars = 100, 5 first column bias, second column is mse diagonal cov with unequal variances toeplitz (by mistake nobs, k_vars = 100, 3) with 5 outlier observationspearson is awful, strongly biased and large mse ogk reweighted looks best, i.e reweighting drops outliers tyler, t and iter_qu look pretty good with independence, but worse for toeplitz case: larger bias and mse than ogk independent with unequal var toeplitz now also with k_vars = 5 |
f149fa5 to
2d32da8
Compare
| 0.861689042081113, 1.52042567119062, 2.27431881174842 | ||
| ]) | ||
| # > cat(convert(ccogk$det, name="det")) | ||
| det = -1 |
Check warning
Code scanning / CodeQL
Variable defined multiple times
2d32da8 to
6fc8e08
Compare
|
update for cov_starting
|
|
#3220 (comment) update adding This might be a good new default scaling instead of tyler unscaled scatter e.g. toeplitz cov, 5 outliers out of nobs=100, setup from previous run I have not checked yet: |
|
problem with normalized scaling, example multivariate-t (rvs from scipy.stats) ? for toepliz scatter/shape and df = 5 no outliers: 5 out of 100 outliers update tyler_rescaled looks good, pearson_oracle is best and it's bias not seem to be affected by heavier tails the same MC with no outliers both bias and mse become worse if there are no outliers (except pearson of course) update 2 there is something fishy in the scaling in the toeplitz case. seems like a scaling factor is wrong, either in the MC or the current code 1000 MC replication, and nobs=500, so not a small sample case. another update for df=500 in mv-t, the results look good, or as good as before, we are close to normal distribution |
|
I think I have to give up here for estimating the covariance matrix if the data come from something like multivariate t I did not read Ollila et al for tyler_reweighted well enough, the reweighting does not match the covariance matrix, in the t-case it's supposed to be the t-shape, i.e. cov * (df - 2) / df Similarly, I guess, the The weird thing is that the Monte Carlo shows good results for matching the covariance in the independence case but not in the correlated (toeplitz) case. I need more work to figure out what to do for non-normal distributions. current status Everything or almost everything looks fine for the normal reference case with outliers. Two possibilities
more MC: |
|
adding statistics for trace in MC toplitz, last column is average trace of the ratio estimate / dgp, of cov divided by k_vars to get ration per diagonal element ogk_rw_unscaled and tyler are not correctly scaled for covariance t, tyler_rescaled and ogk_rw have lowest trace mse (after pearson) |
|
It looks like the initial robust standardization/zscoring follows DetMCD. see Hubert et al 2012. DetMCD uses only the distances computed using the initial cov estimate to select the "central" observations. Scaling is irrelevant in this case. Hubert, Mia, Peter J. Rousseeuw, and Tim Verdonck. “A Deterministic Algorithm for Robust Location and Scatter.” Journal of Computational and Graphical Statistics 21, no. 3 (July 1, 2012): 618–37. https://doi.org/10.1080/10618600.2012.672100. DetMCD in the article has essentially 3 steps
step 1 replaces the random set selection in FastMCD I think we can outsource the orthogonalization step into a new function, used for mcd_det and ogk Aside: they use "large" outliers in their simulations so that there is no overlap between data and outliers. |
| xsp = xs[d < cutoff] | ||
| c = np.cov(xsp.T) | ||
| corr_factor = coef_normalize_cov_truncated(p / 100, k_vars) | ||
| c0 = Holder(cov=c * corr_factor, mean=xsp.mean(0) + center, |
There was a problem hiding this comment.
likely a bug
should be mean=xsp.mean(0) * std + center if data is standardized/scaled from original
all (?) my examples and test cases use mean=0, so bug will have small effect
|
|
||
|
|
||
| def cov_ogk(data, maxiter=2, scale_func=mad, cov_func=cov_gk, | ||
| loc_func=lambda x: np.median(x, axis=0), reweight=0.9, |
There was a problem hiding this comment.
the article maronna/zamar uses reweight beta= 0.9 in Monte Carlo and recommends that.
I think for consistency with other methods, we should standardize on 0.975 as default
|
aside S-estimators notebook try_robust_scale_iter_updated.ipynb has a section at the end where I started to work on S-estimator for location and covariance, mainly expressions for biweight/bisquare Hubert, Mia, Peter Rousseeuw, Dina Vanpaemel, and Tim Verdonck. “The DetS and DetMM Estimators for Multivariate Location and Scatter.” Computational Statistics & Data Analysis 81 (January 2015): 64–75. https://doi.org/10.1016/j.csda.2014.07.013. I have many other articles on S-estimators. One problem seems to be again the consistency factor to make it consistent at normal distribution or at some other distribution (which I don't remember seeing in any article). I guess none of the estimators for statistics that need consistency factors are distribution free / semi-parametric. Additionally, fisher consistency usually requires symmetry (or elliptical symmetry) assumption, e.g. GLM, Poisson also need a distribution specific consistency factor.
Aside: I have not looked at the literature on robust regression if some regressors are categorical or binary. |
|
I just saw: this PR add unit test has number for scale_bias b, but no comment for source/reference I don't remember why I called the from Rousseeuw and Leroy 1987, p. 142 Table 19. Asymptotic Efficiency of S-Estimators for It looks like b in S-B and Y 2006 refers to breakdown point, and not to scale_bias term (K in RL book), maybe a typo. check breakdown formula, bdp = b / sup(rho(x)) = b / rho(c) I need to check whether the same applies to S-estimator for multivariate mean, cov and mv regression. There might be a factor for k_vars. |
|
merging this to get rid of it, so I can start new PRs This still needs quite a lot of restructuring and api work, but I need internal use cases for this to see what a good structure will be. |

rebased version of #3230
(merge conflicts mainly in imports, not too bad)
overview
in
robust.covariance:cov_gkGK (no reference in docstring)cov_ogkOGK based on Maronna and Zamar 2002 (docstring mentions difference to R)cov_tylerstandard Tyler's scatter iteration loop, mean assumed to be zerocov_tyler_regularizedshrinkage towards identity in iteration loop, Chen and Wiesel 2011cov_weightedweighted mean and cov, no iteration loopcov_tyler_pairs_regularizedexperimental, not all options working_cov_itergeneric M-estimator for cov using weight function, available weights:weights_mvt,weights_quantile_cov_startingincomplete, this is just collecting a list of different robust cov, a bit ad-hoc,for use in high breakdown cov estimators,
not useful as standalone (unless we make return more informative)
cov_gk1gk for just one pair of variablesother helper functions:
mahalanobisscale_tau_naive_ledoit_wolf_shrinkage_outlier_gy_reweight_weight_mean_winsorin
stats.covariance:corr_normal_scorescorr based on transforming ranks to normal scorescorr_quadrantbased on signs, unverifiedtransform_corr_normalrescaling to be consistent at normal distribution, for 'pearson', 'gauss_rank', 'kendal', 'spearman' and'quadrant'
_term_integratecurrently not usedstatus, todos
possibly additional returns in future (backwards compatible if Holder instance is returned), e.g. support for outlier detection
(add convenience function for t scatter with option for consistent cov)
(*) very recent article including joint estimation mean, cov
Taskinen, Sara, Gabriel Frahm, Klaus Nordhausen, and Hannu Oja. “A Review of Tyler’s Shape Matrix and Its Extensions.” In Robust and Multivariate Statistical Methods: Festschrift in Honor of David E. Tyler, edited by Mengxi Yi and Klaus Nordhausen, 23–41. Cham: Springer International Publishing, 2023. https://doi.org/10.1007/978-3-031-22687-8_2.
has also good list of references, some that I used, some more recent than when I worked on it initially