Skip to content

ENH: add discretized count distribution - #7488

Merged
josef-pkt merged 8 commits into
statsmodels:mainfrom
josef-pkt:discretized_count
Jun 15, 2021
Merged

josef-pkt merged 8 commits into
statsmodels:mainfrom
josef-pkt:discretized_count

Conversation

@josef-pkt

@josef-pkt josef-pkt commented Jun 7, 2021 •

Copy link
Copy Markdown
Member

see #7479 count models based on discretizing a continuous distribution

update:
this now also includes two fixes for base GenericLikelihood Mixin

  • fix aic of k_constant=0
  • fix bootstrap when recreating model with init_keys

open decision: do we use scale keyword of underlying distribution, or do we handle scale explicitly instead of delegating?
update: decided: explicit scale internally,

currently: parameter, args handling is inconistent in scale, it's a shape parameter for the discrete discretized distribution.
if we use scale keyword, then it will not work if the underlying distribution is discrete, which doesn't allow scale

@pep8speaks

pep8speaks commented Jun 7, 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-06-15 18:00:19 UTC

@lgtm-com

lgtm-com Bot commented Jun 7, 2021

Copy link
Copy Markdown

This pull request introduces 1 alert when merging e2e7d1c into 1a57918 - view on LGTM.com

new alerts:

  • 1 for First argument to super() is not enclosing class

@josef-pkt

Copy link
Copy Markdown
Member Author

failure in style check, but no problems (yet) across scipy versions.
scipy.distributions have a lot more argument checking now compared to the old times, and it get's trickier to subclass them when the subclass doesn't fully follow the existing patterns.

@josef-pkt

Copy link
Copy Markdown
Member Author

I decided to use scale keyword and not support discrete underlying distribution. Poisson worked in my initial version, but will not work anymore after the last commit.

@josef-pkt
josef-pkt force-pushed the discretized_count branch from edaf122 to 44bcf15 Compare June 7, 2021 17:01
@josef-pkt
josef-pkt force-pushed the discretized_count branch from 44bcf15 to 0e6edda Compare June 7, 2021 17:12
@lgtm-com

lgtm-com Bot commented Jun 7, 2021

Copy link
Copy Markdown

This pull request introduces 1 alert when merging 77f72e1 into 1a57918 - view on LGTM.com

new alerts:

  • 1 for First argument to super() is not enclosing class

@josef-pkt

Copy link
Copy Markdown
Member Author

Notes to Pareto

Descretinzing classes work when using Pareto. Failure is in chisquare test which produces nan because prob(y=0) = 0.
Problem is that default support in Pareto starts with 1, but I don't have support for reseting loc in my classes.

switching to Lomax, then everything works, shape name differs between Pareto and Lomax.

I haven't tried genpareto yet.

@josef-pkt

Copy link
Copy Markdown
Member Author

the basics looks fine now
exponential with no shape parameter and burr12 with 2 shape parameters, gamma and lomax with 1 shape parameter.

possible test case for regression models: case with only one link function:

A bit similar to AFT: scale parameter uses log link with regressors, shape parameter of the underlying distribution are scalar params_extra

@lgtm-com

lgtm-com Bot commented Jun 7, 2021

Copy link
Copy Markdown

This pull request introduces 1 alert when merging d67bcc3 into 1a57918 - view on LGTM.com

new alerts:

  • 1 for First argument to super() is not enclosing class

@josef-pkt

josef-pkt commented Jun 8, 2021 •

Copy link
Copy Markdown
Member Author

gamlss in R has discrete burr 12
https://rdrr.io/cran/gamlss.dist/man/DBURR12.html

not sure what parameterization they are using. mu doesn't look completely like scale
by default they use 3 log links.

reference is
Para, B. A. and Jan, T. R. (2016). On discrete three parameter Burr type XII and discrete Lomax distributions and their applications to model count data from medical science. Biometrics and Biostatistics International Journal, 54, part 3, pp 507-554.

but docstring mentions that gamlss uses a different parameterization

an application with gamlss for discretized weibull:
Peluso, Alina, Veronica Vinciotti, and Keming Yu. "Discrete Weibull generalized additive model: An application to count fertility data." Journal of the Royal Statistical Society: Series C (Applied Statistics) 68, no. 3 (2019): 565-583.

@josef-pkt

josef-pkt commented Jun 8, 2021 •

Copy link
Copy Markdown
Member Author

freq_weights would be useful for models with discrete observations,
e.g. data without exog is fully specified with just the frequencies.
freq_weights would make it easier to take examples from articles.

blow up, e.g.
y = np.repeat(np.arange(5), [46, 76, 24, 9, 1])

@josef-pkt

Copy link
Copy Markdown
Member Author

change in plans:
this looks good enough to merge, after finishing a few pieces and cleaning up.

Replicating gamma example from Chakraporty et al 2012 (table 7) with MLE is just a few lines, and matches results except for aic.
No exog in this version, just MLE for distribution fitting.

no default start_params (yet), model sublcasses GenericLikelihoodModel
not enough checking for user error.

@josef-pkt

Copy link
Copy Markdown
Member Author

fixing a shape parameter in multiparameter distributions like burr12 will be useful, both for special cases, like pareto in burr12, and because in some multi parameter distributions some parameters can be closely related and not well identified separately.

adding list of special cases to docstrings would also be helpful, avoids having to look it up or search for it each time.

properties of distributions for start_params, specification search and docs.
e.g. under- or over-dispersion, short or long tails.
e.g. GPP can work with small underdispersion. NB might not converge with under dispersion.
gamma (AFAIR) has light tails, discrete Pareto or generalizations of it have heavy tails.

aside Burr article has one example for teeth, but max physical count is 4.
In those cases it would be better to have right truncated distributions or finite support distributions like Binomial.

The version in this PR has fixed support a=0, b=inf.

@lgtm-com

lgtm-com Bot commented Jun 11, 2021

Copy link
Copy Markdown

This pull request introduces 1 alert when merging df5896f into c2d87b6 - view on LGTM.com

new alerts:

  • 1 for First argument to super() is not enclosing class

@josef-pkt

Copy link
Copy Markdown
Member Author

looking at issues with problems in bootstrap method of genericlikelihood results mixin

specifically does it work when exog = None,
TODO: check whether there is still anything open and left to do in #944

res.bootstrap()

it breaks, but it looks like it's because distr is not added to the recreated model.
what's the pattern to register _init_keys?

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-25-f36e0bef4971> in <module>
----> 1 res.bootstrap()

...\statsmodels\statsmodels\base\model.py in bootstrap(self, nrep, method, disp, store)
   2399             else:
   2400                 exog_resamp = None
-> 2401             fitmod = self.model.__class__(self.endog[rvsind],
   2402                                           exog=exog_resamp)
   2403             if hascloneattr:

...\statsmodels\statsmodels\distributions\discrete.py in __init__(self, endog, exog, distr)
    239         self.distr = distr
    240         super().__init__(endog, exog)
--> 241         self.df_resid = len(endog) - distr.k_shapes
    242         self.df_model = distr.k_shapes  # no constant subtracted
    243         self.k_constant = 0

AttributeError: 'NoneType' object has no attribute 'k_shapes'

distr is required even though it is a keyword argument

@josef-pkt

Copy link
Copy Markdown
Member Author

parameter restrictions

statsmodels.statsmodels.miscmodels.tests.test_generic_mle.TestMyParetoRestriction
test case for (continuous) Pareto with parameter restriction, depending on the shape parameters of the underlying distribution.
miscmodel TModel properly implements fixed params in the GenericLikelihood pattern (only for df of t-distribution)

In the case here, we have several parameters that could be restricted.

@josef-pkt

Copy link
Copy Markdown
Member Author

another change in plans: move models for distribution fitting to separate module distribution.estimation

The estimation module can get other classes, e.g. #2527 fit for scipy distributions (that could be similar to what I have in here)
and other non-MLE estimation procedures, e.g. matching quantiles, characteristic function, ... (some are still in sandbox) and minimum distance estimators #7412 (not yet available).

@josef-pkt

Copy link
Copy Markdown
Member Author

@josef-pkt

josef-pkt commented Jun 15, 2021 •

Copy link
Copy Markdown
Member Author

found a bug: rvs didn't work yet, missing random_state keyword

also, I haven't implemented ppf, isf. They should follow from trunc(x_continuous) behavior, but a bit tricky whether open or closed. i.e. continuous cdf at int maps to lower count.

I can use floor or trunc, except if continuous quantile is an int
I think I can use condition np.floor(qc) == qc, and subtract 1 in those cases

update
equality testing doesn't work in roundtrip cdf - ppf unit test
I guess there is too much numerical noise that the continuous quantile qc could be just above the integer.

Either I leave numerical precision to the user, and fix the unit test or I add a fudge factor np.floor(qc * (1 - 1e-15))
This should produce the "expected" results for round trip, but will give wrong result if the "true" prob for ppf is above int. the latter should be an unlikely case.

I also need to implement sf and isf to get better precision in the upper tails.
same integer problem with isf as with ppf. The multiplicative fudge factor is relative and shrinks with smaller prob in tail.

@josef-pkt

josef-pkt commented Jun 15, 2021 •

Copy link
Copy Markdown
Member Author

test case
discrete exponential (scale = -1/np.log(p)) is the same as scipy.stats version geom(p, loc=-1) or p = exp(- 1 / scale_dexpon)
second page of Chakraborty gamma article 2012

correction scale_dexpon = -1 / np.log(1 - p_geom) (p and 1-p are flipped)
(my initial example had p = 1 - p = 0.5 )

things match so far, including ppf and isf (with fudge factor)

@lgtm-com

lgtm-com Bot commented Jun 15, 2021

Copy link
Copy Markdown

This pull request introduces 1 alert when merging f4299c3 into c2d87b6 - view on LGTM.com

new alerts:

  • 1 for First argument to super() is not enclosing class

@josef-pkt

josef-pkt commented Jun 15, 2021 •

Copy link
Copy Markdown
Member Author

first time version specific test failures.
It's a missing seed in rvs generation. scipy.stats.chisquare test returns nan if (freqs ? or) probs are zero.

