Skip to content

GSOC2017 Zero-Inflated models - #3755

Closed
evgenyzhurko wants to merge 43 commits into
statsmodels:masterfrom
evgenyzhurko:zi_mle
Closed

evgenyzhurko wants to merge 43 commits into
statsmodels:masterfrom
evgenyzhurko:zi_mle

Conversation

@evgenyzhurko

@evgenyzhurko evgenyzhurko commented Jun 12, 2017 •

Copy link
Copy Markdown
Contributor

This model include following models:

  1. Generic Zero Inflated model
  2. Zero-Inflated Poisson model
  3. Zero-Inflated Generalized Poisson model (ZIGP-P)
  4. Zero-Inflated Generalized Negative Binomial model (ZINB-P)

Each model include this parts:

  • LLF
  • Score
  • Hessian
  • Predict
  • Fit
  • Docs
  • Tests

Status: - reviewing, need to implement better way to generate start_params
Last commit for end of GSoC17: Changed way to find start params

@josef-pkt

Copy link
Copy Markdown
Member

@evgenyzhurko I think the discrete_models.py module is getting too large, especially because there are still more models coming.
Can you start a new module count_model.py and move this over?
You could start a new PR with that file. (otherwise we can do a interactive rebase, which is more work. If you only have one commit, then it is also possible to "amend" the commit and force push.

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage decreased (-0.05%) to 90.388% when pulling 9e5a010 on evgenyzhurko:zi_mle into ac25464 on statsmodels:master.

Comment thread statsmodels/discrete/count_model.py Outdated
w = self.model_infl.predict(params_infl)
llf_main = self.main_model.loglikeobs(params_main)

llf = np.zeros_like(y)

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.

it's better to add the dtype here, np.float64, otherwise it will break if endog is int

Comment thread statsmodels/discrete/count_model.py Outdated
exog_infl=exog_infl,
exposure=exposure,
missing=missing, **kwargs)
self.main_model = Poisson(endog, exog)

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.

switch name to model_main so it similar to model_infl

@josef-pkt

Copy link
Copy Markdown
Member

I just had a quick look and it looks good so far, the structure looks fine.

a tip: I usually have an example script file during development in a separate process that I can run before I have unit tests. This catches basic mistakes like import errors or undefined variables. (if they don't show up in the editor already with flake or other code inspection tool.)

@josef-pkt

Copy link
Copy Markdown
Member

an early comment to possible convergence problems (because I just sorted some articles with two part estimation):

If we run into convergence problems, then it might be better to implement zero-truncated Poisson before resolving those. Zero-truncated should provide good starting values for the Zero-Inflated version, and we can estimate the two parts separately for the start_params.
That mainly means that in the first round we shouldn't spend a large amount of time fixing convergence problems in the unit tests for Zero-Inflated if those problems show up.

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage decreased (-0.05%) to 90.381% when pulling 2dce807 on evgenyzhurko:zi_mle into ac25464 on statsmodels:master.

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.002%) to 90.438% when pulling e49119e on evgenyzhurko:zi_mle into ac25464 on statsmodels:master.

@evgenyzhurko

Copy link
Copy Markdown
Contributor Author

@josef-pkt I didn't implement predict for counts, because it's need to implement zero inflated poisson distribution. Will all good with rebase, when i'll try to add same files from different branch?

@josef-pkt

Copy link
Copy Markdown
Member

from which branch do you want to add files?

The main problem is that merging two branches with overlapping files will cause merge conflicts and possibly require interactive rebase, instead of a simple rebase.
That's not really a problem but is more work. But we can do it if it would hold up development otherwise.

