Skip to content

ENH: add score_factor, hessian_factor to discrete rebased - #5711

Closed
josef-pkt wants to merge 4 commits into
statsmodels:mainfrom
josef-pkt:discrete_scorefactor_offset_rebased
Closed

josef-pkt wants to merge 4 commits into
statsmodels:mainfrom
josef-pkt:discrete_scorefactor_offset_rebased

Conversation

@josef-pkt

@josef-pkt josef-pkt commented May 13, 2019 •

Copy link
Copy Markdown
Member

This is a rebased version of #4716

changes to order of import statements got lost in merge conflict resolution
otherwise unchanged

see #4716 for notes, notebook for application of score test https://gist.github.com/josef-pkt/f20abdbd360c2e549f73e98844f5d2c4

ENH:

  • adds offset to binary models
    count models already have offset
    MNLogit does not have offset
    ZeroInflated models don't have offset for the binary model, but have it already for the count submodel
  • adds fit_constrained to binary models as application of offset
  • adds score and hessian factor methods to several models
  • adds score_test to GLM and DiscreteResults
    DiscreteResults.score_test will not work for all models that inherit from it.
    Which models work currently? Which are unit tested?

Unit Tests:

  • compare discrete and GLM statsmodels/discrete/tests/test_sandwich_cov.py CheckDiscreteGLM
    covered: score_test, score_factor, including binary models with offset
    models: Poisson, Logit, Probit, Gauss (is skipped in new assert because methods are not available in OLS)
  • statsmodels/discrete/tests/test_constrained.py
    new Logit subclasses for comparing with GLM CheckGLMConstrainedMixin
    tests fit_constrained, and implicilty offset (I guess)
  • statsmodels/discrete/tests/test_discrete.py
    compare score_factor, hessian_factor with existing methods,
    Warning: this will not test anything when the code duplication is removed.
    CheckModelResults.test_jac is inherited by test classes for most models.

NO new tests for verifying correctness of score_test
(unit tests check only that GLM and discrete models produce the same results up to tolerance)

@josef-pkt

Copy link
Copy Markdown
Member Author

the last commit ENH: add score_test to Results GLM and Discrete
adds the score_test method to GLM and discrete results classes.

I could split out GLM score_test so that we can add diagnostic tests for GLM without the discrete changes. Or merge this essentially as is with a lot of code duplication.

How good is unit test coverage for score tests ?

@codecov

codecov Bot commented May 13, 2019 •

Copy link
Copy Markdown

Codecov Report

Merging #5711 into master will decrease coverage by <.01%.
The diff coverage is 95.3%.

Impacted file tree graph

@@            Coverage Diff             @@
##           master    #5711      +/-   ##
==========================================
- Coverage   82.22%   82.21%   -0.01%     
==========================================
  Files         593      593              
  Lines       93716    93952     +236     
  Branches    10353    10370      +17     
==========================================
+ Hits        77058    77245     +187     
- Misses      14256    14293      +37     
- Partials     2402     2414      +12
Impacted Files Coverage Δ
statsmodels/genmod/generalized_linear_model.py 91.2% <100%> (+0.07%) ⬆️
statsmodels/base/_parameter_inference.py 64% <100%> (-0.94%) ⬇️
statsmodels/discrete/tests/test_sandwich_cov.py 98.3% <100%> (+0.29%) ⬆️
statsmodels/discrete/tests/test_constrained.py 90.75% <92%> (+0.11%) ⬆️
statsmodels/discrete/tests/test_discrete.py 98.89% <93.1%> (-0.44%) ⬇️
statsmodels/discrete/discrete_model.py 88.23% <94.03%> (+0.41%) ⬆️
statsmodels/iolib/openfile.py 66.66% <0%> (-9.1%) ⬇️
statsmodels/base/wrapper.py 86.95% <0%> (-4.35%) ⬇️
statsmodels/datasets/utils.py 80.24% <0%> (-3.09%) ⬇️
statsmodels/tsa/tsatools.py 87.34% <0%> (-2.47%) ⬇️
... and 20 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 e5d170e...cee3dba. Read the comment docs.

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.002%) to 84.798% when pulling cee3dba on josef-pkt:discrete_scorefactor_offset_rebased into e5d170e on statsmodels:master.

Comment thread statsmodels/discrete/discrete_model.py Resolved
Comment thread statsmodels/discrete/discrete_model.py Resolved
Comment thread statsmodels/discrete/discrete_model.py Resolved
Comment thread statsmodels/discrete/discrete_model.py Resolved
Comment thread statsmodels/discrete/discrete_model.py Resolved
dparams = dmudb * (-a4 / a1 +
a3 * a2 / (a1 ** 2) +
(1 + a4) * ((y - 1) / a2 - 1 / a1) +
1 / mu)

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.

  • 1/mu term factors out and when multiplied by dmudb is just 1
  • Substituting in a4=a3*y I think will make it easier to identify cancellable terms, as well as terms common between this and dalpha

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.

Musing: I'm confident Mathematica or something has a maximally-simplify command, but that isn't what we want here. We want some convex combination of maximally-simplify and maximal-readability/interprebility. I wonder if there is a tool for this.


def hessian_factor(self, params):
"""
Generalized Poisson model Hessian matrix of the loglikelihood

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.

I'm not clear on how this is different from just hessian. My understanding of hessian_factor is it gives the X such that exog.dot(X).dot(exog) gives hessian or something like that.

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.

hessian factor is 1-D, and can also be multiplied with other exog than the ones in the model, which is what I use in the score_test and conditional moment tests

@josef-pkt

Copy link
Copy Markdown
Member Author

Formatting comments are already in the old PR
I'm trying to figure out some statistics and econometrics at the moment

Comment thread statsmodels/discrete/discrete_model.py Resolved
Comment thread statsmodels/discrete/discrete_model.py Resolved
Comment thread statsmodels/discrete/discrete_model.py Resolved
Comment thread statsmodels/discrete/discrete_model.py Resolved
Comment thread statsmodels/discrete/discrete_model.py Resolved

def score_factor(self, params):
"""
Logit model derivative of the log-likelihood with respect to linpred

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.

same comment as with hessian_factor above

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.

similar answer
score_factor is 1-D and can be multiplied by any "instruments" or other exog not in the model.

Comment thread statsmodels/discrete/discrete_model.py Resolved
Comment thread statsmodels/discrete/discrete_model.py Resolved

@classmethod
def setup_class(cls):
cls.idx = slice(None)

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.

if this isn't overriden elsewhere, can you set it at the class level outside of setup_class? These are easier to reason about when they are less stateful

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.

defensive programming,
There is no requirement that it is not changed somewhere, and I don't have to think about inheritance for class attributes when adding subclasses.


# not used to match Stata for HC
# nobs, k_params = mod1.exog.shape
# k_params -= 1 # one constraint

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.

?



def check_jac(self):
# moved from CheckModelResults

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 moved? If it takes self, this should probably be a method in a mixin class

#basic cross check
jacsum = self.res1.model.score_obs(self.res1.params).sum(0)
score = self.res1.model.score(self.res1.params)
assert_almost_equal(jacsum, score, DECIMAL_9) #Poisson has low precision ?

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.

space after #. Question mark suggests this probably merits a TODO:

assert_allclose(hess1, hess2, rtol=1e-10)

if isinstance(res2.model, OLS):
# skip the rest

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.

half a sentence on why OLS gets skipped?

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.

OLS does not have score_factor, hessian_factor
only GLM and now some discrete

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.

That will make a great addition to the comment here

rtol=0.01)

def test_jac(self):
self.res1 = self.res

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.

Modifying self inplace here is a code smell. Luckily there is a solution that goes hand-in-hand with the refactoring-out of check_jac: that function only needs res1, can get rid of the self argument and just pass res1=self.res and knock out two smells at once.

@josef-pkt

Copy link
Copy Markdown
Member Author

a quick monte carlo based on my notebook example, Poisson

cases are [mean_misspecified, dispersed, cov_type]

1000 replication, sample size 1000

so

  • (False, False, nonrobust) Poisson is correctly specified, using standard nonrobust score_test
    empirical rejection frequency is very close to nominal alpha
  • (False, False, HC0) Poisson is correctly specified, using HC robust score_test
    is conservative, under rejects by about 1/2, standard result in literature
  • (False, True, HC0) mean function is correctly specified, excess dispersion, HC robust score test
    overrejects but not strongly
  • (False, True, nonrobust) correctly specified mean, excess dispersion, nonrobust score test
    overrejects very strongly, rejection rate is 0.89 instead of 0.05

The other cases have mean_misspecified=True and should reject, which all cases do.

effects of misspecification and power are large because the misspecification and deviation from null are large in the data generating model and sample size 1000 is very large for a test about mean functions.


​
pd.set_option('display.max_columns', 500)
pd.set_option('display.width', 1000)
print(res_df)
                           0.001  0.010  0.050  0.100  0.200  0.300  0.500  0.900
(True, True, nonrobust)    0.998  1.000  1.000  1.000  1.000  1.000  1.000  1.000
(True, True, HC0)          0.963  0.995  1.000  1.000  1.000  1.000  1.000  1.000
(True, False, nonrobust)   1.000  1.000  1.000  1.000  1.000  1.000  1.000  1.000
(True, False, HC0)         1.000  1.000  1.000  1.000  1.000  1.000  1.000  1.000
(False, True, nonrobust)   0.857  0.893  0.927  0.948  0.961  0.975  0.985  0.994
(False, True, HC0)         0.002  0.014  0.063  0.136  0.258  0.392  0.683  0.971
(False, False, nonrobust)  0.001  0.010  0.054  0.106  0.203  0.308  0.480  0.899
(False, False, HC0)        0.000  0.002  0.022  0.055  0.162  0.292  0.560  0.942

hessian = -np.dot(ex.T * hessian_factor, ex)
# see #4714
from statsmodels.genmod.generalized_linear_model import GLM
if isinstance(model, GLM):

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 better approach would be the have models defind an attribute, e.g. hessain_factor that would be 1 by default and could be overridden when necessary, e.g., by GLM, rather than encodign model-class-specific information in a base 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.

That would be better if this were a permanent feature.
However, I hope that we can make this consistent across models and then we just need to delete these lines here.

I have not checked yet how this works in other models like OLS/WLS and RLM, or models in survival.


# this is a copy from stats._diagnostic_other
# this is a copy from stats._diagnostic_other to avoid circular imports
def _lm_robust(score, constraint_matrix, score_deriv_inv, cov_score,

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 copy should be removed and it should be imported right before first use, with a note explaining why it is imported there.

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.

Or just don’t remove the import of disgnostic_other at the top of the file

hypothesis='joint', cov_type=None, cov_kwds=None,
k_constraints=None, observed=True):

res = infer.score_test(self, exog_extra=exog_extra,

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 original GLM.score_test is not used anymore?
The new version allows for some robust sandwich forms

@josef-pkt

Copy link
Copy Markdown
Member Author

I'm going to split out the changes to non Poisson count models so I can get the main changes including Logit ready for merge.

count models should use cut and paste instead of copy-paste for score and hessian factors

@josef-pkt

Copy link
Copy Markdown
Member Author

how much of this is included in #7166 or other PRs?

needs rebase to check what the conflicts with main are.
conflicts with other PRs

X = self.exog
L = np.exp(np.dot(X,params) + exposure + offset)
return L
return -L

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.

why does this change the sign?
(it's in one of the merge conflicts, and I'm not sure what's correct)

@josef-pkt

josef-pkt commented Jul 21, 2021 •

Copy link
Copy Markdown
Member Author

trying to rebase this on either main or #7597, the first commit here has a large number of merge conflicts in discrete_model.py

strange thing is change in sign of hessian. Is there a bug?

in main and 7597, Poisson hessian and hessian_factor have opposite signs.
but both have unit test coverage in main
???

same for others GLM, Logit,
hessian_factor is positive

glm score and score_factor have the same sign.

base._parameter_inference.score_test for variable addition exog_extra assumes that the negative sign is in hessian function, but not in hessian_factor

        hessian_factor = model.hessian_factor(params_constrained,
                                              **hess_kwd)
        hessian = -np.dot(ex.T * hessian_factor, ex)

so we shouldn't flip sign as in this PR, unless we redifine hessian_factor for all models.

@josef-pkt josef-pkt added this to the 0.13 milestone Jul 21, 2021
@josef-pkt josef-pkt modified the milestones: 0.13, 0.14 Sep 8, 2021
@josef-pkt

Copy link
Copy Markdown
Member Author

This is going to have a lot of merge conflicts.

Maybe I should skip the first commit, or large parts of it. e.g. the copy paste in GPP and NB. Logit score_factor will already be in master. Unit tests in first commit still look useful.

@josef-pkt josef-pkt added the superseded Used for PRs with content that is superseded by a newer PR label Oct 31, 2021
@josef-pkt

Copy link
Copy Markdown
Member Author

merged in #7825

@josef-pkt josef-pkt closed this Oct 31, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-base comp-discrete comp-genmod 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.

4 participants