Skip to content

ENH: Diagnostic class rebased - #7597

Merged
josef-pkt merged 16 commits into
statsmodels:mainfrom
josef-pkt:diagnostic_class_rebased
Oct 28, 2021
Merged

josef-pkt merged 16 commits into
statsmodels:mainfrom
josef-pkt:diagnostic_class_rebased

Conversation

@josef-pkt

@josef-pkt josef-pkt commented Jul 21, 2021 •

Copy link
Copy Markdown
Member

closes #7166
rebased version of #7166

see previous PR for comments and details

update What's included in this PR

  • base._parameter inference: im_ratio, tic, gbic
  • poisson diagnostics
    • discrete.diagnostic: PoissonDiagnostic class
    • discrete._diagnostics_count : bug fixes, refactor, new zi test
    • stats._diagnostic_other : bugfix, HC, clean
  • discrete_model :
    • _deriv_mean_dparams in BinaryModel and CountModel
    • get_prediction in LogitResults and PoissonResults
    • _deriv_score_obs_dendog in Logit and Poisson, used for ?
    • score_factor, hessian_factor in Logit
    • im_ratio, info_criteria in DiscreteResults
    • get_influence in Logit and Poisson returning MLEInfluence, tests against GLM.get_influence
  • unit tests
    • PoissonDiagnostic no get_diagnostic

"""
y = self.endog
X = self.exog
L = self.cdf(np.dot(X, params))

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 does not include offset

@josef-pkt

josef-pkt commented Jul 21, 2021 •

Copy link
Copy Markdown
Member Author

there are conflicts with other PRs
e.g. for Logit with or without offset
#5711,
I don't see any other PR label:comp-discrete with overlap to this one. #5711 adds offset to discrete binary Model

@josef-pkt

Copy link
Copy Markdown
Member Author

fails across the board

recent change in main, #7596, breaks extra fit keywords

kwargs = {'atol': 1e-10, 'attach_wls': True}, allowed = ('tol',)

    def check_kwargs(kwargs:dict[str, Any], allowed:Sequence[str]):
        extra = set(list(kwargs.keys())).difference(list(allowed))
        if extra:
>           raise ValueError(
                f"Keyword arguments passed to the optimizer are not allowed. "
                f"The list of allowed keywoard arguments is: "
                f"{', '.join(allowed)}. The list of extraneous keyword "
                f"arguments is: {', '.join(extra)}."
            )
E           ValueError: Keyword arguments passed to the optimizer are not allowed. The list of allowed keywoard arguments is: tol. The list of extraneous keyword arguments is: attach_wls, atol.

@lgtm-com

lgtm-com Bot commented Jul 21, 2021

Copy link
Copy Markdown

This pull request introduces 1 alert when merging fa3d3fc into d2f6634 - view on LGTM.com

new alerts:

  • 1 for Unused import

@bashtage

Copy link
Copy Markdown
Member

Why not fix the issue? There were loads of incorrect keywords in tests, eg tol rather than gtol.

@josef-pkt

Copy link
Copy Markdown
Member Author

I will fix the issue, but it is an indicator that the check breaks code, and checking extra kwargs is not worth it.
I user can just look at warnings.

exception is fine for now to fix our problems but needs to be converted to warning before the release, to avoid breaking user code, subclasses, ...

@pep8speaks

pep8speaks commented Jul 21, 2021 •

Copy link
Copy Markdown

Hello @josef-pkt! Thanks for updating this PR. We checked the lines you've touched for PEP 8 issues, and found:

Line 15:1: F401 'statsmodels.stats.base.HolderTuple' imported but unused

Comment last updated at 2021-10-28 15:27:34 UTC

@lgtm-com

lgtm-com Bot commented Jul 21, 2021

Copy link
Copy Markdown

This pull request introduces 1 alert when merging e3a7688 into d2f6634 - view on LGTM.com

new alerts:

  • 1 for Unused import

@josef-pkt

Copy link
Copy Markdown
Member Author

green, except for one flake unused import

test coverage is pretty low
new discrete.diagnostic.py has zero coverage. It's mostly wrapper code delegating to individual functions.

@josef-pkt

Copy link
Copy Markdown
Member Author

rebased again
merge conflict in GLMResults null, but this PR just adds a catch_warning for DomainWarning in null

return -2*self.llf + np.log(self.nobs)*(self.df_model+1)

@cache_readonly
def im_ratio(self):

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.

now we use a method info_criteria in GLM, regression and tsa

to the parameter vector.
"""
from statsmodels.genmod.families import links
link = links.Log()

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.

which should have a family or link attribute for this

@josef-pkt

josef-pkt commented Sep 29, 2021 •

Copy link
Copy Markdown
Member Author

changes in test_glm_weights.py looks mostly pep-8 cleaning

genmod test_glm CheckComparisonMixin includes test for get_prediction.
classes that use the Mixin seems to be tests for Logit and Poisson

stats/tests/test_influence.py compares get_influence for Logit and Poisson with GLM

Azur failures are only style check for unused import

@lgtm-com

lgtm-com Bot commented Sep 29, 2021

Copy link
Copy Markdown

This pull request introduces 1 alert when merging 1388fad into b5baa4d - view on LGTM.com

new alerts:

  • 1 for Unused import

@josef-pkt

Copy link
Copy Markdown
Member Author

Poisson.get_prediction implements offset and exposure like GLM, but no unit test case with either offset or exposure, AFAICS

score_obs = res.model.score_obs(res.params)
cov_score = score_obs.T @ score_obs
hessneg_inv = np.linalg.inv(-hess)
im_ratio = hessneg_inv @ 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.

use lstsqu to avoid direct matrix inversion

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 these are both always square and hess is full-rank, than solve would be the best solution I think.

def tic(results):
"""Takeuchi information criterion for misspecified models

"""

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.

reference

@josef-pkt

josef-pkt commented Oct 22, 2021 •

Copy link
Copy Markdown
Member Author

It looks like PoissonDiagnostic was still in draft status when I stopped working on it.
Several methods don't work. Most likely copy paste from notebooks and wrapper code that delegates to functions where wrapper code hasn't been fully adjusted.

Currently, I'm trying to figure out how _combine_bins in test_chisquare_prob is supposed to work.
(originally written in notebook try_zi_simulated in 9/2017, with additional cases in notebook but not unittests.)
There might be a mixup somewhere between counts and relative frequencies or probabilitites and expected counts.

The problem is that many of these functions don't exist in other packages. (Maybe in some web appendices to articles. I haven't looked for it again.)

Needs work before we can merge this even with an experimental API.

update
bin_edges=np.arange(3) corresponds to testing prob at y=0, i.e. zero inflation or deflation.
result for that is close to the result of zero_inflation method (with constant inflation) (which has same p-value as brock)
0.3947112012964216, 0.5298333315650978

test_chisquare_prob cannot be used to test 1- or k-inflation, because it drops the last bin, but not bins in front (low y). Bins for the test always includes y=0, maybe pooled with other low y.

bin_edges=np.arange(i)
for i in range(3, 10):
    ti = dia.test_chisquare_prob(bin_edges=np.arange(i))[:3]
    print(i, ti)
3 (0.4036959655747685, 0.5251866527858496, 1)
4 (0.99471566080922, 0.6081353355597368, 2)
5 (1.7119135284788811, 0.6342884017549388, 3)
6 (2.544403866831635, 0.6367026325033609, 4)
7 (2.724375214921637, 0.742387906602849, 5)
8 (3.1623112564257427, 0.7882167155231558, 6)
9 (4.928256282748844, 0.668718185600475, 7)

diac._combine_bins(np.arange(3), np.arange(10) * np.ones((4, 1)))
(array([[0., 1.],
        [0., 1.],
        [0., 1.],
        [0., 1.]]),
 array([1, 1]))

test_chisquare_prob currently does not truncate almost empty bins for high endog values.
Default comes from predict(which="prob") which goes to max(endog).

rerunning Monte Carlo

zi inflation tests, last row is for test_chisquare_prob for zero.
It has higher rejection rate, but only a bit above size ( with nobs=1000)

rej_zi = (res_zi[:, :, None] <= np.array([0.01, 0.05, 0.1, 0.2])[None, None, :]).mean(0)

       ([0.01,   0.05,   0.1,    0.2],
 array([[0.0378, 0.055 , 0.0552, 0.0678],
        [0.0378, 0.055 , 0.0552, 0.0678],
        [0.0102, 0.051 , 0.1002, 0.204 ],
        [0.0118, 0.0598, 0.1096, 0.2112]]))

@josef-pkt

Copy link
Copy Markdown
Member Author

maybe I should change the name of test_chisquare_prob
The name might be misleading as chisquare test, i.e. test the full distribution, all bins.
It's kind of similar, but we can tests arbitrary probabilities, i.e. it's essentially a CMT that just uses chisquare distribution based on asymptotics.

For individual probabilities like zero inflation, we could use one-sided tests.
I guess in small samples, we could even switch to using F-distribution.

The OPG version would apply to any model. For better CMT, we would need derivatives d_probs / d_params (as in explicit zeroinflation tests)

Still, I think we need an upper bound as default to avoid empty or almost empty bins.
Also, we might share code with better binning methods, e.g. merge_cells as in distribution gof tests.

Most of these functions or methods should return now a HolderTuple. with no backwards compatibility guarantee on extra attributes.

@josef-pkt
josef-pkt force-pushed the diagnostic_class_rebased branch from a6421a2 to a2733ba Compare October 22, 2021 21:29
@lgtm-com

lgtm-com Bot commented Oct 22, 2021

Copy link
Copy Markdown

This pull request introduces 1 alert when merging a2733ba into 63a32e9 - view on LGTM.com

new alerts:

  • 1 for Unused import

@josef-pkt

Copy link
Copy Markdown
Member Author

#7131 has a long list of references for score_test

the test in the notebook looks also the best in smaller sample nobs=100 (still two sample regression)

brock and constant only zi test looks strange, pvalues are far from uniform
chisquare test over rejects

print(dframe_zi)
        0.001   0.010   0.025   0.050   0.100   0.200
zi     0.0386  0.0402  0.0402  0.0402  0.0402  0.0402
brock  0.0386  0.0402  0.0402  0.0402  0.0402  0.0402
ipynb  0.0016  0.0074  0.0174  0.0390  0.0934  0.1962
chi2   0.0630  0.0690  0.0816  0.1064  0.1558  0.2536

all dispersion tests also look mostly well sized in small samples
Dean tests maintain size very well
CT tests over-reject,

print(dframe_disp)
             0.001   0.010   0.025   0.050   0.100   0.200
Dean A      0.0020  0.0094  0.0242  0.0502  0.0968  0.2058
Dean B      0.0020  0.0094  0.0242  0.0502  0.0968  0.2058
Dean C      0.0016  0.0110  0.0248  0.0462  0.0984  0.2074
CT nb2      0.0090  0.0328  0.0544  0.0838  0.1408  0.2416
CT nb1      0.0090  0.0328  0.0544  0.0838  0.1408  0.2416
CT nb2 HC3  0.0142  0.0388  0.0594  0.0932  0.1418  0.2438
CT nb1 HC3  0.0098  0.0304  0.0546  0.0844  0.1436  0.2428

(I haven't done any power simulations)

@josef-pkt

Copy link
Copy Markdown
Member Author

Hosmer lemeshow type test for Poisson needs to have a limit on y-cells, i.e. we need to bin low count cells.

code comment in PoissonDiagnostic.chisquare_binned

        # not sure yet how this is supposed to work
        # max_count = endog.max * 2
        # no option for max count in predict
        # counts = (endog == np.arange(max_count)).astype(int)
        expected = self.results.predict(which="prob")

self.results.predict(which="prob") needs options for which counts y the prob is produced, and
we need separately binning/merging of low count cells.
For binning, we could use cdf instead of pmf, i.e. interval censoring.

Note, currently anything with "prob" is not designed for large counts, because we compute full arrays with shape (nobs, max(endog)).

@josef-pkt

josef-pkt commented Oct 24, 2021 •

Copy link
Copy Markdown
Member Author

It looks like test_poisson_zeroinflation_brock, and the equivalent constant inflation test is numerically not stable because of the division by prob0 which can be very small if mu is large.
Simulating a small mu case, mean(endog) = 1.14, then the results look good

again 2-sample case, nobs=1000, nrepl=5000

        0.001   0.010   0.025   0.050   0.100   0.200
zi     0.0014  0.0098  0.0254  0.0478  0.0988  0.2002
brock  0.0014  0.0098  0.0254  0.0478  0.0988  0.2002
ipynb  0.0014  0.0090  0.0252  0.0494  0.1002  0.2024
chi2   0.0016  0.0090  0.0252  0.0500  0.1004  0.2012

scoretest by Broek is parameterized in terms of prob ration theta = prob0 / (1 - prob0), with Null H0: theta = 0

If the score test is in terms of diff = observed0 - count0 (in other articles) then we don't have division by prob0 in the test statistic, and it's computationally more robust even if mu is larger.

rewriting Broek test doesn't help equ 4 instead of similar to equ 3 in Broek article
For larger mu, the test is still strongly distorted
case with endog.mean() = 5.56

        0.001   0.010   0.025   0.050   0.100   0.200
zi     0.0068  0.0370  0.0538  0.0562  0.0562  0.0658
brock  0.0068  0.0370  0.0538  0.0562  0.0562  0.0658
ipynb  0.0006  0.0100  0.0268  0.0534  0.1010  0.2046
chi2   0.0034  0.0172  0.0334  0.0596  0.1094  0.2092
    # score =  ((endog == 0) / prob_zero).sum() - nobs
    # var_score = (1 / prob_zero).sum() - nobs - endog.sum()
    score = (((endog == 0) - prob_zero) / prob_zero).sum()
    var_score = ((1 - prob_zero) / prob_zero).sum() - endog.sum()

Boek article: in the simulation uses mu= 0.5 and mu=1
Jansakul an hinde: the largest mu in the simulation is np.exp(0.75) = 2.117

Ok, leave it as is but add a note in docstring that it only works well for small mu

Jansakul and Hinde test_poisson_zeroinflation has the same problem.
But that's the only one we have for now that allows for exog_infl in the alternative, instead of testing against constant inflation/deflation.
Aside: Do we have a problem with parameters that are not identified under the null?
I guess not because mixing probability pi=0 requires that all infl-params are zero when using identity link.

naming problem: I misspelled Broek in several different ways. Needs fixing.

@josef-pkt

josef-pkt commented Oct 24, 2021 •

Copy link
Copy Markdown
Member Author

No reference for test_chisquare_prob
It's kind of a generic LM test with auxiliary regression. I'm not sure I had a specific reference.
update see #3904 (comment)
similar to Manjón, M., and O. Martínez. 2014 but I wrote the function before having access to that article.
I don't know how much the details match up with them.

Related: I think I also worked with added variable score tests adding dummies for specific cases, e.g. indicator variables for endog in a bin.
I don't see anything like that right now.

general theory by Andrews Econometrica #3904

@josef-pkt

Copy link
Copy Markdown
Member Author

poisson diagnostics need one round of cleanup

Then I can go back to general design.

Basic idea PoissonDiagnostic should be the prototype
We can have similar tests for other models, e.g. ZI test for NegBin and GPP
and test for dispersion joint with zi or conditional on zi model, e.g. ZIP versus ZINB

We don't have Binomial and Beta-Binomial in discrete.
there is also a similar literature on zi and dispersion testing for Binomial, or zi testing in Beta-Binomial

Structure:
Most articles that I read derive specification test for specific models.
However, we should be able to do this more generically.
Full MLE version requires derivatives e.g. d_prop0 / d_params,
OPG is cheap to implement generically, but not very good in smaller samples.

This PR also adds derivatives for MLEInfluence in Logit and Poisson

Tools needed in individual models, e.g.

  • predict(which="xxx").
  • Some derivatives.
    • for diagnostic and predict, e.g. get_prediction, gof-tests, CMT
    • for get_influence
  • access to get_distribution
  • plots I have it for count models, but not yet much for binary models included in PRs.
  • score_test separate PRs, discrete similar to GLM
    • needs score_factor and hessian_factor, and extension to models with extra params, NBB, GPP
    • might also need fit_constrained which needs offset
  • offset for binary models; separate, overlapping PRs

@josef-pkt

josef-pkt commented Oct 24, 2021 •

Copy link
Copy Markdown
Member Author

I found the reference for the zi test in the notebook, #7131 (comment)

implementation follows Tang and Tang 2019 which have the explicit formulas for the Poisson case, based on theory in He et al 2019
Tang and Tang also have formula and comparison with Broek

Given that it does the best in the monte carlos overall, it should be the default.

design question:
I think like Stata we can just return pvalues for all three alternatives, two-sided and smaller and larger.

@josef-pkt
josef-pkt force-pushed the diagnostic_class_rebased branch from 55ab55e to 518fa2e Compare October 25, 2021 15:24
@josef-pkt

josef-pkt commented Oct 25, 2021 •

Copy link
Copy Markdown
Member Author

another refactoring:
I think we should use dfamiles from PR #7793 for discrete models instead of genmod families.
Currently, we only use the link from the family attribute.
In the dfamily for Poisson we could add additional methods like derivatives, instead of hardcoding them in the model class.

I need d_pdf / d_dargs as part of e.g. zero-inflation testing, moment or conditional moment test for probabilities/frequencies.
In poisson mu is the only darg, and we can get it also from score_obs, derivative of loglike/log_pdf.
We need to be able to get d_pdf / d_dargs for arbitrary y=k, not just the observed endog, corresponding to predict(which="prob")

@lgtm-com

lgtm-com Bot commented Oct 25, 2021

Copy link
Copy Markdown

This pull request introduces 1 alert when merging 518fa2e into d990e32 - view on LGTM.com

new alerts:

  • 1 for Unused local variable

@josef-pkt
josef-pkt force-pushed the diagnostic_class_rebased branch from 518fa2e to 8365fbb Compare October 25, 2021 19:06
@lgtm-com

lgtm-com Bot commented Oct 25, 2021

Copy link
Copy Markdown

This pull request introduces 1 alert when merging 8365fbb into d990e32 - view on LGTM.com

new alerts:

  • 1 for Unused local variable

@josef-pkt

josef-pkt commented Oct 25, 2021 •

Copy link
Copy Markdown
Member Author

I will make the Hosmer-lemeshow type test PoissonDiagnostic.chisquare_binned private for now.
It's does not have a proper asymptotic distribution, and I don't know how well the approximation will work. Besides it will require large samples to have enough observations in each bin.
I added k_max to be able to limit the number of y-bins. I'm also using the ordered=True df,, which might not be good if we only have a few groups of observations. I vaguely remember I looked at df before but didn't try to dig out any comments I might have made.
(my current experimentation example is nobs=100, 3 observation groups and k_max = 2 to 4 for a small mean example)

Adrews' theory applies to both partitioning of endog and of exog space, so we might be better off building on that.

Aside: I recently downloaded
Surjanovic, Nikola, Richard Lockhart, and Thomas M. Loughin. 2021. “A Generalized Hosmer-Lemeshow Goodness-of-Fit Test for a Family of Generalized Linear Models.” ArXiv:2007.11049 [Stat], February. http://arxiv.org/abs/2007.11049.

However, it looks to me that they are comparing the mean, i.e.. residual in groups of observations. They are not partitioning the y space and use predictive probabilities as I do.
Update Their G* in section 3.2 is partitioning the linear predictor, which in poisson is equivalent to partitioning the probability mu. But the diff (score or moment) for observed - expected is the group residual. So, they have oneway grouping.
From what I remember I'm doing the direct extension of the multinomial or ordinal Hosmer-Lemeshow type test partitioning the y space (with bin probabilities) and grouping observations, i.e. I end up with something like a 2-dim contingency table.

aside to the aside: Surjanovic et al point out that distribution of the test statistic in HL is a sum of chisquare, and that HL use a 1-term approximation with chisquare using a df correction based mostly on simulations.

@josef-pkt

Copy link
Copy Markdown
Member Author

I will merge this when it comes back green.
individual pieces will need follow-up.

main related parts missing: offset in binary models and score_test (Poisson and Logit to start with)

and get_distribution to make simulations easier

@lgtm-com

lgtm-com Bot commented Oct 28, 2021

Copy link
Copy Markdown

This pull request introduces 2 alerts when merging 5d6aa59 into d990e32 - view on LGTM.com

new alerts:

  • 1 for Unused local variable
  • 1 for Unused import

@josef-pkt
josef-pkt force-pushed the diagnostic_class_rebased branch from 5d6aa59 to 0158af1 Compare October 28, 2021 16:20
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