(I'm trying to do computer repair and maintenance, and expect that I can go back to this in a few days.)

@evgenyzhurko

Copy link
Copy Markdown
Contributor Author

I created new file with Generalized Poisson destribution (#3727) and i need to implement Zero Inflated Poisson destribution in this file, but this file doesn't exist in this branch.
When we merge #3727 i can rebase to this PR to master, so it's help to avoid merge conflict.

@josef-pkt

Copy link
Copy Markdown
Member

If you add the file in a commit without other changes, then it will be easy to skip the commit during interactive rebase, or regular rebase might recognize it as an empty commit and skip without special handling.
I assume you mean the stats.models.distribution.discrete module. I think there will be no problem during rebase, if you copy the module here.

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage decreased (-0.003%) to 90.433% when pulling d620e32 on evgenyzhurko:zi_mle into ac25464 on statsmodels:master.

@evgenyzhurko

Copy link
Copy Markdown
Contributor Author

@josef-pkt
One more question: what name i can use to which in predict function to predict probabilities for counts?
In #3727 i use prob but i think it's bad name. Maybe prob-count?

@josef-pkt

Copy link
Copy Markdown
Member

"prob" is ok, prob-count is a bit redundant in the "count" addition
The alternative would be "pdf" (I'm not really a fan of "pmf")
(the "d" in "pdf" is with respect to a count measure, if we need a justification)

Sometimes I use multiple aliases for user options if there is no obvious easy to remember word. e.g.
if which in ["prob", "pdf", "pmf"]: return ...

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage decreased (-0.003%) to 90.433% when pulling 55303bc on evgenyzhurko:zi_mle into ac25464 on statsmodels:master.

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage decreased (-0.05%) to 90.385% when pulling 95daa29 on evgenyzhurko:zi_mle into ac25464 on statsmodels:master.

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage decreased (-0.05%) to 90.385% when pulling 1c65cde on evgenyzhurko:zi_mle into ac25464 on statsmodels:master.

Comment thread statsmodels/discrete/count_model.py Outdated

"""
params_infl = params[self.k_exog:]
params_main = params[:self.k_exog]

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 will be difficult for negative binomial and generalized poisson with extra params.
maybe put params_infl first and cut at k_exog_infl, so that params_name could be lenght k_exog or k_exog + 1 for extra_params

Comment thread statsmodels/discrete/count_model.py Outdated

.. math:: \\ln\\lambda_{i}=x_{i}\\beta
"""
return approx_fprime(params, self.loglike)

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 could get the generic chain rule for derivatives, that uses the partial derivatives/score from the two models, main and infl.

@josef-pkt

Copy link
Copy Markdown
Member

I just had a very quick look, generic score looks good.
One thing I just remembered that you might be able to reuse for the inflation model:
BinaryModel has _derivative_predict for derivative of predicted probability with respect to exog.
Something like that could be added for the derivative of predict with respect to params if it is not already available in the score computation

@coveralls

coveralls commented Jun 22, 2017 •

Copy link
Copy Markdown

Coverage Status

Coverage decreased (-0.05%) to 90.444% when pulling e935581 on evgenyzhurko:zi_mle into bb1b013 on statsmodels:master.

@evgenyzhurko

Copy link
Copy Markdown
Contributor Author

@josef-pkt I tried to implement hessian. I successfully implemented d2l/dw2 and d2l/dwdparams but i have problem with d2l/dparams2.
d2l / dparams2 = (hessian_main * llf - score * score) / llf^2 for y=0, where llf, score - for observations, but i have hessian_main as a value(sum of observations).
d2l dparams2 = hessian_main for y>0 there is no problem in this case.

So, i don't know how to avoid this problem.

@coveralls

coveralls commented Jun 22, 2017 •

Copy link
Copy Markdown

Coverage Status

Coverage decreased (-0.04%) to 90.455% when pulling 90b2544 on evgenyzhurko:zi_mle into bb1b013 on statsmodels:master.

@coveralls

coveralls commented Jun 23, 2017 •

Copy link
Copy Markdown

Coverage Status

Coverage decreased (-0.05%) to 90.446% when pulling d847dcf on evgenyzhurko:zi_mle into bb1b013 on statsmodels:master.

Comment thread statsmodels/discrete/count_model.py Outdated
zero_idx = np.nonzero(y == 0)[0]
nonzero_idx = np.nonzero(y)[0]

llf = np.zeros_like(y)

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 needs to make sure it is float64, in case y is still int

@coveralls

coveralls commented Jun 23, 2017 •

Copy link
Copy Markdown

Coverage Status

Coverage decreased (-0.05%) to 90.442% when pulling 9b51fcf on evgenyzhurko:zi_mle into bb1b013 on statsmodels:master.

@coveralls

coveralls commented Jun 23, 2017 •

Copy link
Copy Markdown

Coverage Status

Coverage decreased (-0.05%) to 90.442% when pulling 9b51fcf on evgenyzhurko:zi_mle into bb1b013 on statsmodels:master.

@coveralls

coveralls commented Jun 25, 2017 •

Copy link
Copy Markdown

Coverage Status

Coverage decreased (-0.004%) to 90.49% when pulling 1d91833 on evgenyzhurko:zi_mle into bb1b013 on statsmodels:master.

@evgenyzhurko

Copy link
Copy Markdown
Contributor Author

@josef-pkt During implementing Truncated model i found error in GenericZI and ZIP and Truncated.
So, we can't fully generalize score and gessian for ZI and Truncated and other(like hurdle or altered) model. What's the problem?
Each generic model have part of loglikelihood funtio like 'ln(1 + pmf_main). The main problem with this part is sum of constant or variable with probability under the logarithm. When we try to calculate score of these function we got: 1 / (1 + pmf_main) * d pmf / dparams` or something similar.
From main model we can got only derivatives of ln(pmf), not pmf.
As a result we'll always need in implementation of score and hessian.

Now about ZIP model: it's very strange that it works now. We can avoid implementation score and hessian for observations with y != 0(because there's no sum under logarithm), but for 'y = 0' model require both score and hessian.

I hope you are understood what I tried to explain.

@josef-pkt

Copy link
Copy Markdown
Member

It looks like it's getting close to being finished.
I will go through it one more time tomorrow morning.

There are some parts where computations could be rearranged, but the important part is that the computation work correctly and are tested. (and maybe some details that I have to verify again when I have updated my checkout to the latest version of this PR)

@coveralls

coveralls commented Aug 30, 2017 •

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.1%) to 81.444% when pulling 86d87ba on evgenyzhurko:zi_mle into d0af408 on statsmodels:master.

@coveralls

coveralls commented Aug 30, 2017 •

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.1%) to 81.444% when pulling 86d87ba on evgenyzhurko:zi_mle into d0af408 on statsmodels:master.

@josef-pkt

Copy link
Copy Markdown
Member

This pull request introduces 25 alerts - view on lgtm.com

new alerts:

  • 24 for Module-level cyclic import
  • 1 for First argument to super() is not enclosing class

Comment posted by lgtm.com

@coveralls

coveralls commented Aug 31, 2017 •

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.1%) to 81.445% when pulling 8c0bf2b on evgenyzhurko:zi_mle into d0af408 on statsmodels:master.

@josef-pkt

Copy link
Copy Markdown
Member

This pull request introduces 25 alerts - view on lgtm.com

new alerts:

  • 24 for Module-level cyclic import
  • 1 for First argument to super() is not enclosing class

Comment posted by lgtm.com

@evgenyzhurko

Copy link
Copy Markdown
Contributor Author

Predicted prob of Zero Inflated Poisson model returns nan with new exposure. Optional offset works well.

@coveralls

coveralls commented Aug 31, 2017 •

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.1%) to 81.445% when pulling ba8f019 on evgenyzhurko:zi_mle into d0af408 on statsmodels:master.

@josef-pkt

Copy link
Copy Markdown
Member

This pull request introduces 25 alerts - view on lgtm.com

new alerts:

  • 24 for Module-level cyclic import
  • 1 for First argument to super() is not enclosing class

Comment posted by lgtm.com

@josef-pkt

Copy link
Copy Markdown
Member

small problem: predict prob raises exception if exog_infl s 1-dimensional,
2d works:
print(which, res_zigp.predict(exog=exog.mean(0), exog_infl=[exog.mean(0)], which=which).shape)

the other which don't raise, so maybe only the specific fix is needed (instead of generic reshape of exog_infl in predict)

...\statsmodels\discrete\count_model.py in _predict_prob(self, params, exog, exog_infl, exposure, offset)
    568         p = self.model_main.parameterization
    569         counts = np.atleast_2d(np.arange(0, np.max(self.endog)+1))
--> 570         w = self.model_infl.predict(params_infl, exog_infl)[:, None]
    571         w[w == 1.] = np.nextafter(1, 0)
    572         mu = self.model_main.predict(params_main, exog,

IndexError: invalid index to scalar variable.

@josef-pkt

Copy link
Copy Markdown
Member

after updating my checkout to current version: all optimizer that I had tried converge to the same results for ZeroInflatedGeneralizedPoisson based on default start_params
basinhopping had converged to wrong params, dogleg had failed on not positive definite hessian computation, trust-ncg converged before and still does
my guess is that the added clip helped for this.

Comment thread statsmodels/discrete/count_model.py Outdated
params_infl = params[:self.k_inflate]
params_main = params[self.k_inflate:]

prob_main = 1 - self.model_infl.predict(params_infl, exog_infl).mean()

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.

I think there should NOT be a .mean() here

The returned which='prob-main' needs to have the same length or nobs as the exog.

Also, I think in the computation of the other which, it should use the observation or exog specific prob_main and not the average prob_main

@josef-pkt

Copy link
Copy Markdown
Member

@evgenyzhurko What's the test coverage for the different predict options?
Fixing a bug should make it possible to tighten the rtol or atol if available.

If needed, I can help coming up with some unit tests for the predict options given that I have tried them out now for some time.

@evgenyzhurko

Copy link
Copy Markdown
Contributor Author

Additional unit tests will be useful.

I also can't find solution to avoid problem with nan, when i use exposure in _predict_prob for ZeroInflatedPoisson model. In other models all is good.

@josef-pkt

Copy link
Copy Markdown
Member

I haven't looked at exposure yet. My guess is that there are most likely problems because of the internal storing of log(exposure) instead of exposure. I will look into it, or we say that exposure is not supported yet.

I only checked ZeroInflatedPoisson docstring in my notebook, and it is still missing the inflation arguments in Parameters.

@coveralls

coveralls commented Aug 31, 2017 •

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.1%) to 81.445% when pulling 95bd417 on evgenyzhurko:zi_mle into d0af408 on statsmodels:master.

@coveralls

coveralls commented Aug 31, 2017 •

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.1%) to 81.454% when pulling bc6b566 on evgenyzhurko:zi_mle into d0af408 on statsmodels:master.

@coveralls

coveralls commented Aug 31, 2017 •

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.1%) to 81.441% when pulling bc6b566 on evgenyzhurko:zi_mle into d0af408 on statsmodels:master.

@josef-pkt

Copy link
Copy Markdown
Member

This pull request introduces 25 alerts - view on lgtm.com

new alerts:

  • 24 for Module-level cyclic import
  • 1 for First argument to super() is not enclosing class

Comment posted by lgtm.com

@josef-pkt

Copy link
Copy Markdown
Member

@evgenyzhurko do you still have any open changes for this PR?

I would like to take this over and make a few more changes before merging.
I thought of merging the PR as is, but I prefer to do a few more cleanups, maybe enhancements and (maybe) bug fixes before merging.

@evgenyzhurko

Copy link
Copy Markdown
Contributor Author

@josef-pkt No, i have no any changes for now.

One open issue is inflation arguments in Parameters.
All arguments described in section Arguments.

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.

4 participants