incorrect there is already a seed in the test method

@josef-pkt
josef-pkt force-pushed the discretized_count branch from f4299c3 to 245b5e5 Compare June 15, 2021 13:51
@josef-pkt

josef-pkt commented Jun 15, 2021 •

Copy link
Copy Markdown
Member Author

The last commit after which the failure started changed my rvs to _rvs, i.e. we go through scipy wrapper function instead of calling the distribution specific rvs directly.
Maybe something strange with scipy 1.3 and 1.4 in rvs/random_state

update
It looks like it is the size keyword.
This was introduced in scipy 1.5 scipy/scipy@a193f8e
This means I have to support the old _size attribute instead of keyword. I don't remember how exactly that worked.

I guess it created only a single observation. It's strange that we could estimate parameters, AFAICS, only lomax failed to converge. There is no hardocded nobs or check that the data has the correct length. I will add an assert for len(y).

@josef-pkt
josef-pkt force-pushed the discretized_count branch from 245b5e5 to 02eb87f Compare June 15, 2021 14:15
@josef-pkt

josef-pkt commented Jun 15, 2021 •

Copy link
Copy Markdown
Member Author

another failure with scipy <1.5, discrete ppf, was wrong at boundary if loc!=0
fixed in scipy/scipy@d6483ae

        ppf1 = dgeo.ppf(0)
        ppf = dpg.ppf(0)
>       assert_equal(ppf, ppf1)
E       AssertionError: 
E       Items are not equal:
E        ACTUAL: -1.0
E        DESIRED: 0.0

AFAICS in the scipy code, isf has not been fixed for loc at boundary
I opened scipy/scipy#14236

@lgtm-com

lgtm-com Bot commented Jun 15, 2021

Copy link
Copy Markdown

This pull request introduces 1 alert when merging 02eb87f into 1b009b1 - view on LGTM.com

new alerts:

  • 1 for First argument to super() is not enclosing class

@josef-pkt
josef-pkt force-pushed the discretized_count branch from 02eb87f to 464b4dc Compare June 15, 2021 15:20
@josef-pkt

Copy link
Copy Markdown
Member Author

another amend and force push. This should now fix the unit tests for problems with scipy

@lgtm-com

lgtm-com Bot commented Jun 15, 2021

Copy link
Copy Markdown

This pull request introduces 1 alert when merging 464b4dc into 1b009b1 - view on LGTM.com

new alerts:

  • 1 for First argument to super() is not enclosing class

@josef-pkt

Copy link
Copy Markdown
Member Author

all green
LGTM complains about the class in a super call, but I intentionally skip the immediate super class. We do it also in some cases in discrete.
(I don't know how to turn off that complaint)

@josef-pkt

josef-pkt commented Jun 15, 2021 •

Copy link
Copy Markdown
Member Author

distribution docs needs updating
the distribution page currently shows mainly sandbox code
https://www.statsmodels.org/dev/distributions.html

I will add the count distributions for now, and leave more rewriting and reorganizing for later.

For example, I don't know what the status of statsmodels.distributions.edgeworth is. I haven't looked at expansions in a very long time. The last substantive change was in 2014 (by Evgeni), since then only maintenance.
I don't remember how this matches with my sandbox code, distributions.html mentions Gram-Charlier expansion with a similar normal expansion class https://www.statsmodels.org/dev/generated/statsmodels.sandbox.distributions.extras.NormExpan_gen.html

@lgtm-com

lgtm-com Bot commented Jun 15, 2021

Copy link
Copy Markdown

This pull request introduces 1 alert when merging 0ce4f9d into 1b009b1 - view on LGTM.com

new alerts:

  • 1 for First argument to super() is not enclosing class

@josef-pkt

josef-pkt commented Jun 15, 2021 •

Copy link
Copy Markdown
Member Author

aside: statsmodels.distributions does not have an api.py. Functions and classes are imported in the __init__.py module.
In #7408 I add a copula/api.py but not one for the distribution directory.

I don't want to add more to the __init__.py, we should (eventually) use an api.py also here.

another aside: inconsistency in naming generalized poisson GPP distributions:
genpoisson_p
genpoisson_p_gen
zigeneralizedpoisson_gen
zigenpoisson

@josef-pkt

Copy link
Copy Markdown
Member Author

I just saw that I'm not implementing _argcheck for DiscretizedCount
I assume it's handled by the underlying continuous distribution, but I didn't check whether that works for all methods. I think it should.

@josef-pkt
josef-pkt force-pushed the discretized_count branch from 0ce4f9d to 1564321 Compare June 15, 2021 18:00
@josef-pkt

Copy link
Copy Markdown
Member Author

codecov is high, just a few lines

missing cases in unit tests:

  • add_scale=False
  • d_offset != 0

and some exceptions, ValueError

@lgtm-com

lgtm-com Bot commented Jun 15, 2021

Copy link
Copy Markdown

This pull request introduces 1 alert when merging 1564321 into 1b009b1 - view on LGTM.com

new alerts:

  • 1 for First argument to super() is not enclosing class

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