Skip to content

Score/LM conditional moment tests - #2096

Merged
josef-pkt merged 11 commits into
statsmodels:masterfrom
josef-pkt:score_cm_test
Jun 5, 2018
Merged

josef-pkt merged 11 commits into
statsmodels:masterfrom
josef-pkt:score_cm_test

Conversation

@josef-pkt

Copy link
Copy Markdown
Member

first round of adding generic robust score/LM and conditional moment tests

see #2041 for summary issue

most generic tests have unit tests for OLS case
some generic functions are untested
also includes GLM specific cm/lmtest, and Poisson over/under dispersion tests, no test coverage

I might want to merge this with only variable addition as verified use case and leave other applications and extensions for another PR.

Note: efficient GMM (with optimal weighting matrix): weighting matrix is irrelevant if we estimate with exactly identified model. However, Newey West say that the optimization like (Q)MLE or M-estimator with constraints is not efficient. (refering to CMT in Newey 1985 GMM versus Newey/West efficient GMM)

TODO

  • needs a GLM case as unit test
  • needs examples and unit tests for hypothesis on variances and error correlation.

Extensions

For the next two it is not clear yet whether the generic/general case can handle those. My guess is that it should be covered already.

  • nuisance parameters under alternative hypothesis,
    example Wooldridge variance tests in GLM/LEF joint with mean
  • locally mis-specified alternative, Bera and Yoon
    This looks just like a test on only some of the overidentifying restrictions but partialling out all other alternatives, but I haven't verified that yet.
  • cov_type: we don't have a simple function yet to calculate robust covariances standalone
  • other extensions are to use this to implement specific functions

@josef-pkt

Copy link
Copy Markdown
Member Author

There are/were some problems with Coveralls.io
I'm currently able to see this
https://coveralls.io/files/356696207
but no summary statistics for coverage and front page hasn't updated in a while
https://coveralls.io/r/statsmodels/statsmodels

(scipy's frontpage also hasn't updated since the same day)

@josef-pkt josef-pkt added this to the 0.7 milestone Nov 18, 2014
@josef-pkt josef-pkt mentioned this pull request Jan 8, 2015
29 tasks
@josef-pkt josef-pkt modified the milestones: 0.8, 0.7 Feb 4, 2015
@josef-pkt

Copy link
Copy Markdown
Member Author

moved to 0.8
no reason to put it in if it doesn't have a public function, and it's not yet used internally anywhere else.

@josef-pkt

Copy link
Copy Markdown
Member Author

see #2637 (comment)
I need to go back and use the GMM framework directly.

@josef-pkt josef-pkt left a comment

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.

brief superficial skimming

I guess this needs more examples in unit tests.
AFAIR, these functions are not in other packages, but we might be able to test some special cases.

Also, check for larger nobs where hypothesis tests should be equivalent in large samples.
Otherwise, we can check some examples with Monte Carlos.

Comment thread statsmodels/stats/_diagnostic_other.py Outdated
return stat, pval, stat2


def lm_robust(score, R, Ainv, B, V=None):

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.

replace 1 letter names

Comment thread statsmodels/stats/_diagnostic_other.py Outdated
return lm_stat#, lm_stat2


def lm_robust_subset(score, k_constraints, score_deriv, cov_score):

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 it would be better of k_constraints allows an index as option, instead of assuming sorted by Null hypothesis

Returns
-------
lm_stat : float
score/lagrange multiplier statistic

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.

does not return a results instance, why not?

description.append(['CT nb1 HC1', 'mu (1 + a)'])


return np.array(results_all), description

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 results instance that is more informative ?

return lm_stat, pval


def dispersion_poisson(results):

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.

add method argument instead of always computing all of them

res_ols = OLS(endog_v, ex).fit(cov_type=cov_type, cov_kwds=cov_kwds,
use_t=use_t)

if use_wald:

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 this just internal or a different statistic? no option for this
(I don't remember if these are numerically equivalent procedures)



class TestCMTOLS(CheckCMT):

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.

add code comment to what this is testing

@josef-pkt

Copy link
Copy Markdown
Member Author

Also, by now we should have some special cases for different models which we can use to check/test against.

@josef-pkt

Copy link
Copy Markdown
Member Author

rebased on master (no merge conflicts)

@coveralls

coveralls commented May 20, 2017 •

Copy link
Copy Markdown

Coverage Status

Coverage decreased (-0.2%) to 90.185% when pulling 35c8e77 on josef-pkt:score_cm_test into 90e2af8 on statsmodels:master.

@josef-pkt

Copy link
Copy Markdown
Member Author

all green, test coverage drops quite a bit. (main problem with PR: not much in other packages for verifying this)

maybe just verify with simple MonteCarlo, and add regression tests
There might be examples in Wooldridge textbook, however not exact because there are too many "asymptotically equivalent" versions.

One possibility, use zero restriction i.e. added variable tests as special case.

@josef-pkt

Copy link
Copy Markdown
Member Author

rebased again, no merge conflicts

@coveralls

coveralls commented Nov 1, 2017 •

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.07%) to 83.373% when pulling dbbfc52 on josef-pkt:score_cm_test into d8cb151 on statsmodels:master.

@codecov-io

codecov-io commented Nov 1, 2017 •

Copy link
Copy Markdown

Codecov Report

Merging #2096 into master will increase coverage by 0.06%.
The diff coverage is 86.89%.

Impacted file tree graph

@@            Coverage Diff             @@
##           master    #2096      +/-   ##
==========================================
+ Coverage   80.72%   80.79%   +0.06%     
==========================================
  Files         573      577       +4     
  Lines       88061    88740     +679     
  Branches     9906     9945      +39     
==========================================
+ Hits        71087    71696     +609     
- Misses      14696    14747      +51     
- Partials     2278     2297      +19
Impacted Files Coverage Δ
statsmodels/stats/tests/test_diagnostic_other.py 100% <100%> (ø)
statsmodels/discrete/discrete_model.py 87.93% <100%> (+0.13%) ⬆️
statsmodels/base/_parameter_inference.py 64.47% <64.47%> (ø)
statsmodels/stats/_diagnostic_other.py 80.44% <80.44%> (ø)
statsmodels/genmod/tests/test_score_test.py 99.1% <99.1%> (ø)
statsmodels/stats/descriptivestats.py 24.13% <0%> (ø) ⬆️
statsmodels/regression/recursive_ls.py 96.85% <0%> (ø) ⬆️
statsmodels/regression/tests/test_recursive_ls.py 98.46% <0%> (ø) ⬆️
... and 5 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 c6a76ed...ca84a6a. Read the comment docs.

@josef-pkt

Copy link
Copy Markdown
Member Author

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

new alerts:

  • 2 for Variable defined multiple times
  • 1 for Wrong number of arguments in a call

Comment posted by lgtm.com

@josef-pkt

Copy link
Copy Markdown
Member Author

This pull request introduces 1 alert when merging da5f2ec into c6a76ed - view on LGTM.com

new alerts:

  • 1 for Variable defined multiple times

Comment posted by LGTM.com

@josef-pkt

josef-pkt commented Jun 2, 2018 •

Copy link
Copy Markdown
Member Author

All green, but test coverage for the two code modules is still only 67 and 70 %

I didn't remember that the all methods of computing score and robust score produce identical results, up to linalg floating point precision, at least for the OLS case:

(Pdb) for i in self.res_hc0(): print(i)
('Wooldridge', (1.6385932313951996, 0.44074155619527366))
('Newey', (1.6385932313952039, 0.44074155619527278, 2))
('Tauchen', (1.6385932313952032, 0.44074155619527278, 2))
('score subset QMLE', (1.6385932313952041, 0.44074155619527278))
('scoreB QMLE', 1.6385932313952039)
('scoreV QMLE', 1.6385932313952034)
('cmt', (1.6385932313952036, 0.44074155619527278))
('cmt', (1.6385932313952036, 0.44074155619527278))
('score subset_parts QMLE', (1.6385932313952041, 0.65067106485691695)) 
      # 0.65... differs because I added a different k_constraints so I get a failure  to drop into pdb



(Pdb) for i in self.res_score(): print(i)
('ols R2', 1.6857659627548593)
('score simple', 1.6857659627548425)
('score mle', 1.6857659627548429)
('Newey', (1.6857659627548434, 0.43046770240534737, 2))
('Tauchen', (1.6857659627548427, 0.43046770240534749, 2))


(Pdb) for i in self.res_opg(): print(i)
('ols R2', 1.7222600241848962)
('comp_lm uc', (1.7222600241848816, 0.4226841741195434, 2.0))
('Newey', (1.7222600241848758, 0.42268417411954462, 2))
('Tauchen', (1.7222600241848758, 0.42268417411954462, 2))
('score subset QMLE', (1.7222600241848753, 0.42268417411954462))
('scoreB QMLE', 1.7222600241848809)
('scoreV QMLE', 1.7222600241848807)

@josef-pkt

Copy link
Copy Markdown
Member Author

This pull request introduces 1 alert when merging e70db33 into c6a76ed - view on LGTM.com

new alerts:

  • 1 for Variable defined multiple times

Comment posted by LGTM.com

@josef-pkt

josef-pkt commented Jun 2, 2018 •

Copy link
Copy Markdown
Member Author

all Boos robust, generalized score test functions are now unit tested for OLS
there is still another group of generic cm/lm test functions, but I'm getting close to giving up for now.

this PR is green
one travis 3.6 is failing with
test_lag_order_selection

E                   AssertionError: 
E                   Not equal to tolerance rtol=0, atol=0.0005
E                   Error in LAG ORDER SELECTION - HQIC for:
E                   - Dataset: e6
E                   - Deterministic terms: co, seasons: 4
E                   (mismatch 100.0%)
E                    x: array(1)
E                    y: array(0)

numpy: 1.14.3
scipy: 1.1.0

@josef-pkt

Copy link
Copy Markdown
Member Author

This pull request introduces 1 alert when merging ca84a6a into c6a76ed - view on LGTM.com

new alerts:

  • 1 for Variable defined multiple times

Comment posted by LGTM.com

@josef-pkt

josef-pkt commented Jun 2, 2018 •

Copy link
Copy Markdown
Member Author

this time all green

the last commit added one test case for dispersion_poisson_generic and fixed some bugs in it.

I'm postponing a full testing for it to when I go back to diagnostic tests.
I remember only part of the details, and there are too many options to verify all of them quickly.

For example exog_new_test can be used to test different alternatives for the variance function which can be variants of testing against NB1 or NB2 alternatives.
However, I don't remember which is which and how we can replicate eg. the 7 dispersion tests in dispersion_poisson by Dean and by Cameron/Trivedi.
I tried a few cases in the unit tests:

+        # constant only dispersion
+        ex = np.ones((res_drop.model.endog.shape[0], 1))
+        # ex = np.column_stack((np.ones(res_drop.model.endog.shape[0]),
+        #                      res_drop.predict()))  # or **2
+        # dispersion_poisson_generic might not be correct
+        # or not clear what the alternative hypothesis is
+        # choosing different `ex` implies different alternative hypotheses
+        res_test = diao.dispersion_poisson_generic(res_drop, ex)

The point of dispersion_poisson_generic is that it has the pattern for general LM diagnostics and specification tests, based on auxiliary (OPG ?) regression, similar to those currently for OLS diagnostic.
e.g. the dispersion test is a special case for heteroscedasticity testing for Poisson which already has inherent heteroscedasticity.
(my guess is that we can easily extend it to GLM and the various implied variance functions. It allows more flexibibility in specifying the alternative variance function than just using pearson_chi2 excess dispersion.)

conditional_moment_test_regression is a more general version of dispersion_poisson_generic and has no unit test coverage yet.

@josef-pkt

josef-pkt commented Jun 3, 2018 •

Copy link
Copy Markdown
Member Author

conditional_moment_test_regression uses
statistic = nobs * res.rsquared

I'm pretty sure this should us uncentered rsquared, so is currently only correct if there is no constant in the OLS regression.
edit rsquared should be fine in this case, there should not be a constant among the regressors because then rsquared would be 1, so rsquared is the uncentered rsquared. The auxiliary regression regresses ones on the moment conditions.
i.e. it's just the quadratic form i'x (x'x)^{-1} x'i / i'i where i is a vector of ones, and x are the moment conditions.

comparing with dispersion test
Cameron Trivedi version in dispersion_poisson use wald test and each has only a single regressor, either fitted or constant. The second two use HC1 in wald test.
So, dispersion poisson are special cases but I had used a different version in unit test which doesn't produce the same numbers.

most tests in sandbox diagnostics for OLS use rsquared, not uncentered rsquared.
why is that ?
(some things where I don't remember the details correctly?)

het_white and het_breuschpagan don't include a restriction on the constant in the hypothesis test, i.e. resid**2 can be any constant, but slope coefficients should be zero.
In the poisson dispersion case the scale is hypothesized to be 1 and not an arbitrary constant, i.e. we also test that constant=0.
So it looks like we need to make centered versus uncentered r-squared as option or as consequence on which test is used, e.g. include constant in the exog_control but not in the exog regressors, moment conditions hypothesized to be zero.


- fit_constrained result: model contains score and hessian function for
the full, unrestricted model, but the parameter estimate in the results
instance are for the restricted model. This is the case if the 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.

are -> is

k_constraints : int or None
Number of constraints that were used in the estimation of params
restricted relative to the number of exog in the model.
This must be provided if no exog_extra are given. If exog_extra is

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.

outdated: k_constraints is not necessary anymore.
Inferred from constraints attribute added by fit_constrained, if not provided

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 leave it in for now as override possibility.
There is a path if constraints attribute is not available, e.g. fit_zeros doesn't have it.

matrix.

cov_type is 'HC0'

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.

missing explanation

cov_score = nobs * np.cov(score_obs.T)
V = self.cov_params_default
# temporary to try out
chi2stat = _lm_robust(score, r_matrix, hinv, cov_score, V=V)

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.

cov_score should be None in this case

@josef-pkt

Copy link
Copy Markdown
Member Author

I had an old review open. Now all addressed or ignored with comment.
Last commit did some doc work and cleanup but this is still WIP until we have usecases for it.
(e.g. I don't know yet whether I shouldn't switch to rsquared_uncentered by default.

Merge when green.

Next up: most likely enhancing discrete with offset and score factor, and then adding score_test to results classes in discrete and GLM.

@josef-pkt

Copy link
Copy Markdown
Member Author

This pull request introduces 2 alerts when merging 67ef53d into d8cb151 - view on LGTM.com

new alerts:

  • 1 for Wrong name for an argument in a call
  • 1 for Variable defined multiple times

Comment posted by LGTM.com

@josef-pkt

Copy link
Copy Markdown
Member Author

This pull request introduces 1 alert when merging dbbfc52 into d8cb151 - view on LGTM.com

new alerts:

  • 1 for Variable defined multiple times

Comment posted by LGTM.com

@josef-pkt

Copy link
Copy Markdown
Member Author

again one of the vecm lag order selection test fails on one python on travis

otherwise green, merging

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.

3 participants