Skip to content

ENH: Truncated, hurdle count model rebased - #7973

Merged
josef-pkt merged 19 commits into
statsmodels:mainfrom
josef-pkt:truncated_model_rebased
Jan 22, 2022
Merged

josef-pkt merged 19 commits into
statsmodels:mainfrom
josef-pkt:truncated_model_rebased

Conversation

@josef-pkt

Copy link
Copy Markdown
Member

rebased on main.

it's working, but unit tests fail, and some merge conflict resolutions might be incorrect

@pep8speaks

pep8speaks commented Dec 22, 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 2022-01-21 19:05:00 UTC

@josef-pkt

josef-pkt commented Dec 22, 2021 •

Copy link
Copy Markdown
Member Author

my experimental truncation class in #7922 (comment)
produces the same result as the unit test result in here for zero truncated Poisson with Randhie data

The test with this PR for TestZeroTruncatedPoissonModel also passes
The poisson truncation test with truncation=5 TestTruncatedPoissonModel fails.
The results module doesn't show what commands were used to create the reference numbers.

I also get with my class a bit different params at low=6, but I get a closer match to the reference numbers with low=5.
???
I'm using "nm" to get start_params for "newton" with my version.

@lgtm-com

lgtm-com Bot commented Dec 22, 2021

Copy link
Copy Markdown

This pull request introduces 5 alerts when merging 0f2328e into 590384e - view on LGTM.com

new alerts:

  • 3 for Unused import
  • 2 for First argument to super() is not enclosing class

@josef-pkt

Copy link
Copy Markdown
Member Author

and I think pytest runs setup_class again for each method. i.e. we are wasting a lot of computing time for repeated fit of the same thing.
maybe not, the test class also includes regularized fit that causes convergence warnings

@bashtage

Copy link
Copy Markdown
Member

Iirc or runs it once per worker which is 2 on CI. There is a switch that tried to parallelize by keeping test files on the same worker. Not sure if we use that or not.

@josef-pkt

Copy link
Copy Markdown
Member Author

most likely I was mistaken,
I didn't go through the test classes in details yet, and the warnings that I see might correspond to different calls of fit.

@josef-pkt
josef-pkt force-pushed the truncated_model_rebased branch from 0f2328e to 22332e5 Compare December 23, 2021 14:16
@josef-pkt

josef-pkt commented Dec 23, 2021 •

Copy link
Copy Markdown
Member Author

amended last commit to fix remaining errors when running unit tests
5 failures remain
5 failed, 22 passed, 23 warnings in 7.74s for discrete\tests\test_truncated_model.py

warnings are RuntimeWarnings (zero division, invalid values, ...) and Convergence warnings mainly in fit_regularized

about numeric failures
most are not large, and estimated parameters are small, 1e-3, 1e-4,
convergence tolerance both in statsmodels and in reference numbers could be the cause of failures.
all those are in TestTruncatedPoissonModel

update when I switch to method="newton", then those tests pass,
specifying "bfgs" doesn't help and might be the default

test_truncated_model.TestTruncatedNBP_predict test_var fails by a large amount, 5.5 instead of 15.0,
either unit test or code is wrong, and test had error before because of a typo

@lgtm-com

lgtm-com Bot commented Dec 23, 2021

Copy link
Copy Markdown

This pull request introduces 5 alerts when merging 22332e5 into 590384e - view on LGTM.com

new alerts:

  • 3 for Unused import
  • 2 for First argument to super() is not enclosing class

@josef-pkt
josef-pkt force-pushed the truncated_model_rebased branch from 22332e5 to 47ea32c Compare December 23, 2021 15:17
@josef-pkt

josef-pkt commented Dec 23, 2021 •

Copy link
Copy Markdown
Member Author

my git has changed, no automatic trailing whitespace cleanup anymore during rebase

this only includes unit test for truncated poisson and truncated NBP.
no unit test, not even smoke tests for the other models

I deleted the __main__ parts during rebase, I need to look for examples for censored and hurdle models.
Currently, I don't know what Censored models are supposed to be and do.
update it looks like right censored, with 0 and non-zero as observations

Hurdle model combines Censored for zeros and Truncated model for y>0

