Skip to content

WIP ENH: Outlier robust covariance - #3230

Closed
josef-pkt wants to merge 16 commits into
statsmodels:mainfrom
josef-pkt:outlier_cov
Closed

josef-pkt wants to merge 16 commits into
statsmodels:mainfrom
josef-pkt:outlier_cov

Conversation

@josef-pkt

@josef-pkt josef-pkt commented Oct 8, 2016 •

Copy link
Copy Markdown
Member

see #3221

getting started, some parts are almost clean
for other parts I need to collect functions from various scripts so I can start on a consistent collection

contains:

  • stats.covariance gaussian rank correlation, quadrant correlation, and helper function to transform for consistency at the normal distribution (only regression tests)
  • robust.covariance:
    • supporting function: tau_scale (currently wrong location, written to support OGK)
    • GK, OGK: verified agains R robustbase, but unit tests don't have numbers from R yet.
    • Tyler : this is currently just my old function, not verified or checked again
    • iterative weighted covariance: with t-distribution weights (smoke test)
  • scale estimators:
    • _scale_iter: basic iterative M-estimator for scale, IIRC, given rho function, approximate unit test
    • trimmed_scale: another old function, not reviewed again
    • ? I still have an m-scale function that uses scipy fsolve, maybe obsolete given the iterative solvers

problems to address

  • perfect prediction (mad=0) again: When we use mad as initial estimate, we get scale=0 if more than half of the observations fit perfectly. see REF/ENH RLM and robust scale for almost perfect prediction #1341
    • we need to handle the scale=0 special case in the calculations and add unit tests
    • we need options to choose the fraction of resid=0 at which we want scale=0 (comments in an article, which ? IIRC a tau-scale article), use trimmed variance as alternative to mad as starting value ?

Terminology

  • Is scale std or var in robust? Are we consistent?
    scale_trimmed returns standard deviation.
    (difference scale in distribution is std (sigma), scale in regression is var (sigma**2)
  • covariance, scatter, shape in elliptical distribution
    • cov either covariance or scatter matrix, as returned by functions, scaling depends on options or implementation details
    • covariance: expected second moment, (of distribution parameter or random variable)
    • scatter: covariance that is not necessarily scale or has indeterminate scale, e.g. Tyler
    • shape: covariance matrix scale so that det(cov) = 1, i.e. covariance = scale * shape
  • center of location: center, median, mean, loc. What is the generic term?
    • mean returned by functions for the center, i.e. mean or expected value of data excluding outliers
      ok for symmetric distribution where mean is the center, e.g. median estimates the mean.
      Need to be more explicit for skewed distributions, but main value of interest is mean (expected value), but we also have median and location parameters which might differ.


def mahalanobis(data, cov=None, cov_inv=None):
"""Mahalanobis distance

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.

note: this does not return the sqrt


def cov_gk1(x, y, scale_func=mad):
"""Gnanadesikan and Kettenring covariance between two variables

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.

maybe add option for general version, i.e. a, b coefficient as in Huber/Ronchetti book (?)
or normalized by scale of x and of y.

cf = 2 * ((1 - c**2) * stats.norm.cdf(c) - c * stats.norm.pdf(c)
+ c**2) - 1
#return Holder(loc=mean, scale=np.sqrt(var / cf))
return mean, np.sqrt(var / cf)

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.

return holder ?

Comment thread statsmodels/robust/covariance.py Outdated

# calculate MAD only once if needed
if start_cov is None or shrinkage_factor is None:
scale_mad = sm.robust.mad(x, center=0)

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.

drop sm (pylint error)

Comment thread statsmodels/robust/covariance.py Outdated
if diff < eps:
break

return c, i, shrinkage_factor, corr

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.

return Holder, CovResults instead

for it in range(maxiter):
dist = mahalanobis(data, cov=cov)
w = weights_func(dist, *weights_args)
cov, mean = cov_weighted(data, w)

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.

in general we need different options for denominator in weighted cov.
standard M does not rescale cov by wsum

Comment thread statsmodels/robust/covariance.py Outdated
s = np.median(dist) / stats.chi2.ppf(0.5, k_vars)
cov *= s

return cov, mean, w, dist, it, converged

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.

return Holder or CovResults for consistent pattern. This is partially a tools function.

def _scale_iter(data, scale0='mad', maxiter=10, rtol=1e-6, atol=1e-8,
meef_scale=None, scale_bias=None):
"""iterative scale estimate base on "rho" function

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.

docstring, requirement for meef_scale

is this a standard M-estimator of scale?

scale_old = scale
for i in range(maxiter):
x_scaled = x / scale
weights_scale = meef_scale(x_scaled) / (1e-50 + x_scaled**2)

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.

this looks like an unnecessary detour: either use weights_scale as argument or usemeef_scale (i.e. "rho") in the iteration.

def _scale_iter(data, scale0='mad', maxiter=10, rtol=1e-6, atol=1e-8,
meef_scale=None, scale_bias=None):
"""iterative scale estimate base on "rho" function

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.

rename scale_bias?
need consistent terminology for various consistency or normalization "constants"

@josef-pkt

Copy link
Copy Markdown
Member Author

rebased, a few merge conflict in test_scale

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.006%) to 81.892% when pulling df6d678 on josef-pkt:outlier_cov into 5b8f20d on statsmodels:master.

x_scaled = x / scale
weights_scale = meef_scale(x_scaled) / (1e-50 + x_scaled**2)
if debug:
print('weights sum', weights_scale.sum(), end=" ")

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.

print syntax is not py 2 compatible

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.007%) to 81.892% when pulling f698b3d on josef-pkt:outlier_cov into 5b8f20d on statsmodels:master.

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.006%) to 81.892% when pulling 450a606 on josef-pkt:outlier_cov into 5b8f20d on statsmodels:master.

@josef-pkt

Copy link
Copy Markdown
Member Author

We need to start to add future division everywhere (like scipy), that's more efficient than chasing every failure to see which module is missing it.
amended the last commit again with hopefully the last needed future import

@coveralls

coveralls commented Nov 1, 2017 •

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.03%) to 81.913% when pulling 6f124aa on josef-pkt:outlier_cov into 5b8f20d on statsmodels:master.

@josef-pkt

Copy link
Copy Markdown
Member Author

This pull request introduces 2 alerts - view on lgtm.com

new alerts:

  • 2 for Variable defined multiple times

Comment posted by lgtm.com

@codecov-io

codecov-io commented Nov 1, 2017 •

Copy link
Copy Markdown

Codecov Report

Merging #3230 into master will decrease coverage by <.01%.
The diff coverage is 78.02%.

Impacted file tree graph

@@            Coverage Diff             @@
##           master    #3230      +/-   ##
==========================================
- Coverage   79.32%   79.31%   -0.01%     
==========================================
  Files         544      548       +4     
  Lines       81718    82295     +577     
  Branches     9255     9339      +84     
==========================================
+ Hits        64822    65274     +452     
- Misses      14802    14884      +82     
- Partials     2094     2137      +43
Impacted Files Coverage Δ
statsmodels/robust/tests/test_covariance.py 100% <100%> (ø)
statsmodels/stats/tests/test_covariance.py 100% <100%> (ø)
statsmodels/robust/covariance.py 69.09% <69.09%> (ø)
statsmodels/robust/scale.py 79.69% <73.01%> (-6.02%) ⬇️
statsmodels/stats/covariance.py 74.32% <74.32%> (ø)
statsmodels/robust/tests/test_scale.py 93.91% <94.59%> (+0.24%) ⬆️
... and 1 more

Continue to review full report at Codecov.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update 5b8f20d...6f124aa. Read the comment docs.

@josef-pkt

josef-pkt commented Dec 7, 2018 •

Copy link
Copy Markdown
Member Author

(When I was waiting at the dentists office I saw that I had rrcov documentation on my iPad.)
rrcov has most of the related methods, but random algorithm might not allow for very tight test tolerance.
unit tests !

@josef-pkt

Copy link
Copy Markdown
Member Author

unit test coverage is low but not too bad 75% for both main modules

with unit tests against R package rrcov, we should be able to get good enough coverage for merging.
rrcov has a class based implementation.

@josef-pkt

Copy link
Copy Markdown
Member Author

many merge conflicts in test_scale.py
test_scale has been pep-8-ed and blackened

@josef-pkt josef-pkt added the superseded Used for PRs with content that is superseded by a newer PR label Feb 17, 2022
@josef-pkt

Copy link
Copy Markdown
Member Author

rebased version in #8129

@josef-pkt

Copy link
Copy Markdown
Member Author

closing #8129 has been merged

@josef-pkt josef-pkt closed this Jun 19, 2024
@josef-pkt josef-pkt modified the milestones: josef, 0.15 Jun 19, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-robust comp-stats superseded Used for PRs with content that is superseded by a newer PR type-enh

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants