Skip to content

ENH/REF: discrete add get_distribution, add which="var" for NBP, GPP - #7929

Merged
josef-pkt merged 7 commits into
statsmodels:mainfrom
josef-pkt:count_results
Dec 13, 2021
Merged

josef-pkt merged 7 commits into
statsmodels:mainfrom
josef-pkt:count_results

Conversation

@josef-pkt

@josef-pkt josef-pkt commented Dec 6, 2021 •

Copy link
Copy Markdown
Member

more work on post-estimation for discrete

This also outsources the predict transform exog from base.model.Results.predict to a new private method _transform_predict_exog
This helper method is reused in get_distribution to avoid code duplication. get_distribution does not use the pandas index because return is a scipy frozen distribution instance.

see also #7928 class diagram of unit tests

no get_distribution for MNLogit. I never tried out the scipy multinomial distribution, and don't know if it will work for our case.

This PR has now

  • get_distribution for all discrete models except MNLogit. Currently only in model classes not in results classes.
  • added predict which="var" for count models, not yet zi

@pep8speaks

pep8speaks commented Dec 6, 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:

There are currently no PEP 8 issues detected in this Pull Request. Cheers! 🍻

Comment last updated at 2021-12-13 18:13:53 UTC

@josef-pkt

Copy link
Copy Markdown
Member Author

currently only smoketests to check that methods and inherited methods work

@lgtm-com

lgtm-com Bot commented Dec 6, 2021

Copy link
Copy Markdown

This pull request introduces 4 alerts and fixes 1 when merging 9d6f81e into 6b4aa33 - view on LGTM.com

new alerts:

  • 2 for Module is imported with 'import' and 'import from'
  • 1 for Unnecessary pass
  • 1 for Unused import

fixed alerts:

  • 1 for Module is imported with 'import' and 'import from'

@josef-pkt

Copy link
Copy Markdown
Member Author

amended and force pushed

Should be correct now. unit tests for get_distribution check the implied mean.
I added mean and var to distribution genpoisson_p_gen. Fallback computation for mean in scipy is very slow and not accurate (AFAICS) at high means.
We need to check separately the unit tests for distribution genpoisson

Aside: standard geometric distribution parameter as in scipy is 1 / mean

@josef-pkt

Copy link
Copy Markdown
Member Author

we can add predict which="var" to all models here, specifically to binary (except MNLogit)

get_distribution for BinaryModel, i.e. inherited by Logit and Probit, returns scipy bernoulli frozen distribution

@lgtm-com

lgtm-com Bot commented Dec 6, 2021

Copy link
Copy Markdown

This pull request introduces 1 alert and fixes 1 when merging 12f13dc into 6b4aa33 - view on LGTM.com

new alerts:

  • 1 for Module is imported with 'import' and 'import from'

fixed alerts:

  • 1 for Module is imported with 'import' and 'import from'

@josef-pkt

Copy link
Copy Markdown
Member Author

all green
coverage: new var options and methods are not yet tested, otherwise pretty complete.

This PR also includes a new NegativeBinomialPResults class, but it doesn't have extra methods yet.
It's intended for post estimation get_xxx that will not be available for old negbin.

@josef-pkt

Copy link
Copy Markdown
Member Author

checking patterns in count models predict:

NegativeBinomialP.predict: if statements for offset and exposure still look wrong, e.g. exog is given but offset argument is None, but model has offset.
same code in GeneralizedPoisson.predict
#1486 problems we had in GLM

NegativeBinomial does not have predict, uses inherited from CountModel.
We need predict method to add model specific which="var" and NB also doesn't have which="prob"

