Skip to content

BUG: Add finite check for _MinimalWLS - #4960

Merged
bashtage merged 1 commit into
statsmodels:masterfrom
bashtage:minimial-wls-check
May 6, 2019
Merged

bashtage merged 1 commit into
statsmodels:masterfrom
bashtage:minimial-wls-check

Conversation

@bashtage

Copy link
Copy Markdown
Member

Add optional finite check for _MinimalWLS

closes #4566

@coveralls

coveralls commented Aug 22, 2018 •

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.04%) to 84.578% when pulling b7452c7 on bashtage:minimial-wls-check into fb6d268 on statsmodels:master.

@codecov-io

codecov-io commented Aug 22, 2018 •

Copy link
Copy Markdown

Codecov Report

Merging #4960 into master will decrease coverage by 0.46%.
The diff coverage is 100%.

Impacted file tree graph

@@            Coverage Diff             @@
##           master    #4960      +/-   ##
==========================================
- Coverage      82%   81.54%   -0.47%     
==========================================
  Files         588      569      -19     
  Lines       93362    89641    -3721     
  Branches    10372    10032     -340     
==========================================
- Hits        76566    73096    -3470     
+ Misses      14392    14273     -119     
+ Partials     2404     2272     -132
Impacted Files Coverage Δ
statsmodels/robust/robust_linear_model.py 79.64% <ø> (+0.12%) ⬆️
statsmodels/genmod/generalized_linear_model.py 90.72% <100%> (-0.43%) ⬇️
statsmodels/regression/tests/test_tools.py 100% <100%> (ø) ⬆️
statsmodels/regression/_tools.py 100% <100%> (ø) ⬆️
statsmodels/tsa/kalmanf/kalmanfilter.py 36.08% <0%> (-53.01%) ⬇️
statsmodels/tools/_testing.py 59.09% <0%> (-33.02%) ⬇️
statsmodels/sandbox/utils_old.py 41.66% <0%> (-27.3%) ⬇️
statsmodels/tools/grouputils.py 61.2% <0%> (-6.19%) ⬇️
statsmodels/sandbox/distributions/multivariate.py 65.21% <0%> (-5%) ⬇️
statsmodels/base/elastic_net.py 87.39% <0%> (-3.37%) ⬇️
... and 241 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 fb6d268...b7452c7. Read the comment docs.

Comment thread statsmodels/regression/_tools.py Outdated
self.exog = exog
self.weights = weights
if check_finite:
msg = 'NaN/inf detected in {0], estimation infeasible.'

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Typo brace/bracket?

@bashtage
bashtage force-pushed the minimial-wls-check branch 2 times, most recently from dc55eb6 to 42902bc Compare August 23, 2018 22:17
@bashtage
bashtage force-pushed the minimial-wls-check branch 2 times, most recently from 8794875 to db7e079 Compare September 13, 2018 09:54
Comment thread statsmodels/regression/_tools.py Outdated
self.weights = weights
if check_finite:
msg = 'NaN/inf detected in {0}, estimation infeasible.'
if not np.all(np.isfinite(endog)):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

the fastest way to check this is to use np.isfinite(endog.ptp()) according to a stackoverflow (?) question
(the only disadvantage is that it causes a numpy warning if there is a nan or inf, e.g. in the unit tests)
np.all(np.isfinite( needs to loop through the array twice and needs to create an intermediate elementwise array

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.

%timeit np.all(np.isfinite(endog))
748 µs ± 33.3 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

%timeit np.isfinite(endog.ptp())
1.02 ms ± 47.8 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

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.

%timeit np.isfinite(endog)
641 µs ± 24.1 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

%timeit endog.ptp()
982 µs ± 7.85 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

%timeit endog.sum()
924 µs ± 8.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

that's what I get in my older setup

x = np.random.randn(100000, 5)
%timeit np.all(np.isfinite(x))
%timeit np.isfinite(x.ptp())
1000 loops, best of 3: 962 µs per loop
1000 loops, best of 3: 227 µs per loop

a quick stackoverflow search finds https://stackoverflow.com/questions/6736590/fast-check-for-nan-in-numpy
but I don't remember from where I got the ptp part

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.

On your example

%timeit np.all(np.isfinite(x))
283 µs ± 5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

%timeit np.isfinite(x.ptp())
365 µs ± 5.35 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

Comment thread statsmodels/regression/_tools.py Outdated
raise ValueError(msg.format('endog'))
if not np.all(np.isfinite(weights)):
raise ValueError(msg.format('weights'))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I think to catch algorithmic problems, e.g. negative weights, we need to do the check on w_half

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.

Is there a scenario where w_half is not OK but weights is? Computing w_half when there is an issue will likely raise a warning before the exception is thrown.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The problems is negative weights which cause nans in w_half, which will cause a Warning but doesn't prevent the nans to go into linalg.

I don't remember or know in which part the problem was in my example when I ran into this, the reason for the problem was "user error".
IIRC, we should get it in a linear probability model for GLM Binomial when predicted is outside open interval (0, 1), but maybe we "sanitize" it in this case by clipping.
There is a set of issues related to this #2208 where we intentionally don't have a properly defined model.

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 switched it around.

@josef-pkt

Copy link
Copy Markdown
Member

another issue, AFAICS:
In the application for IRLS in RLM, we only need to check endog and exog once, but we need to check sqrt(weights) repeatedly.
in GLM however, the endog and exog in the call to minimal wls use wendog, wexog which change, or at least wendog changes.

@josef-pkt

Copy link
Copy Markdown
Member

one example case for the performance impact would be @thequackdaddy case with 5 to 10 Million observations.

@bashtage

Copy link
Copy Markdown
Member Author

With 10M obs it adds about 25ms per iteration. Is suspect this is negligible compared to the actual cost of the fit. But I can make the tests separately optional.

@bashtage

Copy link
Copy Markdown
Member Author

These are mostly to prevent hangs that are unexplainable by end users, rather than to be a method to detect algorithmic problems.

@josef-pkt

Copy link
Copy Markdown
Member

I'm copying part of my inline comment here for easier reference

--
I don't remember or know in which part the problem was in my example when I ran into this, the reason for the problem was "user error".
IIRC, we should get it in a linear probability model for GLM Binomial when predicted is outside open interval (0, 1), but maybe we "sanitize" it in this case by clipping.
There is a set of issues related to this #2208 where we intentionally don't have a properly defined model.

--

The problem is that we intentionally allow misspecified models.
The isfinite check should be a safeguard for cases when the misspecification is not correctly/safely handled by the algorithm, i.e. IRLS.
For known problems, either because of misspecification or because of data problems like edge cases, we can catch and handle them directly, like clipping in the families. However, that problem handling is incomplete and might always leave some unhandled cases that might end up with not finite values in IRLS.

@bashtage

Copy link
Copy Markdown
Member Author

Some benchmarks, % slowdown with checks

n      slowdown
500    6.99%
5000   5.32%
50000  1.64%
500000 0.56%

Check is O(n), iterative estimator is O(n^2) so negligible for large models.

"""

def __init__(self, endog, exog, weights=1.0):
msg = 'NaN, inf or invalid value detected in {0}, estimation infeasible.'

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

why is this a class attribute?

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.

Probably an unnecessary optimization preventing the string from being re-created in each instance.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks. I've been porting a bunch of your PRs to sm2, will probably put this inside __init__ there.

Add optional finite check for _MinimalWLS
Add separate checks for endo and weights and adjust use upstream

closes statsmodels#4566
@bashtage
bashtage force-pushed the minimial-wls-check branch from dcb9440 to b7452c7 Compare May 6, 2019 07:18
@bashtage
bashtage merged commit ebd7a4c into statsmodels:master May 6, 2019
@bashtage
bashtage deleted the minimial-wls-check branch May 6, 2019 08:09
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

ENH/REF isfinite check when using _MinimalWLS

5 participants