Skip to content

ENH: get_distribution was ZeroInflatedPoisson gives nan, ZeroInflatedGeneralizedPoisson paras are inconsistent #7624

Closed

Description

@thisisreallife

Background

I have an 1-D data, which is a zero inflated count data. So, I try to fit a zero-inflated possion model to get a estimated distribution. I tried with my true data and synthetic data on different models using statsmodels. However, it gives strange results:

  1. ZeroInflatedPoisson gives nan pmf at some simulated data. I did
  2. ZeroInflatedGeneralizedPoisson paramters are inconsistent with different api. Api itself has no documentation.

Statsmodels is not well documented, here is the official guide of statsmodels.discrete.count_model

Question 1, ZeroInlatedPossion gives nan pmf

I want to fit an zero-inflated possion model and then perform a KS-test between data and fitted distribution. However, on synthetic dataset, frozen_dist.pmf(1) gives nan, which means model did not return a zero-inflated poisson distribution.

import numpy as np
import scipy.stats as stats
from statsmodels.discrete.count_model import ZeroInflatedPoisson,ZeroInflatedGeneralizedPoisson,ZeroInflatedNegativeBinomialP

data = stats.bernoulli.rvs(p = 0.4, size = 2000, random_state = 42)*\
stats.poisson.rvs(mu = 5, size = 2000, random_state = 42)
# data1 = np.array([ 0.,  0.,  0.,  0.,  0.,  0.,  0., 15.,  0.,  0.,  0.,  0.,  0.,
#         0.,  0.,  1.,  0.,  1.,  0.,  0.,  0.,  0.,  2.,  1.,  0.,  1.,
#         0.,  0.,  1.,  0.,  0.,  0.,  0.,  1.,  1.,  0.,  0.,  0.,  0.,
#         0.,  0.,  0.,  1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.])

zip_model = ZeroInflatedPoisson(endog = data, exog= np.ones_like(data)) # clarify a model
zip_res = zip_model.fit() # fit model with data to estimate distribution parameters
frozen_dist = zip_model.distribution(*zip_res.params) # frozen a distribution
frozen_dist.pmf(1) # fitted with data, it gives nan; fitted with data1, it gives real values
# stats.kstest(data1, frozen_dist.cdf)

Output:

nan

Question 2, ZeroInflatedGeneralizedPoisson can not frozen a distribution with fitted params

Like ZeroInflatedPoisson, I want to fit a model to estimate distribution parameters and then frozen a distribution based on parameters. However, the paramters of fitted model(zip_res.params) is not consistent with args of zigp_model.distribution, which makes me so confused. I can hardly find any useful documentation about these api.

# zigp model params did not consistent with zigp_model.distribution
data = stats.bernoulli.rvs(p = 0.4, size = 2000, random_state = 42)*\
stats.poisson.rvs(mu = 5, size = 2000, random_state = 42)
# data1 = np.array([ 0.,  0.,  0.,  0.,  0.,  0.,  0., 15.,  0.,  0.,  0.,  0.,  0.,
#         0.,  0.,  1.,  0.,  1.,  0.,  0.,  0.,  0.,  2.,  1.,  0.,  1.,
#         0.,  0.,  1.,  0.,  0.,  0.,  0.,  1.,  1.,  0.,  0.,  0.,  0.,
#         0.,  0.,  0.,  1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.])

zigp_model = ZeroInflatedGeneralizedPoisson(endog = data, exog= np.ones_like(data))
zigp_res = zigp_model.fit()
frozen_dist = zigp_model.distribution(*zip_res.params) # Error in this step
stats.kstest(data, frozen_dist.cdf)

Output:

TypeError: _parse_args() missing 2 required positional arguments: 'p' and 'w'

Output of import statsmodels.api as sm; sm.show_versions()

Details

INSTALLED VERSIONS

Python: 3.6.12.final.0
OS: Darwin 19.6.0 Darwin Kernel Version 19.6.0: Tue Jan 12 22:13:05 PST 2021; root:xnu-6153.141.16~1/RELEASE_X86_64 x86_64
byteorder: little
LC_ALL: None
LANG: zh_CN.UTF-8

statsmodels

Installed: 0.12.1 (/Users/travis/opt/anaconda3/envs/envpython36/lib/python3.6/site-packages/statsmodels)

Required Dependencies

cython: 0.29.21 (/Users/travis/opt/anaconda3/envs/envpython36/lib/python3.6/site-packages/Cython)
numpy: 1.19.5 (/Users/travis/opt/anaconda3/envs/envpython36/lib/python3.6/site-packages/numpy)
scipy: 1.4.1 (/Users/travis/opt/anaconda3/envs/envpython36/lib/python3.6/site-packages/scipy)
pandas: 1.1.5 (/Users/travis/opt/anaconda3/envs/envpython36/lib/python3.6/site-packages/pandas)
dateutil: 2.8.1 (/Users/travis/opt/anaconda3/envs/envpython36/lib/python3.6/site-packages/dateutil)
patsy: 0.5.1 (/Users/travis/opt/anaconda3/envs/envpython36/lib/python3.6/site-packages/patsy)

Optional Dependencies

matplotlib: 3.3.1 (/Users/travis/opt/anaconda3/envs/envpython36/lib/python3.6/site-packages/matplotlib)
backend: module://ipykernel.pylab.backend_inline
cvxopt: Not installed
joblib: 1.0.0 (/Users/travis/opt/anaconda3/envs/envpython36/lib/python3.6/site-packages/joblib)

Developer Tools

IPython: 7.16.1 (/Users/travis/opt/anaconda3/envs/envpython36/lib/python3.6/site-packages/IPython)
jinja2: 2.11.2 (/Users/travis/opt/anaconda3/envs/envpython36/lib/python3.6/site-packages/jinja2)
sphinx: Not installed
pygments: 2.7.1 (/Users/travis/opt/anaconda3/envs/envpython36/lib/python3.6/site-packages/pygments)
pytest: Not installed
virtualenv: Not installed

Activity

  1. josef-pkt commented on Aug 5, 2021

    @josef-pkt
    Member

    I can look at it in 3 or 4 days, I’m currently travelling.

    You could look at the unit tests to see whether the are examples for what you need.
    Also the zero inflated predict method computes many kind of prediction including predicted probabilities. You can look at the code for how we do it.

    Aside: scipy kstext is for continuous distributions and will not be correct for discrete distribution.
    I have a gist notebook for zi models. If I can find it with my ipad

  2. josef-pkt commented on Aug 7, 2021

    @josef-pkt
    Member

    distribution is an attribute of the model class set in __init__, e.g.
    self.distribution = zigenpoisson

    usage for example in ZIP _predict_prob
    result = self.distribution.pmf(counts, mu, w)

    so distribution is not a get_distribution method. It needs distribution args and not model params.

    ZI GPP has in _predict_prob
    result = self.distribution.pmf(counts, mu, params_main[-1], p, w)

    we need a separate get_distribution method that computes the required distribution args from predict and params.
    see issue #106 and recently merged PRs for GLM #7535 and in beta regression #7543

  3. josef-pkt commented on Aug 8, 2021

    @josef-pkt
    Member

    The following works in one example, code based on zip _predict_prob.
    I think the shape handling (for 1-dim) could be changed.

    The frozen distribution has colum_vector args corresponding to observations. This broadcasts with vectorized evaluation, e.g. pmf of a 1-dim array. e.g. distr.pmf([0, 1]) with distr = get_distribution(...).
    However, it always returns 2-d results, e.g distr.mean().shape is (200, 1).
    Do we have the same for other get_distribution returns?

    def get_distribution(self, params, exog, exog_infl, exposure, offset):
        params_infl = params[:self.k_inflate]
        params_main = params[self.k_inflate:]
    
        counts = np.atleast_2d(np.arange(0, np.max(self.endog)+1))
    
        if len(exog_infl.shape) < 2:
            transform = True
            w = np.atleast_2d(
                self.model_infl.predict(params_infl, exog_infl))[:, None]
        else:
            transform = False
            w = self.model_infl.predict(params_infl, exog_infl)[:, None]
    
        w = np.clip(w, np.finfo(float).eps, 1 - np.finfo(float).eps)
        mu = self.model_main.predict(params_main, exog,
            offset=offset)[:, None]
        result = self.distribution(mu, w)
        return result #[0] if transform else result
    
  4. changed the title [-]ZeroInflatedPoisson gives nan, ZeroInflatedGeneralizedPoisson paras are inconsistent[/-] [+]ENH: get_distribution was ZeroInflatedPoisson gives nan, ZeroInflatedGeneralizedPoisson paras are inconsistent[/+] on Dec 24, 2021
  5. josef-pkt commented on Dec 24, 2021

    @josef-pkt
    Member

    closing
    get_distribution was added in #7929 for zi and other countmodels

  6. added this to the 0.13.2 milestone on Feb 8, 2022
  7. modified the milestones: 0.13.2, 0.14 on Apr 14, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions