Skip to content

GSOC2017 Truncated and Hurdle count models - #3802

Closed
evgenyzhurko wants to merge 22 commits into
statsmodels:mainfrom
evgenyzhurko:truncated_model
Closed

evgenyzhurko wants to merge 22 commits into
statsmodels:mainfrom
evgenyzhurko:truncated_model

Conversation

@evgenyzhurko

@evgenyzhurko evgenyzhurko commented Jul 2, 2017 •

Copy link
Copy Markdown
Contributor

This PR include following models:

  1. Generic Truncated model
  2. Truncated Poisson model
  3. Truncated Generalized Poisson model
  4. Truncated Negative Binomial model
  5. Generic Censored model
  6. Censored Poisson model
  7. Censored Generalized Poisson model
  8. Censored Negative Binomial model
  9. Hurdle model
    a. Poisson - Poisson
    b. Poisson - Negative Binomial
    c. Negative Binomial - Negative Binomial
    d. Negative Binomial - Poisson

Each model include this parts:

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

Status: - reviewing, need to improve tests for this models.

All this model include in a single PR, because hurdle model based on truncated and censored model.

Last commit before GSoC final evaluation: Implemented Censored Genralized Poisson model

@evgenyzhurko evgenyzhurko mentioned this pull request Jul 2, 2017
7 tasks done
Comment thread statsmodels/discrete/count_model.py Outdated
"""
llf_main = self.model_main.loglikeobs(params)

pmf = np.zeros_like(self.endog)

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.

dtype in case endog is int

@josef-pkt josef-pkt left a comment

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 made some comments on outsourcing truncation probability cdf.
However, after thinking a bit more, using the cdf instead of the pdf loop might not improve performance if the main use case is zero-truncation or at most a few counts.

for i in range(self.trunc + 1):
model = self.model_main_name(np.ones_like(self.endog) * i,
self.exog)
pmf += np.exp(model.loglikeobs(params))

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 loop could be put into a cdf method that can be overwritten by a subclass.
E.g. poisson should have a build in method (or method delegated to scipy distribution cdf)

self.exog)
pmf_i = np.exp(model.loglikeobs(params))
score_trunc += (model.score_obs(params).T * pmf_i).T
pmf += pmf_i

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'm not sure whether it will be very useful, but this could be put into a separate cdf_deriv method.

Overall, for the design: we should outsource parts to separate methods, if it is useful to override the method for specific models or distributions that have a analytical or computational more efficient way to calculate those parts.

Comment thread statsmodels/discrete/count_model.py Outdated
self.exog)
pmf_i = np.exp(model.loglikeobs(params))
score_trunc += (model.score_obs(params).T * pmf_i).T
pmf += pmf_i

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.

? now this is cdf and deriv at the same time.
So maybe one method that optionally returns either or both.

(but then there is still hessian_trunc)

@evgenyzhurko

evgenyzhurko commented Jul 3, 2017 •

Copy link
Copy Markdown
Contributor Author

@josef-pkt I tried to evaluate generic hessian, but it isn't successfully. The main problem that truncated model have variable amount of pmf(depends of truncation value)
llf = pmf_main(y, x) / (1 - pmf_main(0, x)) for Zero-Truncated
llf = pmf_main(y, x) / (1 - pmf_main(0, x) + pmf_main(1, x) + pmf_main(2, x)) for truncation=2 and so on.
I skip analytic hessian for now.
I'll return for analytic hessian later.

For now, model works well for different trucation(i tested 0 and 5), results equal to STATA.
This model will be a good base for altered(adjusted) model.

@coveralls

coveralls commented Jul 3, 2017 •

Copy link
Copy Markdown

Coverage Status

Coverage decreased (-0.0003%) to 90.86% when pulling b0ba6c2 on evgenyzhurko:truncated_model into 359f08b on statsmodels:master.

@coveralls

coveralls commented Jul 4, 2017 •

Copy link
Copy Markdown

Coverage Status

Coverage decreased (-0.0003%) to 90.86% when pulling 46a0808 on evgenyzhurko:truncated_model into 359f08b on statsmodels:master.

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage decreased (-0.06%) to 90.804% when pulling 980d6cd on evgenyzhurko:truncated_model into 359f08b on statsmodels:master.

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage decreased (-0.09%) to 90.774% when pulling 7716d1f on evgenyzhurko:truncated_model into 359f08b on statsmodels:master.

Comment thread statsmodels/discrete/count_model.py Outdated
elif which == 'linear':
return linpred
elif which =='prob':
counts = np.atleast_2d(np.arange(0, np.max(self.endog)+1))

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 starting at zero is good for consistency, even though probabilities below trunc will be zero.

I think we should add an optional count_prob or similarly named argument for this, in analogy to the n parameter in PoissonResults.predict_prob


""" + base._missing_param_doc}

def __init__(self, endog, exog, truncation=0, offset=None,

@josef-pkt josef-pkt Jul 8, 2017 •

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.

truncation argument needs to be added to the docstring.
Specifically, it needs to specify whether the truncation point is in the support or out of support of the distribution.
i.e. pmf(k) = 0 for k < truncation or for k<= truncation?

@josef-pkt

Copy link
Copy Markdown
Member

doc strings still need work, several are incomplete

@josef-pkt

Copy link
Copy Markdown
Member

travis test runs fail on python 3 because of a left in py 2 print statement

File "/home/travis/build/statsmodels/statsmodels/statsmodels/discrete/count_model.py", line 353
    print endog[endog > 0].mean()


class TestTruncatedPoissonModel(object):
@classmethod
def setupClass(cls):

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.

please use setup_class to simplfy moving to pytest.


class TestZeroTruncatedPoissonModel(object):
@classmethod
def setupClass(cls):

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.

Same here

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage decreased (-0.07%) to 90.786% when pulling ba33545 on evgenyzhurko:truncated_model into 359f08b on statsmodels:master.

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage decreased (-0.06%) to 90.801% when pulling db68ff1 on evgenyzhurko:truncated_model into 359f08b on statsmodels:master.

@coveralls

coveralls commented Jul 16, 2017 •

Copy link
Copy Markdown

Coverage Status

Coverage decreased (-0.006%) to 90.854% when pulling d69ec1e on evgenyzhurko:truncated_model into 359f08b on statsmodels:master.

@coveralls

coveralls commented Jul 16, 2017 •

Copy link
Copy Markdown

Coverage Status

Coverage decreased (-0.02%) to 90.854% when pulling 42f1855 on evgenyzhurko:truncated_model into 5ec2856 on statsmodels:master.

@coveralls

coveralls commented Jul 19, 2017 •

Copy link
Copy Markdown

Coverage Status

Coverage decreased (-0.05%) to 90.825% when pulling c27ab36 on evgenyzhurko:truncated_model into 5ec2856 on statsmodels:master.

@evgenyzhurko evgenyzhurko changed the title Implemented Trucated model Trucated and Hurdle models Jul 20, 2017
@coveralls

coveralls commented Jul 20, 2017 •

Copy link
Copy Markdown

Coverage Status

Coverage decreased (-0.07%) to 90.805% when pulling 4c83fc4 on evgenyzhurko:truncated_model into 5ec2856 on statsmodels:master.

Comment thread statsmodels/discrete/count_model.py Outdated

""" + base._missing_param_doc}

def __init__(self, endog, exog, offset=None,

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 we should have two exog as in zero-inflated, one for the zeros and one for y > 0

Comment thread statsmodels/discrete/count_model.py Outdated

y = self.endog
zero_idx = np.nonzero(y == 0)[0]
nonzero_idx = np.nonzero(y)[0]

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.

to avoid recomputing this, it would be better to put this in __init__ and attach as attributes.

It might be more efficient to also separate endog and exog into the zero and non-zero parts and attach as internal attributes. It would use more permanent memory, but might be faster. (maybe some timing is necessary to see whether it's worth it.) If we have time before the end of GSOC we could some performance checks to see whether and where the speed can be improved, but for now the priority is to get a working and unit tested version.

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.

actually, the split would be part of the models, since exog don't show up in these methods directly

Comment thread statsmodels/discrete/count_model.py Outdated
missing=missing, **kwargs)
self.model1 = self.model_name1(
np.zeros_like(self.endog, dtype=np.float64), self.exog)
self.model2 = self.model_name2(self.endog, self.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.

shouldn't model2, the truncated model, only get endog and exog for non-zero endog observations (y > 0)?
y = 0 should not be an observation in the support of the zero-truncated model.
or is this not imposed at this point, i.e. in the generic setting?

@coveralls

coveralls commented Jul 21, 2017 •

Copy link
Copy Markdown

Coverage Status

Coverage decreased (-0.01%) to 90.867% when pulling 774de60 on evgenyzhurko:truncated_model into 5ec2856 on statsmodels:master.

@coveralls

coveralls commented Jul 22, 2017 •

Copy link
Copy Markdown

Coverage Status

Coverage decreased (-0.001%) to 90.877% when pulling d43d2ff on evgenyzhurko:truncated_model into 5ec2856 on statsmodels:master.

@coveralls

coveralls commented Jul 22, 2017 •

Copy link
Copy Markdown

Coverage Status

Coverage decreased (-0.02%) to 90.862% when pulling 3d487f7 on evgenyzhurko:truncated_model into 5ec2856 on statsmodels:master.

@evgenyzhurko

evgenyzhurko commented Aug 7, 2017 •

Copy link
Copy Markdown
Contributor Author

@josef-pkt
I refactored hurdle model, but i don't know how i can implement result class for 2 models.
I also implemented zero-censored model in additional to hurdle model, as a result hurdle model have a simple structure.
Current hurdle model results(params and llf) equal to R results(pscl package).

Do you have any idea how i can implement result class?

@josef-pkt

Copy link
Copy Markdown
Member

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

new alerts:

  • 29 for Module-level cyclic import
  • 2 for First argument to super() is not enclosing class
  • 1 for Explicit export is not defined

Comment posted by lgtm.com

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage decreased (-0.1%) to 81.196% when pulling 50ad467 on evgenyzhurko:truncated_model into 92a66d7 on statsmodels:master.

@coveralls

coveralls commented Aug 21, 2017 •

Copy link
Copy Markdown

Coverage Status

Coverage decreased (-0.08%) to 81.246% when pulling 50ad467 on evgenyzhurko:truncated_model into 92a66d7 on statsmodels:master.

@josef-pkt

Copy link
Copy Markdown
Member

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

new alerts:

  • 30 for Module-level cyclic import
  • 2 for First argument to super() is not enclosing class
  • 1 for Missing call to init during object initialization
  • 1 for Explicit export is not defined

Comment posted by lgtm.com

@josef-pkt

Copy link
Copy Markdown
Member

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

new alerts:

  • 30 for Module-level cyclic import
  • 2 for First argument to super() is not enclosing class
  • 1 for Missing call to init during object initialization
  • 1 for Explicit export is not defined

Comment posted by lgtm.com

@josef-pkt

Copy link
Copy Markdown
Member

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

new alerts:

  • 32 for Module-level cyclic import
  • 2 for First argument to super() is not enclosing class
  • 1 for Missing call to init during object initialization
  • 1 for Syntax error
  • 1 for Explicit export is not defined

Comment posted by lgtm.com

@josef-pkt

Copy link
Copy Markdown
Member

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

new alerts:

  • 30 for Module-level cyclic import
  • 2 for First argument to super() is not enclosing class
  • 1 for Missing call to init during object initialization
  • 1 for Explicit export is not defined

Comment posted by lgtm.com

@josef-pkt

Copy link
Copy Markdown
Member

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

new alerts:

  • 30 for Module-level cyclic import
  • 2 for First argument to super() is not enclosing class
  • 1 for Missing call to init during object initialization

Comment posted by lgtm.com

@evgenyzhurko evgenyzhurko changed the title Trucated and Hurdle models GSOC2017 Trucated and Hurdle models Aug 29, 2017
@josef-pkt

Copy link
Copy Markdown
Member

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

new alerts:

  • 35 for Module-level cyclic import
  • 2 for First argument to super() is not enclosing class
  • 1 for Missing call to init during object initialization

Comment posted by lgtm.com

@josef-pkt

Copy link
Copy Markdown
Member

@evgenyzhurko I don't think I have time to go through this in detail within the next few weeks (if we want to get the release out).

main question: What did you use as references for this, especially for the censored model and the hurdle model implemented through censored + truncated?

I just found an older Stata package http://www.stata-journal.com/article.html?article=st0219 and just realised that Stata 14 includes cpoisson as new model.
Based on the loglikeobs, the current version is not a general censored model, but only supports the model for the zeros as in the zero-modified hurdle model. (i.e. no censoring at user defined points larger than 1.) Given that, it needs to be either extended to arbitrary right censoring, or privatised for now, prepend underscore to the class names _CensordXxx, so it's clear that it is used only to support the hurdle models.
(I never looked at the literature specific to censored count models.)

@evgenyzhurko

Copy link
Copy Markdown
Contributor Author

@josef-pkt
I have not got any articles for the Censored model, i looked through the hurdle model in the R and implemented in the same way.

You are right, that you need to implement Generic model with the same censoring param like in the truncation model.
I think it will be better to review this model in 2-3 weeks (I'll busy during the next week, so i'll continue in one week later).
I'll also want to add tests, because current censored and hurdle models not covered yet.

@josef-pkt

Copy link
Copy Markdown
Member

I did a brief check on the literature
Stata cpoisson has some references
Cameron Trivedi have a section on hurdle models: They mention that Mullahy in the original paper on modified count models uses the same distribution (family) for the zeros as for the non-zero part, e.g. Poisson. The advantage is that we can test against a single distribution by equality of the two sets of parameters when using the same exog in both parts. (I didn't check yet: CT mention that Mullahy also has a Hausman test as specification test.)
The now more common specification is to use Logit or Probit as a binary model for the zeros.

I haven't checked Winkelman's textbook yet, which is also in the Stata references for cpoisson.

One possibility would be to consider the current Censored models as additional binary models, and allow Hurdle to use either the BinaryCensored or a binary model, Logit, Probit, for the zeros.

(Another obvious extension would be to allow Hurdle models to specify a larger than zero transition point, so we combine a general Censored with a general Truncated count model, i.e. stitch together two count models. I haven't seen this in any reference but it would be just one additional parameter in hurdle models when the general Censored count models are available.)

llf_main = self.model_main.loglikeobs(params)

llf = np.concatenate((llf_main[self.zero_idx],
np.log(1 - np.exp(llf_main[self.nonzero_idx]))))

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.

as explanation:
np.exp(llf_main[self.nonzero_idx])) is the probability for y=0 given x, because the model_main has endog=zeros

@josef-pkt josef-pkt changed the title GSOC2017 Trucated and Hurdle models GSOC2017 Truncated and Hurdle count models Nov 19, 2020
@josef-pkt

Copy link
Copy Markdown
Member

I'm trying to rebase this on current main

merge conflict are very difficult
merge diff wants to convert ZeroInflated model into Truncated Model, so we get many small conflicts

@josef-pkt josef-pkt mentioned this pull request Dec 22, 2021
@josef-pkt josef-pkt added this to the 0.14 milestone Dec 23, 2021
@josef-pkt josef-pkt added the superseded Used for PRs with content that is superseded by a newer PR label Feb 14, 2022
@josef-pkt

Copy link
Copy Markdown
Member

merged in #7973
followup in #8031

@josef-pkt josef-pkt closed this Feb 14, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-discrete superseded Used for PRs with content that is superseded by a newer PR type-enh

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants