Skip to content

ENH: Outlier robust covariance - rebased - #8129

Merged
josef-pkt merged 20 commits into
statsmodels:mainfrom
josef-pkt:outlier_cov_rebased
Mar 29, 2024
Merged

josef-pkt merged 20 commits into
statsmodels:mainfrom
josef-pkt:outlier_cov_rebased

Conversation

@josef-pkt

@josef-pkt josef-pkt commented Feb 17, 2022 •

Copy link
Copy Markdown
Member

rebased version of #3230

(merge conflicts mainly in imports, not too bad)

overview

in robust.covariance:

cov_gk GK (no reference in docstring)
cov_ogk OGK based on Maronna and Zamar 2002 (docstring mentions difference to R)
cov_tyler standard Tyler's scatter iteration loop, mean assumed to be zero
cov_tyler_regularized shrinkage towards identity in iteration loop, Chen and Wiesel 2011
cov_weighted weighted mean and cov, no iteration loop
cov_tyler_pairs_regularized experimental, not all options working
_cov_iter generic M-estimator for cov using weight function, available weights: weights_mvt, weights_quantile

_cov_starting incomplete, 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_gk1 gk for just one pair of variables

other helper functions:
mahalanobis
scale_tau
_naive_ledoit_wolf_shrinkage
_outlier_gy
_reweight
_weight_mean
_winsor

in stats.covariance:

corr_normal_scores corr based on transforming ranks to normal scores
corr_quadrant based on signs, unverified
transform_corr_normal rescaling to be consistent at normal distribution, for 'pearson', 'gauss_rank', 'kendal', 'spearman' and
'quadrant'
_term_integrate currently not used

status, todos

  • consistency with reference distribution, gaussian cov
    • which estimators are consistent, or have option for returning consistent cov
    • recipe for rescaling, or document when rescaling is not available
  • unit test, Monte Carlo checks
    • ogk works very well in normal sample with a few outliers in MC
  • check returns, e.g. cov_ogk and cov_weighted do not return a Holder instance
    possibly additional returns in future (backwards compatible if Holder instance is returned), e.g. support for outlier detection
  • check options, e.g. string options instead of boolean
  • references in docstring are missing or incomplete
  • check scale_tau function. try, support qn_scale which is now in robust
  • high priority: ogk, tyler, M-estimator with e.g. t-weights
    (add convenience function for t scatter with option for consistent cov)
  • ...
  • missing:
    • joint estimation robust mean - robust cov: Tyler M-estimation, Hettmansperger-Randles (*)
    • corr to cov for stats.covariance, using a robust univariate scale estimate, e.g. Öllerer and Croux 2015
    • outlier detection, the try_robust_cov_more_updated.ipynb notebook has experiments for outlier detection with references to several articles
  • ...

(*) 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

@pep8speaks

pep8speaks commented Feb 17, 2022 •

Copy link
Copy Markdown

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

@lgtm-com

lgtm-com Bot commented Feb 17, 2022

Copy link
Copy Markdown

This pull request introduces 3 alerts when merging 97d24cc into 8c67ccb - view on LGTM.com

new alerts:

  • 2 for Variable defined multiple times
  • 1 for Unused import

@josef-pkt

Copy link
Copy Markdown
Member Author

It would be useful to have some internal use cases to help in interface design.
This includes mostly "helper" functions, i.e. they have the pieces but not a clear access and usage.

Maybe an MVOutlier class that can be used to quickly check for multivariate outliers using different methods and robust estimators. Maybe a bit similar to outlier influence but for a constant mean, constant variance model.

@josef-pkt josef-pkt mentioned this pull request Nov 29, 2022
6 tasks
@josef-pkt josef-pkt added this to the 0.15 milestone Dec 21, 2022
Comment thread statsmodels/robust/covariance.py Outdated
Comment on lines +414 to +418
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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Adding from scipy.linalg.lapack import dtrtri, this vectorized implementation is faster:

Suggested change
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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess this will always be much faster because of the vectorization in x if nobs is not very small.
looks good, AFAICS

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

pr_8129_robust_cov

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()

@josef-pkt

Copy link
Copy Markdown
Member Author

This PR already includes cov_tyler_regularized :)
updated references for it in #3220 (comment)

@josef-pkt

Copy link
Copy Markdown
Member Author

similar performance improvement as above can be made in line 508

@josef-pkt

Copy link
Copy Markdown
Member Author

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.
A test case would be to see what happens in tyler and regularized tyler if k_vars > nobs.

@josef-pkt

Copy link
Copy Markdown
Member Author

current Monte Carlo results for consistency at normal distribution
same case as before with updated defaults in functions
ogk_raw is now rescaled by default

looks good overall
iter_qu looks the worst
tyler is unscaled by default, ok under independence, some bias with toeplitz
t has second lowest mse after pearson for both cov

nobs, k_vars = 100, 5
n_rep = 100
multivariate normal data with no outliers

first column bias, second column is mse

diagonal cov with unequal variances

pearson              (-0.0005271733585976983, 0.0027834380793607984)
pearson_oracle       (-0.0005271733585976983, 0.0027834380793607984)
ogk_raw              (0.003123923670784035, 0.0056301681758464)
ogk_rw               (-0.00220759496593598, 0.004231183061724666)
ogk_rw_unscaled      (-0.015688274406626467, 0.00475047033636568)
tyler                (-0.0001472632625806714, 0.004483323477927456)
tyler_rescaled       (-0.0009336300501877378, 0.004102034035892761)
t                    (-0.0013829352057956146, 0.0033002693679949815)
iter_qu              (0.006246531213839035, 0.014052922490647733)

toeplitz (by mistake nobs, k_vars = 100, 3)

pearson              (-0.02073333082233498, 0.013345699780021694)
pearson_oracle       (-0.02073333082233498, 0.013345699780021694)
ogk_raw              (-0.030868863420961228, 0.030892096032430726)
ogk_rw               (-0.042765211246419646, 0.02588144871776369)
ogk_rw_unscaled      (-0.16178167188046366, 0.045403750358603535)
tyler                (0.06418139223216467, 0.04054981287165576)
tyler_rescaled       (-0.012541930431487994, 0.024661556929123217)
t                    (-0.022073871296519956, 0.016568171441358342)
iter_qu              (0.033241279847667934, 0.08437330261046865)

with 5 outlier observations

pearson is awful, strongly biased and large mse

ogk reweighted looks best, i.e reweighting drops outliers
ogk_raw looks second best

tyler, t and iter_qu look pretty good with independence, but worse for toeplitz case: larger bias and mse than ogk
bias is positive, i.e. still overestimates variances and covariances.
tyler_rescaled is the best of these estimators

independent with unequal var

pearson              (1.1924881803059688, 1.4381638614982897)
pearson_oracle       (-0.0005322024661195243, 0.0028232668629331725)
ogk_raw              (0.009014285940483419, 0.007050987099282287)
ogk_rw               (-0.0010346409803914769, 0.0044783967586986976)
ogk_rw_unscaled      (-0.014692735127175331, 0.004854152762602558)
tyler                (0.0348990390404658, 0.0063290324586747345)
tyler_rescaled       (0.025948292201790263, 0.004797274727059101)
t                    (0.0760689047222673, 0.0096946522731137)
iter_qu              (0.03006335919795613, 0.01556579343992031)

toeplitz now also with k_vars = 5

pearson              (1.2010928104101966, 1.4977569615814377)
pearson_oracle       (-0.006255258013948482, 0.014175116256447108)
ogk_raw              (0.07475042201706014, 0.04732349727719695)
ogk_rw               (-0.007517314799377516, 0.022482708074581713)
ogk_rw_unscaled      (-0.08140257636514503, 0.024777509404520406)
tyler                (0.30203293429565414, 0.14781551020721068)
tyler_rescaled       (0.17132359747773215, 0.05836303614144228)
t                    (0.2704038209407136, 0.09996370809148274)
iter_qu              (0.18414275032817318, 0.12383366146612233)

@josef-pkt
josef-pkt force-pushed the outlier_cov_rebased branch 2 times, most recently from f149fa5 to 2d32da8 Compare January 12, 2024 21:46
0.861689042081113, 1.52042567119062, 2.27431881174842
])
# > cat(convert(ccogk$det, name="det"))
det = -1

Check warning

Code scanning / CodeQL

Variable defined multiple times

This assignment to 'det' is unnecessary as it is [redefined](1) before this value is used.
Comment thread statsmodels/robust/covariance.py Fixed
@josef-pkt
josef-pkt force-pushed the outlier_cov_rebased branch from 2d32da8 to 6fc8e08 Compare January 14, 2024 14:13
@josef-pkt

josef-pkt commented Jan 14, 2024 •

Copy link
Copy Markdown
Member Author

cov_tyler_regularized still needs review and checking, e.g. options and defaults, plus speedup

cov_tyler_pairs_regularized sounds unfinished, note in docstring that parts are not working yet

_cov_starting: It's not clear why standardization is used if is_standarized is not True.
This rescaling affects covariance, but the returned cov do not compensate for it. (i.e. no multiplication by outer(std, std))
I adding the compensating return rescaling in next commit.
By default, only subtracting median as center is used, which does not affect covariance scale (directly).
Also:
c02 = _naive_ledoit_wolf_shrinkage does not include scaling correction for truncation of sample.

update for cov_starting
One reason for standardization is that we use identity cov to compute initial mahalanobis distance.
As alternative, we could use a diagonal starting cov using some robust variance estimate, std**2 with eg. std=mad(...).
e.g. rename "is_standardized" to "standardize=False", and add option for cov_initial or scale_initial, or var_initial

_cov_iter : this looks like a standard M-estimator for mean and cov simultaneously.
However, it uses the same weights for mean and cov.
In general it shouldn't be the same weights. ???
The utility function cov_weighted called by _cov_iter allows for different weights for mean and cov.
update to this: the references use 1, 2 or 3 different weight functions
e.g. cov_weighted cites Rocke Wolf with 3 weights functions, similar Huber, Ronzetti book has 3 weights function in general.
I think the 3rd weight function (weight_denom) could be absorbed into the second weight function (cov weights)
references on t-distribution loc/cov have 1 or 2 weight functions.
Maronna et al book 2nd ed. have 1 or 2 weight functions in 6.3 M-estimators for loc-scale,
e.g. for t distribution it's only one, equ. 6.11 - 6.13 p. 203 (which looks like what I have in the code.)

@josef-pkt

josef-pkt commented Jan 15, 2024 •

Copy link
Copy Markdown
Member Author

#3220 (comment)
for new scaling of Tyler's shape matrix

update
this scaling seems to work well

adding wscaled to MC for normalize="weights" in tyler
works better than chi2 rescaling for tyler

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
tyler_wscaled is similar to ogk_raw but ogk_reweighted is better in normal plus outlier case

pearson              (1.2010928104101966, 1.4977569615814377)
pearson_oracle       (-0.006255258013948482, 0.014175116256447108)
ogk_raw              (0.07475042201706014, 0.04732349727719695)
ogk_rw               (-0.007517314799377516, 0.022482708074581713)
ogk_rw_unscaled      (-0.08140257636514503, 0.024777509404520406)
tyler                (0.30203293429565353, 0.1478155102072102)
tyler_rescaled       (0.1713235974777322, 0.058363036141442295)
tyler_wscaled        (-0.08838842546728841, 0.03335173036379611)
t                    (0.2780443589235747, 0.10390871093171893)
iter_qu              (0.19090769474299768, 0.12864560678498546)

I have not checked yet:
can this weight scaling also be used with regularized tyler?

@josef-pkt

josef-pkt commented Jan 16, 2024 •

Copy link
Copy Markdown
Member Author

problem with normalized scaling, example multivariate-t (rvs from scipy.stats) ?

for toepliz scatter/shape and df = 5

no outliers:
only tyler (raw) looks well scaled, tyler_rescaled and t have good mse but bias, tyler_wscaled does not look good
t does not look as well as I would expect, but mse is fine

ppearson              (0.005095080845462322, 0.033093201867869224)
pearson_oracle       (0.005095080845462322, 0.033093201867869224)
ogk_raw              (-0.14362334314276437, 0.0425971669066077)
ogk_rw               (-0.18968867102095385, 0.05732800533553345)
ogk_rw_unscaled      (-0.23601967383404157, 0.07969140088207238)
tyler                (-0.09455257009383629, 0.025679175637280706)
tyler_rescaled       (-0.14561788454572333, 0.0367858294559646)
tyler_wscaled        (-0.3128684431085659, 0.13018863610565126)
t                    (-0.1479145909990094, 0.036701343321600834)
iter_qu              (-0.11940701801373665, 0.04790679442170776)

5 out of 100 outliers
pearson is awful,
tyler and tyler_rescaled look good
t looks ok

pearson              (1.2019325054480248, 1.5129288525201139)
pearson_oracle       (0.012388966735701314, 0.03547274806512049)
ogk_raw              (-0.09765751600574266, 0.03368539588660832)
ogk_rw               (-0.17620186270789787, 0.05241834122332371)
ogk_rw_unscaled      (-0.22457280754981765, 0.07424465811510429)
tyler                (0.08290922552882096, 0.03101463208755225)
tyler_rescaled       (0.0009261804838539575, 0.019676397063201036)
tyler_wscaled        (-0.24271403135426126, 0.09328205228674095)
t                    (0.09470869474846698, 0.03002894412261686)
iter_qu              (-0.03386326174787265, 0.042259449271064946)

update
increasing number of MC replication from 100 to 1000
others are the same as above
nobs, k_vars = 100, 5
5 outliers
toeplitz

pearson              (1.2021836857075423, 1.5147971514270198)
pearson_oracle       (-0.0046465820237696145, 0.03595214031664192)
ogk_raw              (-0.09532287115319216, 0.035739719457922745)
ogk_rw               (-0.17834908760924395, 0.05365027619414827)
ogk_rw_unscaled      (-0.226395254770638, 0.07567143421833113)
tyler                (0.0688568218170609, 0.030050500547812935)
tyler_rescaled       (-0.012328056649928563, 0.021373380439045953)
tyler_wscaled        (-0.24764588848471286, 0.09589708462324427)
t                    (0.07927323359693837, 0.02898164660309049)
iter_qu              (-0.04669183979830413, 0.04155002863490037)

tyler_rescaled looks good, pearson_oracle is best and it's bias not seem to be affected by heavier tails
but tyler rescaled has smaller mse than pearson oracle
tyler_wscaled is the worst after plain pearson, in both bias and mse
t is not very good in bias, but second best in mse

the same MC with no outliers

both bias and mse become worse if there are no outliers (except pearson of course)
something strange ???

pearson              (-0.004154852931821781, 0.03450440165417732)
pearson_oracle       (-0.004154852931821781, 0.03450440165417732)
ogk_raw              (-0.1468594631439977, 0.04527738453396124)
ogk_rw               (-0.19394196988475243, 0.05971113497810653)
ogk_rw_unscaled      (-0.2396296416062989, 0.08232948406457748)
tyler                (-0.1006331064893426, 0.02820840063177027)
tyler_rescaled       (-0.14847970901929253, 0.038798991627362535)
tyler_wscaled        (-0.31453464938741027, 0.1316869299507362)
t                    (-0.1490261933501983, 0.038043511322848556)
iter_qu              (-0.1270949441100881, 0.04817262300017789)

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
e.g. around 0.61 in ogk.rw and 0.69 in tyler_rescaled and t
MC for diagonal independence cov looks good and does not have this problem

1000 MC replication, and nobs=500, so not a small sample case.
no outlier case

cov, (res_ogk_u).mean(0)
(array([[1.        , 0.5       , 0.33333333, 0.25      , 0.2       ],
        [0.5       , 1.        , 0.5       , 0.33333333, 0.25      ],
        [0.33333333, 0.5       , 1.        , 0.5       , 0.33333333],
        [0.25      , 0.33333333, 0.5       , 1.        , 0.5       ],
        [0.2       , 0.25      , 0.33333333, 0.5       , 1.        ]]),

 array([[0.52383317, 0.25991511, 0.17525928, 0.13084488, 0.10436847],
        [0.25991511, 0.51979074, 0.2597885 , 0.17340899, 0.13018508],
        [0.17525928, 0.2597885 , 0.52423743, 0.26270417, 0.17542751],
        [0.13084488, 0.17340899, 0.26270417, 0.52267021, 0.26113884],
        [0.10436847, 0.13018508, 0.17542751, 0.26113884, 0.52112719]]))

res_mc2["ogk_rw"].mean(0) / cov
array([[0.6171853 , 0.61246899, 0.61947653, 0.61665082, 0.61483967],
       [0.61246899, 0.61242246, 0.61217064, 0.61293642, 0.61354127],
       [0.61947653, 0.61217064, 0.6176616 , 0.61904119, 0.62007116],
       [0.61665082, 0.61293642, 0.61904119, 0.61581508, 0.61535261],
       [0.61483967, 0.61354127, 0.62007116, 0.61535261, 0.61399708]])

res_mc2["tyler_rescaled"].mean(0) / cov
array([[0.69291118, 0.68958547, 0.69402104, 0.68804758, 0.6889056 ],
       [0.68958547, 0.68835282, 0.68942914, 0.68890124, 0.69120593],
       [0.69402104, 0.68942914, 0.69136937, 0.6940859 , 0.69460697],
       [0.68804758, 0.68890124, 0.6940859 , 0.6909398 , 0.69134929],
       [0.6889056 , 0.69120593, 0.69460697, 0.69134929, 0.69062227]])

res_mc2["t"].mean(0) / cov
array([[0.69232497, 0.68964638, 0.69253398, 0.68773889, 0.68655529],
       [0.68964638, 0.68784458, 0.68829242, 0.68819215, 0.69126996],
       [0.69253398, 0.68829242, 0.69057281, 0.69218851, 0.69358342],
       [0.68773889, 0.68819215, 0.69218851, 0.69002884, 0.69082163],
       [0.68655529, 0.69126996, 0.69358342, 0.69082163, 0.69008991]])

another update
it's not related to multivariate-t directly, it's the small df

for df=500 in mv-t, the results look good, or as good as before, we are close to normal distribution

pearson              (-0.0017870552559519275, 0.0027325730504174726)
pearson_oracle       (-0.0017870552559519275, 0.0027325730504174726)
ogk_raw              (-0.0018909302564192635, 0.006559487533916925)
ogk_rw               (-0.005915265666546422, 0.004530245856540806)
ogk_rw_unscaled      (-0.08004284456065859, 0.011457443972481957)
tyler                (0.060397312613018624, 0.01059260768296218)
tyler_rescaled       (-0.0017623837631354593, 0.0038980473132122317)
tyler_wscaled        (-0.19901632023885543, 0.05285228352755771)
t                    (-0.0022961112085661097, 0.0032653789885521345)
iter_qu              (0.007507979749940001, 0.013415554456148315)

@josef-pkt

josef-pkt commented Jan 17, 2024 •

Copy link
Copy Markdown
Member Author

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
To get the covariance matrix we still need to correct for this tail heaviness.

Similarly, I guess, the t estimator estimates also this t-shape matrix and not the covariance.

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.
update to this: this is an artificial effect, I think. We are off by a factor, bias of correlation is 0 * factor. The wrong scaling still leaves zeros to be zero.
to check this I need to compute statistics for the trace/variances.
see next comment

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.
However, for non-normal elliptical distributions we only estimate some scatter matrices, i.e. shape (normalized scatter) is fine, but scaling might not correspond to covariance (i.e. consistent estimate of covariance up to a scaling factor, but scaling is method specific and not consistently estimated unless reference distribution is normal)

Two possibilities

  • use t-distribution (for given or estimated df) as reference distribution if we suspect heavy tailed data
  • use scaling based on robust variance estimators, e.g. set scaling so that trace(scatter) = sum(variances). But that will run into the same problem if the robust variance estimate uses correction factor for a (normal) reference distribution (like mad, iqr, ...)

more MC:
check that covariance matrix from df corrected multivariate-t shape matrix estimate has better small sample properties than pearson covariance if underlying data is heavy tailed but without outliers.

@josef-pkt

josef-pkt commented Jan 17, 2024 •

Copy link
Copy Markdown
Member Author

adding statistics for trace in MC

toplitz,
nobs=100, n_repl=100 so it's faster, but results are similar to increasing those
normal distribution rvs
one definition difference to before
I dropped rescale for ogk_raw, i.e. now it's rcov.cov_ogk(x, rescale_raw=False)
(and tyler_wscaled had a bug in definition AFAICS)

last column is average trace of the ratio estimate / dgp, of cov divided by k_vars to get ration per diagonal element
second last column is trace of mse np.trace(((res - cov)**2).T).mean() / k_vars
third column is bias in trace(estimate - dgp) / k_vars

ogk_rw_unscaled and tyler are not correctly scaled for covariance
all other are pretty close to trace ratio=1

t, tyler_rescaled and ogk_rw have lowest trace mse (after pearson)

pearson              (-0.010121798502342344, 0.031658440521423754, -0.014254187722945153, 0.04824191864506138, 0.9904972081847031)
pearson_oracle       (-0.010121798502342344, 0.031658440521423754, -0.014254187722945153, 0.04824191864506138, 0.9904972081847031)
gk                   (-0.01402884194357211, 0.08357338635334474, -0.01210056932416316, 0.1336181742181662, 0.9919329537838912)
ogk_raw              (-0.0017469093788409368, 0.08418047339261571, 0.014256930830604937, 0.1338587143513144, 1.0095046205537364)
ogk_rw               (-0.028028051385295315, 0.05550799939443335, -0.04678398434439665, 0.08708069941037547, 0.9688106771037356)
ogk_rw_unscaled      (-0.13632211440909214, 0.06298992516923513, -0.26658961652187874, 0.13222353532547343, 0.8222735889854142)
tyler                (0.10013130181496764, 0.09430681109921885, 0.20557701093139863, 0.17916489075875025, 1.1370513406209324)
tyler_rescaled       (-0.009929383519914287, 0.04713812334819595, -0.009721485781405819, 0.07207234992188319, 0.9935190094790629)
tyler_wscaled        (0.04204153660765845, 0.13277197843307367, 0.07275355511068463, 0.278657544472361, 1.0485023700737899)
t                    (-0.01446423540873472, 0.03794023549857343, -0.021853509995089993, 0.060511152192371055, 0.9854309933366066)
iter_qu              (0.05274305143693057, 0.16394736190358147, 0.12228683623282474, 0.24734210603275128, 1.0815245574885497)

@josef-pkt

Copy link
Copy Markdown
Member Author

_cov_starting again

It looks like the initial robust standardization/zscoring follows DetMCD. see Hubert et al 2012.
They also add an orthogonalization step as in OGK, that's currently not in the _cov_starting function.

DetMCD uses only the distances computed using the initial cov estimate to select the "central" observations. Scaling is irrelevant in this case.
So they don't need to revert any initial scaling/standardization.

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

    1. get preliminary, starting distances
    • robust standardization/zscoring z = (x - median) / robust_scale (they use Qn if nobs < 1000 and tau-scale otherwise in the MC)
    • compute set of intial cov estimates, OGK, normal scores, ... (they have 6)
    • orthogonalization step with robust scale for principal components, as in OGK
    • select observations with smallest distances
    1. C-step, refine estimates for n/2 (or similar number, (n+p+1)/2 in MC) of estimations using original data, and
      • choose solution with smallest determinant
  • reweighting step

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.
If we only remove outliers, then we don't need a correction factor for truncation (for reweighted cov) .
AFAICS, they only use the reweighted DetMCD and not the raw DetMCD. They don't mention any truncation correction for the raw DetMCD which has a large truncation fraction.
Their reweighting step uses chi2 ppf at 0.975 as cutoff.

Comment thread statsmodels/robust/covariance.py Outdated
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,

@josef-pkt josef-pkt Jan 22, 2024 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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,

@josef-pkt josef-pkt Jan 22, 2024 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

@josef-pkt

Copy link
Copy Markdown
Member Author

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
reference in comment is DetS article (which I don't find right now)

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.
Although:

  • reweighted trimmed estimators will be nearly distribution free (as mean/OLS and pearson cov on outlier trimmed data)
  • some statistics/estimators are scale invariant, so scaling factor is irrelevant

Aside: I have not looked at the literature on robust regression if some regressors are categorical or binary.

@josef-pkt

josef-pkt commented Feb 10, 2024 •

Copy link
Copy Markdown
Member Author

I just saw: this PR add _scale_iter to robust.scale module
AFAICS, it is the base function for M-scale estimation, needed in e.g. S-estimator and MM-estimator of cov and (IIRC) regression.
almost empty docstring, no references although it's used in many articles and text books.

unit test has number for scale_bias b, but no comment for source/reference
uses default biscale parameter c=4.685, with b equal to scale_bias = 0.43684963023076195
related Salibian-Barrera and Yohai 2006 Fast-S regression use c = 1.547 and b=0.5 referring to book by Rousseeuw and Leroy 1987 see below

I don't remember why I called the norm meef_scale.
It needs a helper function for computing fisher consistency correction term, need both univariate (for regression based on normal) and multivariate (for mean-cov and multivariate regression, based on chi or chi2).
We should be able to hardcode explicit formulas for specific norms/meef_scale and compute generically for other norms by numerical integration.

from Rousseeuw and Leroy 1987, p. 142

Table 19. Asymptotic Efficiency of S-Estimators for
different Values of E*, Making use of Tukey’s
Biweight Function
~~
bdp% eff% c K (same as b)

array([[50.    , 28.7   ,  1.547 ,  0.1995],
       [45.    , 37.    ,  1.756 ,  0.2312],
       [40.    , 46.2   ,  1.988 ,  0.2634],
       [35.    , 56.    ,  2.251 ,  0.2957],
       [30.    , 66.1   ,  2.56  ,  0.3278],
       [25.    , 75.9   ,  2.937 ,  0.3593],
       [20.    , 84.7   ,  3.42  ,  0.3899],
       [15.    , 91.7   ,  4.096 ,  0.4194],
       [10.    , 96.6   ,  5.182 ,  0.4475]])

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)

from statsmodels.robust import norms​
c, b = 1.547, 0.1995
norm = norms.TukeyBiweight(c=c)
m = norm(c)
m, b / m
(0.39886816666666663, 0.5001652592815755)

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.

@josef-pkt

Copy link
Copy Markdown
Member Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants