Skip to content

ENH: White spec test (issue1126) - #4721

Closed
JimVaranelli wants to merge 8 commits into
statsmodels:masterfrom
JimVaranelli:issue1126
Closed

JimVaranelli wants to merge 8 commits into
statsmodels:masterfrom
JimVaranelli:issue1126

Conversation

@JimVaranelli

@JimVaranelli JimVaranelli commented Jun 7, 2018 •

Copy link
Copy Markdown
Contributor

White's two-moment specification test. Unit test compares to SAS 9.3.

#1126

Comment thread statsmodels/sandbox/stats/diagnostic.py Outdated
# chi-square test
dof = devx.shape[1]
pval = stats.chi2.sf(stat, dof)
return dof, stat, pval

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.

stat, pval, dof
if we return tuple

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This was updated in the previous commit - forgot to update this note.

@josef-pkt josef-pkt left a comment

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.

A quick first review with comments about the things that I can see quickly.
I will do a fuller review over the next days.

I think it looks good overall.
Thanks

i0, i1 = np.triu_indices(x.shape[1])
exog = np.delete(x[:,i0]*x[:,i1], 0, 1)
assert exog.shape[1] == nvar + nvar * (nvar + 1) / 2
# collinearity check - see _fit_collinear

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.

blank line before makes it easier to quickly skim the blocks

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done.

Comment thread statsmodels/sandbox/stats/diagnostic.py Outdated
sqmndevs = sqe - np.mean(sqe)
D = np.dot(exog.T, sqmndevs)
devx = exog - np.mean(exog, axis=0)
B = np.linalg.multi_dot([devx.T, np.diag(np.square(sqmndevs)), devx])

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.

we can avoid creating diagonal matrices
e.g. x.T dot diag(s) dot x = (x.T * s).dot(x)

however, in this case I would do something like
after
devx = exog - np.mean(exog, axis=0)

devx *= sqmndevs[:, None]
B = devx.T.dot(devx)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This looks reasonable but I want to experiment with it some more. I will update it the next commit.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks for the pointer to the newaxis function it was a new one for me and it works great in this particular instance. Updated.

Comment thread statsmodels/sandbox/stats/diagnostic.py Outdated
nvar = x.shape[1] - 1
# add interaction terms
i0, i1 = np.triu_indices(x.shape[1])
exog = np.delete(x[:,i0]*x[:,i1], 0, 1)

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.

whitespace around operators except **

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done.

Comment thread statsmodels/sandbox/stats/diagnostic.py Outdated
mask = np.abs(r.diagonal()) < np.sqrt(tol)
exog = exog[:,np.where(~mask)[0]]
# calculate test statistic
sqe = np.square(e)

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.

Is there an advantage to using square instead of just e*e or e**2?
(I needed to look up what square does because I never used it.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I actually had e * e in the first cut but np.square may be faster for ;large arrays. We have the same square function in our c++ vector / matrix classes so I went with it. But I think in the majority of cases there will be no real difference so I switched it back.

def test_spec_white(self):
resdir = os.path.join(cur_dir, "results")
wsfiles = ['wspec1.csv', 'wspec2.csv', 'wspec3.csv', 'wspec4.csv']
for file in os.listdir(resdir):

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 this os.listdir can be skipped
just loop over wsfiles directly

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I chose the method shown more out of fault tolerance than any performance concerns but now that I think about it if someone accidentally removes one of the test files the correct action is to error out. I will change it in the next commit.

Comment thread statsmodels/sandbox/stats/diagnostic.py Outdated
D = np.dot(exog.T, sqmndevs)
devx = exog - np.mean(exog, axis=0)
B = np.linalg.multi_dot([devx.T, np.diag(np.square(sqmndevs)), devx])
stat = np.linalg.multi_dot([D, np.linalg.inv(B), D])

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.

if we don't need the explicit inverse, then using linalg.solve is better
stats = D.dot.(np.linalg.solve(B, D)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I will take a closer look and update in the next commit.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I took a closer look at the np.solve and it indeed has speed/accuracy advantage for large arrays. Our local modeling tends to be very small sample sizes (nobs<50) so this has no practical significance in our environment but it is definitely helpful in the general case here. Updated.

@josef-pkt

Copy link
Copy Markdown
Member

This pull request introduces 1 alert when merging 271b828 into 8928f8d - view on LGTM.com

new alerts:

  • 1 for Module-level cyclic import

Comment posted by LGTM.com

@josef-pkt

Copy link
Copy Markdown
Member

BTW: You can ignore the LGTM circular import alerts.
All the ones I checked before where false alarm.

@coveralls

coveralls commented Jun 7, 2018 •

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.4%) to 83.859% when pulling c8fe207 on JimVaranelli:issue1126 into 8928f8d on statsmodels:master.

@josef-pkt

Copy link
Copy Markdown
Member

This pull request introduces 1 alert when merging bb23f81 into 8928f8d - view on LGTM.com

new alerts:

  • 1 for Module-level cyclic import

Comment posted by LGTM.com

@josef-pkt

Copy link
Copy Markdown
Member

This pull request introduces 1 alert when merging 5adc464 into 8928f8d - view on LGTM.com

new alerts:

  • 1 for Module-level cyclic import

Comment posted by LGTM.com

@josef-pkt

Copy link
Copy Markdown
Member

This pull request introduces 1 alert when merging 256bf53 into 8928f8d - view on LGTM.com

new alerts:

  • 1 for Module-level cyclic import

Comment posted by LGTM.com

@codecov-io

codecov-io commented Jun 9, 2018 •

Copy link
Copy Markdown

Codecov Report

Merging #4721 into master will increase coverage by 0.49%.
The diff coverage is 95%.

Impacted file tree graph

@@            Coverage Diff             @@
##           master    #4721      +/-   ##
==========================================
+ Coverage   80.88%   81.38%   +0.49%     
==========================================
  Files         577      581       +4     
  Lines       88572    90234    +1662     
  Branches     9885    10082     +197     
==========================================
+ Hits        71642    73435    +1793     
+ Misses      14672    14505     -167     
- Partials     2258     2294      +36
Impacted Files Coverage Δ
statsmodels/stats/diagnostic.py 100% <ø> (ø) ⬆️
statsmodels/stats/tests/test_diagnostic.py 92.19% <100%> (+0.42%) ⬆️
statsmodels/sandbox/stats/diagnostic.py 60.23% <90.9%> (+1.37%) ⬆️
statsmodels/tsa/holtwinters.py 90.19% <0%> (-4.9%) ⬇️
statsmodels/tsa/statespace/kalman_filter.py 84.16% <0%> (-3.54%) ⬇️
statsmodels/regression/recursive_ls.py 93.77% <0%> (-3.09%) ⬇️
statsmodels/stats/correlation_tools.py 90.27% <0%> (-3.06%) ⬇️
statsmodels/tsa/stattools.py 82.65% <0%> (-1.28%) ⬇️
statsmodels/tools/_testing.py 59.09% <0%> (-0.62%) ⬇️
...tatsmodels/sandbox/panel/correlation_structures.py 32.78% <0%> (-0.55%) ⬇️
... and 141 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 8928f8d...c8fe207. Read the comment docs.

@josef-pkt

Copy link
Copy Markdown
Member

@JimVaranelli Thank you

LGTM, the linear algebra looks good, but I didn't try to understand the computation.

Can you squash this?
AFAICS, earlier commits don't provide additional information in this case.

Comment thread statsmodels/sandbox/stats/diagnostic.py Outdated
# add interaction terms
i0, i1 = np.triu_indices(x.shape[1])
exog = np.delete(x[:,i0] * x[:,i1], 0, 1)
assert exog.shape[1] == nvar + nvar * (nvar + 1) / 2

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.

Should not leave assertions in final code

return lm, lm_pval, ftest


def spec_white(resid, exog):

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.

This should be added to the main code, not sandbox. Virtually nothing gets out of the sb, and if tested, then it should be in main.

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.

Agreed.

Comment thread statsmodels/sandbox/stats/diagnostic.py Outdated
# calculate test statistic
sqe = e * e
sqmndevs = sqe - np.mean(sqe)
D = np.dot(exog.T, sqmndevs)

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.

should use lowercase for better pep compliance.

Comment thread statsmodels/sandbox/stats/diagnostic.py Outdated
D = np.dot(exog.T, sqmndevs)
devx = exog - np.mean(exog, axis=0)
devx *= sqmndevs[:, None]
B = devx.T.dot(devx)

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.

same.

---------
White, H. (1980). A heteroskedasticity-consistent covariance matrix
estimator and a direct test for heteroscedasticity. Econometrica,
48: 817-838.

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.

See also for het_white

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

@bashtage @josef-pkt - Sorry for the delay. I made the changes above except for relocating out of sandbox. I believe the reason it's in sandbox is due to the still experimental nature of the collinearity check. Is this correct?

Also, there's been no further comments regarding the Zivot-Andrews test. Is there still interest in my generating a PR for that? See #4746

@JimVaranelli

Copy link
Copy Markdown
Contributor Author

Cleared the Codacy unused variable check. Not sure what to do about the test_spec_white() method could be a function complaint?

@josef-pkt

Copy link
Copy Markdown
Member

Not sure what to do about the test_spec_white() method could be a function complaint?

You added the test as a method to a test class, but you are not actually using anything in self, e.g. any of the data or results attached to the class/instance.
In this case it is better to move the test into a separate function (not as method inside a class) next to the other test functions.

@JimVaranelli

Copy link
Copy Markdown
Contributor Author

Moved the static function outside of the class.

@bashtage

Copy link
Copy Markdown
Member

@josef-pkt Looks ready.

@JimVaranelli We can wait to move it out of the sandbox. This is a nice function and should be in main sm. There are a few other diagnostic functions in sandbox that can be moved at the same time in a later PR once this is merged.

@josef-pkt

Copy link
Copy Markdown
Member

LGTM, the only issue is to clean up the commit history.
The best would be to open a new PR with rebase and completely squashed commits.
The current commit messages are mostly uninformative, but it might still be useful to leave this PR branch unchanged for the record.

@JimVaranelli

Copy link
Copy Markdown
Contributor Author

@josef-pkt Sorry for the delay I've been swamped with deliverable deadlines these past few weeks. I should be able to get the new PR out this weekend or early next week. I will also finalize the code for the ZA test (#4746) and generate a PR. With @bashtage code optimization I think SM will have the best publically available version of that particular test.

@JimVaranelli

Copy link
Copy Markdown
Contributor Author

@josef-pkt Sorry again for the delay here. Would you still like me to create a new clean PR for this? I expect to submit a new PR for #4746 in the next few days.

@josef-pkt

Copy link
Copy Markdown
Member

@JimVaranelli Yes, please do.

I put on my personal todo list to rebase PRs that are essentially ready for merging but have fallen too far behind master.
(But currently my checkout is still dirty with uncommitted changes for my own PRs.)

@JimVaranelli

Copy link
Copy Markdown
Contributor Author

@josef-pkt OK will do. I'll definitely get that done this weekend. I'll also try to push out the ZA test PR this weekend as well but if not this weekend then early next week.

@JimVaranelli

Copy link
Copy Markdown
Contributor Author

@josef-pkt Added PR 5452 for clean commit history

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.

6 participants