Poisson.predict calls super for mean and linear, and recursive call for "prob" (and "var" that I'm just adding)
the super call should not use the linear keyword anymore

CountModel.predict : the conditions for offset, exposure handling look correct but messy.
Somewhere (?) I rearranged those conditions to make them easier to understand.
code comment says copied from GLM.predict which looks similar.

GenericZeroInflated. predict: looks like a rearranged version
ZI has offset and exposure for main model, but not for inflation model
additional handling for exog_infl

others:
BetaModel does not have offset yet, so no offset handling in predict

I also just found #7624 ZI models are still missing get_distribution

@josef-pkt

josef-pkt commented Dec 7, 2021 •

Copy link
Copy Markdown
Member Author

I never looked at geometric special case in NegBin

wikipedia has two versions,

  • starting at 1, k >=1, this is also the scipy version
  • starting at 0, k >= 0

Problem is that in the starting at 1 version, the mean mu has to be >= 1, If mu < 1 than variance using formula would be negative. but we use exp mean function (log link) that imposes mu > 0.

I need to figure out how the parameterization works.
If our version has k>=0 (which should be the case), then, I think, get_distribution needs loc = -1

https://en.wikipedia.org/wiki/Geometric_distribution
https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.geom.html

update
simulated with get_distribution rvs. no zeros in endog
(simulation/rvs described in later comment)

image

@lgtm-com

lgtm-com Bot commented Dec 7, 2021

Copy link
Copy Markdown

This pull request introduces 1 alert and fixes 1 when merging 1b644b3 into ab51acc - view on LGTM.com

new alerts:

  • 1 for Module is imported with 'import' and 'import from'

fixed alerts:

  • 1 for Module is imported with 'import' and 'import from'

@josef-pkt

Copy link
Copy Markdown
Member Author

BUG: inherited rvs of gen_poisson does not work. I get only ones back.

I don't remember if I ever checked the generic rvs for discrete distributions in scipy.
I thought it would work and just be very slow.

Using scalar params works, i.e. this is fine:
genpoisson_p.rvs(3, 1, 1, size=100)

The problem was that GeneralizedPoisson.fit didn't converge and had large negative dispersion parameter.

The diagnostic plots look good in the following example, especially with nobs=5000
empirical frequencies of rvs simulated data are close to the frequencies implied by the estimated model

NegativeBinomial does not have predict which="probs" yet.

nobs = 5000
x = np.ones((nobs, 1))
y = 1 * (1 + np.random.randn(nobs))**2

models = Poisson, NegativeBinomialP, GeneralizedPoisson, NegativeBinomial
for cls_model in models[:-1]:#[2:]:
    print("\n\n", cls_model)
    mod = cls_model(y, x)
    res = mod.fit()
    distr = mod.get_distribution(res.params)
    try:
        y2 = distr.rvs(size = (nobs, 1)).squeeze()
    except ValueError:
        y2 = distr.rvs(size=nobs).squeeze()

    mod = cls_model(y2, x)
    res = mod.fit()
    dia = res.get_diagnostic()
    dia.plot_probs();

@josef-pkt

Copy link
Copy Markdown
Member Author

we still have an inconsistency in the shape of the frozen distribution.
In the newer get_distribution I return a column array of args, the older get_distribution use 1-dim args.

@josef-pkt

Copy link
Copy Markdown
Member Author

amended with fix for geometric distribution. now with loc=-1, and appropriate mean, var
force pushed

aside: I saw somewhere the comment that geometric distribution is NB2 with alpha=1.

should be correct now. get_diagnostic with plot function is nice and convenient

current models in my notebook with consistent options (except 1-dim versus 2-dim get_distribution)

models = [
    (Poisson, {}), 
    (NegativeBinomialP, {}),
    (NegativeBinomialP, {"p": 1}),
    (GeneralizedPoisson, {}), 
    (GeneralizedPoisson, {"p": 2}), 
    (NegativeBinomial, {}),
    (NegativeBinomial, {"loglike_method": 'nb1'}),
    (NegativeBinomial, {"loglike_method": 'geometric'}),
    ]

not yet:

  • get_distribution for ZI models
  • no quick convenient check for Binary models, Logit, Probit. There is no get_diagnostic and BinaryDiagnostic class yet.

@lgtm-com

lgtm-com Bot commented Dec 8, 2021

Copy link
Copy Markdown

This pull request introduces 1 alert and fixes 1 when merging 38b5076 into ab51acc - view on LGTM.com

new alerts:

  • 1 for Module is imported with 'import' and 'import from'

fixed alerts:

  • 1 for Module is imported with 'import' and 'import from'

@josef-pkt

Copy link
Copy Markdown
Member Author

plots looks useful

I guess there is a bug in ZeroInflatedPoisson based on the plots.
empirical doesn't match estimate frequencies

image

@josef-pkt

josef-pkt commented Dec 9, 2021 •

Copy link
Copy Markdown
Member Author

inconsistent default of p in GeneralizedPoisson and ZeroInflatedGeneralizedPoisson

  • GeneralizedPoisson default p = 1
  • ZeroInflatedGeneralizedPoisson default p = 2

I got some surprising results when I assumed the default p are the same.

my additional cases that I'm checking for get_distribution and get_diagnostic plot:

    (ZeroInflatedPoisson, {}),
    (ZeroInflatedGeneralizedPoisson, {}),
    (ZeroInflatedGeneralizedPoisson, {"p": 1}),
    (ZeroInflatedNegativeBinomialP, {}),
    (ZeroInflatedNegativeBinomialP, {"p": 1}),

GeneralizedPoisson loglike is not very stable. I easily get invalid value in log and convergence warnings for simple random samples.
I'm adding a clip to keep a1 and a2 positive and away form zero.

@josef-pkt

Copy link
Copy Markdown
Member Author

it looks like I have zi get_distribution working correctly now.
It also matches _mean and _var in the distributions for ZI GPP. I will rename them and drop the leading underline.

One bug in old, existing code: which="prob" _predict_prob in ZeroInflatedGeneralizedPoisson used the wrong p (missing +1)
No other changes to existing code.

I have not yet checked _mean and _var fpr the other two ZI distributions.

My current example case for checking is a constants only model. So, no checks for different exog.

@josef-pkt

Copy link
Copy Markdown
Member Author

I pushed the zi get_distribution part

Not sure yet.
params in ZI models is not very close to data generating params, even when I increase nobs.
The zero-inflation parameter/probability estimate looks noisy.
There could still be problems in the simulation.

I have not added yet an assert on the frequencies, which should be stably predicted even if individual parameters are noisy.

Also I'm still running occasionally into convergence problems when I change the DGP numbers, nobs or params.

@lgtm-com

lgtm-com Bot commented Dec 10, 2021

Copy link
Copy Markdown

This pull request introduces 1 alert and fixes 1 when merging 36fd5b9 into 1b75604 - view on LGTM.com

new alerts:

  • 1 for Module is imported with 'import' and 'import from'

fixed alerts:

  • 1 for Module is imported with 'import' and 'import from'

@lgtm-com

lgtm-com Bot commented Dec 10, 2021

Copy link
Copy Markdown

This pull request introduces 1 alert and fixes 1 when merging 30deeb4 into 506b9f3 - view on LGTM.com

new alerts:

  • 1 for Module is imported with 'import' and 'import from'

fixed alerts:

  • 1 for Module is imported with 'import' and 'import from'

@josef-pkt

josef-pkt commented Dec 11, 2021 •

Copy link
Copy Markdown
Member Author

still to do:
missing which="var" and resid_pearson
more checking of rvs from get_distribution
docstrings

zinegbin.rvs looks correct
I ran 50 Million draws and frequencies are close to pmf, for mu, alpha, p, w = 1, 0.5, 2, 0.2

aside when mu=1, then negbin is independent of p

@josef-pkt

josef-pkt commented Dec 11, 2021 •

Copy link
Copy Markdown
Member Author

ZI predict: generic or individual methods?

Currently, only the generic ZI model class defines predict. The specific subclasses to not define a predict method.
The only non-generic which="prob" uses private model specific method _predict_prob.

which = "var" also needs to be model specific, i.e. either another helper function or adding a predict method that partially delegates to super. Or, we could generically go through get_distribution, but that might be too much of a detour.

Everything related to mean function, works generically because all models are parameterized in terms of mean_main mu and prob of inflation (i.e. mean of inflation model).

Do we add other "which" in future that need more model specific computation and methods?
which="cdf" will need to go through the distributions.

aside: we need to explain in docs what the existing which are
'mean', 'mean-main', 'linear', 'mean-nonzero', 'prob-zero, 'prob', 'prob-main'

(I had made a mistake earlier and though prob-zero is the inflation probability. but it's Prob(y=0))

also: generic ZI predict still has the ugly pattern of temporarily changing the model data, model.endog. model.exog, ...

another possible change in future: Do we add dfamilies for ZI models?
It's not a priority, but we might want to add dispersion models ZI Het GPP and ZI Het NBP, and eventually ZI Het BetaBinomial,
with two possible exog for the main model.

All 3 ZI models have model specific _dispersion_factor in the results class as cached property.
We could use that for resid_pearson directly.
But it cannot be used for prediction for new data.

@josef-pkt

josef-pkt commented Dec 11, 2021 •

Copy link
Copy Markdown
Member Author

another option #7923 add predict(which="_dargs")

needs distribution specific return, mu and alpha and w in zi case
(mu, w) could be handled generically, but we need to handle the extra param alpha in ZIGPP, ZINBP
This would avoid duplicate computation in repeated calls to predict, as e.g. currently in ZI get_distribution

Once everything is working and has settled, then we need a review and refactor of redundant and duplicated computation.
Currently, I just want to get things to work without refactoring all over the place.

decision for now: new model specific _predict_var (similar to BetaModel) (which is called by predict and it calls predict for w, mu)

update
BetaModel._predict_var takes also exog and endog and calls predict
instead we can use the predicted dargs when calling _predict_var from predict
(somewhere (?) I used that pattern already)
same for zi countmodels

@josef-pkt

josef-pkt commented Dec 12, 2021 •

Copy link
Copy Markdown
Member Author

results .get_distribution is defined in DiscreteResults and inherited by ZI models

The individual ZI results classes define get_margeff, but all raise NotImplementedError

@lgtm-com

lgtm-com Bot commented Dec 12, 2021

Copy link
Copy Markdown

This pull request introduces 1 alert and fixes 1 when merging 7d9505e into 3600f3f - view on LGTM.com

new alerts:

  • 1 for Module is imported with 'import' and 'import from'

fixed alerts:

  • 1 for Module is imported with 'import' and 'import from'

@josef-pkt

josef-pkt commented Dec 12, 2021 •

Copy link
Copy Markdown
Member Author

post-estimation results for discrete looks more filled in now (after this PR) #7707

main undecided is get_influence, I guess I will default to using resid_pearson which is a safer bet than sf/sqrt(-hf) as default residual.

I haven't checked margeff yet for GPP, NBP, I don't know the status.
update
margeff for NBP has unit tests
GPP get_margeff works, but no unit tests AFAICS, We could add test comparing to NonLinearDeltaCov directly.

@lgtm-com

lgtm-com Bot commented Dec 12, 2021

Copy link
Copy Markdown

This pull request introduces 1 alert and fixes 1 when merging 370c357 into 3600f3f - view on LGTM.com

new alerts:

  • 1 for Module is imported with 'import' and 'import from'

fixed alerts:

  • 1 for Module is imported with 'import' and 'import from'

@lgtm-com

lgtm-com Bot commented Dec 13, 2021

Copy link
Copy Markdown

This pull request introduces 1 alert and fixes 1 when merging 3b9042f into 3600f3f - view on LGTM.com

new alerts:

  • 1 for Module is imported with 'import' and 'import from'

fixed alerts:

  • 1 for Module is imported with 'import' and 'import from'

@josef-pkt

Copy link
Copy Markdown
Member Author

now I added generic resid_pearson.

That's all the features that I wanted to add in this PR.
it doesn't include refactoring to streamline the code.

I should fix some docstrings, then it's ready to merge

Next PR, I guess, get_diagnostic

@lgtm-com

lgtm-com Bot commented Dec 13, 2021

Copy link
Copy Markdown

This pull request introduces 1 alert and fixes 1 when merging e7753c0 into 4458e43 - view on LGTM.com

new alerts:

  • 1 for Module is imported with 'import' and 'import from'

fixed alerts:

  • 1 for Module is imported with 'import' and 'import from'

@josef-pkt

Copy link
Copy Markdown
Member Author

followup

  • streamlining code: it should be possible to reduced code duplication and possibly repeated computations
  • It's still not sure offset and exposure are correctly handled in all predict cases. Needs simple unit tests to check all options combinations
  • consistency across models: e.g. Poisson get_distribution returns 1-dim, newer methods return 2-dim
  • this PR didn't touch GLM. GLM.predict still needs to be "modernized"
  • discrete fittedvalues is still wrong and we cannot reuse it.

@josef-pkt josef-pkt mentioned this pull request Dec 13, 2021
3 of 17 tasks
@josef-pkt

Copy link
Copy Markdown
Member Author

mistakes in docs
https://www.statsmodels.org/dev/generated/statsmodels.discrete.discrete_model.Poisson.predict.html
missing return section
incorrect quotes in linear docs
first line should mention other statistics. I had changed this somewhere (?)

https://www.statsmodels.org/dev/generated/statsmodels.discrete.discrete_model.Poisson.get_distribution.html
"exog" mentions main count model, copy error from ZI docstring

https://www.statsmodels.org/dev/generated/statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoisson.predict.html
is also missing return section
contains appropriate first line "Predict response variable or other statistic given exogenous variables."

results get_distribution is missing docstrings, I didn't check it in this PR
https://www.statsmodels.org/dev/generated/statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.get_distribution.html

results get_prediction
https://www.statsmodels.org/dev/generated/statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.get_prediction.html
looks good overall, first line has wrong part "when endpoint transformation is valid." which is wrong for ZI

generic docstrings don't have appropriate See Also link to the model specific predict method
generic predict/get_prediction don't provide much information, e.g.
https://www.statsmodels.org/dev/generated/statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.predict.html

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.

2 participants