I made a comment in the original PR to rename Censored or privatize it, because it hardcodes the censoring location y=0 versus y>0.
Stata has censored poisson that allows left-, right- and interval-censoring.

Comment thread statsmodels/discrete/truncated_model.py Outdated
exposure=exposure,
offset=offset)
self.model_dist = truncatedpoisson
self.result = TruncatedPoissonResults

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

these should have class in the name as other count models
it looks like we only have it in ZI models self.result_class ,...

@josef-pkt

josef-pkt commented Dec 23, 2021 •

Copy link
Copy Markdown
Member Author
  • there is no distribution class for truncated GPP, only Poisson and NBP
    from statsmodels.distributions import truncatedpoisson, truncatednegbin
    GPP will be more difficult because we don't have cdf for it (except generic brute force)
  • Censored and Hurdle models don't have predict, they might inherit the wrong CountModel.predict
  • Truncated model uses fixed truncation point, the same for all observations.
    that works for hurdle models or zero truncation, but not for general case
  • Hurdle model assumes exog in censored model for zeros and in truncated model are the same
  • Hurdle model: how is cov_params computed? currently no explicit computation
    Is it just block-diagonal based on the cov_params/hessian of the two separate models?
    Also, fit includes cov_type but the model does not have score_obs
  • ...
  • ...

Note:
GenericCensored model reorders observations in loglikeobs and score_obs, (zeros and nonzeros)

@lgtm-com

lgtm-com Bot commented Dec 23, 2021

Copy link
Copy Markdown

This pull request introduces 5 alerts when merging 47ea32c into 590384e - view on LGTM.com

new alerts:

  • 3 for Unused import
  • 2 for First argument to super() is not enclosing class


pmf = np.zeros_like(self.endog, dtype=np.float64)
score_trunc = np.zeros_like(score_main, dtype=np.float64)
for i in range(self.trunc + 1):

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this should use cdf when available, i.e. Poisson and NBP
instead of loop

@josef-pkt

josef-pkt commented Dec 23, 2021 •

Copy link
Copy Markdown
Member Author

There is still much work to do, and to read up on the models. (I don't know the formulas, e.g. for predict or loglike for hurdle)
even without redesigning and generalizing the models.

We want to include the hurdle model as counterpart to zero-inflated models.
Truncated and censored here are designed to support the hurdle model. (e.g. cdf of lower truncation point for zero truncation is just the prob of zero, a loop to compute cdf from pmf has just one element.)
For general truncation and censoring, we would need more general versions of those models.

I renamed the module to truncated_model, something more with "hurdle" would have been more appropriate.

One question is whether making Truncated models here public or whether to keep those class names reserved for more general versions. on possibility would be to add "FT" to the class name for "fixed truncation". Then we can still optimize the compuations for this case.

Censored is too specialized to use those class names.

https://data.princeton.edu/wws509/notes/countmoments
includes conditional mean and var for zero-truncated and hurdle models poisson, NB (2?)

Comment thread statsmodels/discrete/truncated_model.py Outdated
cov_kwds = {}

result._get_robustcov_results(cov_type=cov_type,
use_self=True, use_t=use_t, **cov_kwds)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this shouldn't be needed here.
The call to super in results class should handle this already

@josef-pkt

josef-pkt commented Jan 1, 2022 •

Copy link
Copy Markdown
Member Author

BUG: truncated models, df_resid uses full observations count not selected (endog >= truncation).

from summary of a simple example (simulated poisson data, for nobs=5000, example is truncation=1)

No. Observations: 3080
Model: TruncatedPoisson Df Residuals: 4998

as a consequence wald_test with use_f=True is wrong.

(in the example wald_test rejects null that params are equal to dgp params)
I had made a mistake in defining the restriction

@josef-pkt

Copy link
Copy Markdown
Member Author

prob plot doesn't look correct for truncated poisson

prob plot for zero-truncated seems to use truncated sample for freq,
probs look like unconditional counts/probabilities. truncated zero count has positive expected count
maybe something wrong with statsmodels.distributions.discrete.truncatedpoisson_gen

dia = res_t0.get_diagnostic()
dia.plot_probs();

image

@josef-pkt

josef-pkt commented Jan 16, 2022 •

Copy link
Copy Markdown
Member Author

question: Is negbin dispersion parameter identified in the constant only zero-model ?
#8020

In some runs with constant only negbin-negbin hurdle I get non-invertible hessian.
Maybe in the constant only model we have problems with non-identification similar to variance in Probit is not identified and needs to be fixed.
With non-constant exog, we will have inherent heteroscedasticity which should make dispersion parameter identified, I guess.

(just guessing, I haven't looked for references for this.)

Aside: current code uses full count data for computation of start_params, so this will be standard negbin which is identified.

seems to be the problem
evals don't look so small, condition number and bse are large
(sample selection problem, I ran this when I didn't get a non-invertible hessian)


np.linalg.eigvalsh(cov), np.linalg.eigvalsh(cov[:2, :2])
(array([2.42009371e-05, 2.56418370e-05, 2.75569801e-04, 2.01685811e+02]),
 array([2.42009371e-05, 2.01685811e+02]))

print(res_hnb.summary())
                          Hurdle Regression Results                           
==============================================================================
Dep. Variable:                      y   No. Observations:                50000
Model:                         Hurdle   Df Residuals:                    49996
Method:                           MLE   Df Model:                            0
Date:                Sun, 16 Jan 2022   Pseudo R-squ.:              -1.870e-11
Time:                        09:16:06   Log-Likelihood:                -89206.
converged:               [True, True]   LL-Null:                       -89206.
Covariance Type:            nonrobust   LLR p-value:                       nan
==============================================================================
                 coef    std err          z      P>|z|      [0.025      0.975]
------------------------------------------------------------------------------
zm_const       0.7430      9.614      0.077      0.938     -18.100      19.586
zm_alpha       0.2177     10.453      0.021      0.983     -20.269      20.705
const          0.5005      0.008     59.323      0.000       0.484       0.517
alpha          0.4991      0.015     32.905      0.000       0.469       0.529
==============================================================================

update
Cameron, Trivedi count book doesn't say anything about this.
They mention that Mullahy's original 1986 article proposed using the same family/distribution for zero and count model, and that the common practice nowadays is to use Logit or Probit for the zero model.

Mullahy 1986 only looks at poisson and geometric hurdle with both submodels from the same distribution.
Geometric is negbin with fixed alpha=1, and doesn't have a separate parameter that could be unidentified.

update
for NBP
prob_nz = 1 - (1 + alpha * mu**(p-1))**(- 1 / alpha)

if mu is constant, then we cannot use prob_nz to identify two parameters.

@josef-pkt

josef-pkt commented Jan 16, 2022 •

Copy link
Copy Markdown
Member Author

Even in a model with a continuous exog, [constant, trend], the negbin zero model still has problems, still not well identified.
update I have a mistake in the digp with explanatory variables for creating hurdle data. I used a short cut that is only correct for the constant only model.

@josef-pkt

Copy link
Copy Markdown
Member Author

aside
add some predict which for the prob ratio similar to "zero" in pscl
either p(y = 0 | zero_model) / p(y = 0 | count_model) or the ratio for to complementary probability P(y > 0) = 1 - P(y = 0).

currently I have these two, "prob-main" (1 - "prob-zero") and "prob-trunc" only separately

This gives directly a measure about excess zeros.

@josef-pkt

Copy link
Copy Markdown
Member Author

Given the identification problems in the negbin zero model, the null model will have unidentified parameters, even when the full model does have enough variation.
llnull is still unique, but "LLR p-value" reported in summary will be wrong if theory of LR tests with unidentified nuisance parameters under the null hypothesis applies.

Default null is constant(s) only model. In the Hurdle case, this means no all slope coefficients are zero, but we still have constant zero-modification.

Another "null" model would be no slope effects and no zero-modification. i.e. simple Negbin with constant only.
No problem in that case. Null is identified from full count data.

Another possible case will be with score_test that has constant zero-modification as alternative, eg.
null is no zero-modification null model (single negbin)
alternative hypothesis for score_test, coefficient of constant in zero model differs.
However, there should not be a problem if underlying slope effects are large.
If only the constant coefficient can change, then the other parameters are still identified from the full model.
i.e. we need #8020

@lgtm-com

lgtm-com Bot commented Jan 17, 2022

Copy link
Copy Markdown

This pull request introduces 6 alerts when merging e78dbb0 into 55f9e73 - view on LGTM.com

new alerts:

  • 4 for Unused local variable
  • 2 for First argument to super() is not enclosing class

@josef-pkt

Copy link
Copy Markdown
Member Author

starting with renamings

Hurdle is also too generic if we add it to the statsmodels.api
we likely get other hurdle models besides count hurdles
e.g. there is an R backage for hurdle models with continuous R+ main distribution

I'm renaming model2 in hurdle results to results_count which is not generic, but I guess we won't have much generic code for it to need a more generic name.

Comment thread statsmodels/discrete/truncated_model.py Outdated
else:
counts = np.atleast_2d(np.arange(0, np.max(self.endog)+1))
mu = self.predict(params, exog=exog, exposure=np.exp(exposure),
offset=offset, which="mean-main")[:, None]

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

mu can be computed without calling predict again

Comment thread statsmodels/discrete/truncated_model.py Outdated
offset=offset, which="prob", y_values=counts)[:, None]
return probs
elif which == 'var':
mu = np.exp(linpred)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

add special cases, truncation=0 as in which=mean

@lgtm-com

lgtm-com Bot commented Jan 21, 2022

Copy link
Copy Markdown

This pull request introduces 6 alerts when merging f6fd400 into ad64444 - view on LGTM.com

new alerts:

  • 4 for Unused local variable
  • 2 for First argument to super() is not enclosing class

@josef-pkt

Copy link
Copy Markdown
Member Author

NBP (and GPP) truncated and hurdle models still have a bug with recreating model, parameterization is not an init_key
see comment above #7973 (comment)

hurdle has two, p=2, pzero=2, (which don't apply in poisson case).
I could change to default pzero=None, in which case pzero = p if zero model is NBP (or GPP)

both hurdle and truncated models currently only attach p/parameterization in submodel(s).

Comment thread statsmodels/discrete/truncated_model.py Outdated
mnc2_tregion = (np.arange(self.truncation + 1)**2 *
probs).sum(1)
p = self.model_main.parameterization
vm = mu * (1 + alpha * mu**(p-1))

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is distribution specific -> outsource

Comment thread statsmodels/discrete/truncated_model.py Outdated
mu = np.exp(linpred)
if self.truncation == 0:
p = self.model_main.parameterization
prob_zero = (1 + alpha * mu**(p-1))**(- 1 / alpha)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

prob_zero is now available in base model

Comment thread statsmodels/discrete/truncated_model.py Outdated
mean = (mu - mean_tregion) / (1 - prob_tregion)
mnc2_tregion = (np.arange(self.truncation + 1)**2 *
probs).sum(1)
mnc2 = (mu**2 + mu - mnc2_tregion) / (1 - prob_tregion)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

mu here is poisson variance, distribution specific

@josef-pkt
josef-pkt force-pushed the truncated_model_rebased branch from f6fd400 to 6ad39f0 Compare January 21, 2022 19:04
@josef-pkt

Copy link
Copy Markdown
Member Author

naming inconsistency
truncated: prob-main is pmf expected frequencies if there is no truncation, vector statistic corresponding to y_values
hurdle: prob-main is the probability that the main/count model is selected, i.e. 1 - prob_zero. scalar statistic

The definition in hurdle is in analogy to the zero-inflated model,
The main point in truncated model is that we want to know the underlying distribution if truncation is just a sampling problem, but the distribution of interest is the untruncated distribution.

I guess I need a better name for truncated models. "prob-base" ? referring to the base distribution

@lgtm-com

lgtm-com Bot commented Jan 21, 2022

Copy link
Copy Markdown

This pull request introduces 4 alerts when merging 6ad39f0 into ad64444 - view on LGTM.com

new alerts:

  • 2 for Unused local variable
  • 2 for First argument to super() is not enclosing class

@josef-pkt

Copy link
Copy Markdown
Member Author

merging
I need a short break from this

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