Skip to content

GSOC2017 Generalized Poisson (GP-P) model - #3727

Closed
evgenyzhurko wants to merge 34 commits into
statsmodels:masterfrom
evgenyzhurko:generalized_poisson
Closed

evgenyzhurko wants to merge 34 commits into
statsmodels:masterfrom
evgenyzhurko:generalized_poisson

Conversation

@evgenyzhurko

@evgenyzhurko evgenyzhurko commented May 29, 2017 •

Copy link
Copy Markdown
Contributor

This PR include implementation of Generalized Poisson model
This model include this parts:

  • Log-likelihood function
  • Score
  • Hessian
  • Fit
  • Result
  • Tests
  • Docs

Status - merged #3795

@evgenyzhurko

Copy link
Copy Markdown
Contributor Author

@josef-pkt what is your opinion about p-param as a separate param?
This param might be also done as in the NegativeBinomial model, e.g. 'GP1', 'GP2'.

@coveralls

coveralls commented May 29, 2017 •

Copy link
Copy Markdown

Coverage Status

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

Comment thread statsmodels/discrete/discrete_model.py Outdated
mu = self.predict(params[:-1])
return (np.log(mu) + (endog - 1) * np.log(mu + alpha * np.power(mu, p) * endog) -
np.log(1 + alpha * np.power(mu, p)) - gammaln(endog + 1) -
(mu + alpha * np.power(mu, p) * endog) / (1 + alpha * np.power(mu, p)))

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 useful to create some temporary variables to avoid computing several times the same thing
e.g. alpha * np.power(mu, p) is computed 4 times

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

FWIW It looks like this loglikeobs matches the one here under the change of variables

xi = 1 - 1/(1 + alpha * mu**p)

p here bears a strong resemblance to Q in NegativeBinomial._ll_nbin. Is the relationship more than just aesthetic? Does p take on only a particular set of values?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

@josef-pkt You are right, i'll refactor this part
@jbrockmendel There is no a resemblance(only in names). I don't find some articles where GP use p>2 or p<0. In many articles say only about p=1 as GP-1 and p=2 as GP-2.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The gammaln call is likely to be the slowest part of this function. Since the argument doesn't depend on params, there is some mileage to be gained by caching it.

For that matter, if endog is only taking on positive integer values, then it may be faster to use the $Gamma(n) = (n-1)!$ identity. No idea if scipy implements that internally.

I'll take a look to see if any of this can be useful elsewhere.

Update: I take back the factorial suggestion. Benchmarking it looks like np.log(factorial(x)) is about twice as expensive as gammaln(x)

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.

@jbrockmendel
gammaln is the best function for this kind of computation.
It has one of the best precision and avoids overflow (and is heavily used in scipy.stats.distributions for this reason).
Also, we don't want to restrict to integers. (for quasi-maximum likelihood, endog could be any non-negative number.

About caching intermediate computation that are invariant in the optimization. This is a bit tricky in general and I think we should skip it in the first version of this PR/GSOC.
#3692 (comment)
(If it turns out that it looks relatively easy for a model, then we could try it out later.)

Comment thread statsmodels/discrete/discrete_model.py Outdated
super(GeneralizedPoisson, self).__init__(endog, exog, offset=offset,
exposure=exposure,
missing=missing, **kwargs)
self.p = p - 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.

it's better to store the argument, or change the argument to what is stored.
using the same name, makes it difficult to recreate a model
(we have currently the problem with exposure which is internally stored as log(exposure), which causes some problems

@josef-pkt

josef-pkt commented May 29, 2017 •

Copy link
Copy Markdown
Member

having p in __init__ looks like the appropriate place, all estimation in this class will be for fixed p (at least for the first round)

@jbrockmendel

Copy link
Copy Markdown
Contributor

Is there another reasonable name for p that might be longer? Short names make it tough to do a text search for e.g. "where are all the places in the code that use the variable k"

@evgenyzhurko

evgenyzhurko commented May 30, 2017 •

Copy link
Copy Markdown
Contributor Author

@jbrockmendel What's about p_param or parameterization as name for p?

@jbrockmendel

Copy link
Copy Markdown
Contributor

Either of those work on the name-length front. Ideally the name would also be informative to a reader who isn't familiar with the model (e.g. me). Maybe "overdispersion"?

@josef-pkt

Copy link
Copy Markdown
Member

about naming of p:
I also don't like one letter arguments, or arguments that are not self explanatory. However, I couldn't come up with an alternative suggestion.
Maybe we can settle on something similar to the p power parameter in GLM family tweedie, which we ended up calling var_power.
In the literature it is mostly GP-P or GP(p).

@evgenyzhurko

evgenyzhurko commented May 31, 2017 •

Copy link
Copy Markdown
Contributor Author

I implemented score function and tried to test it using approx_fprime_cs.

res_n = sm.GeneralizedPoisson(data.endog, data.exog, p=1).score(list(res_nm.params) + [0])
print res_n
res_n = approx_fprime_cs(list(res_nm.params) + [0], sm.GeneralizedPoisson(data.endog, data.exog, p=1).loglikeobs)
print res_n.sum(0)

This code gives the following result:

[  15.49534433  103.55903513    1.45694541  -34.25504764]
[ -5.32907052e-15  -3.55271368e-14  -8.88178420e-16  -9.74495236e+00]

I have checked dl/dalpha and dl/dparams many times, but results not equal.
Is it a good way to test score using approx_fprime_cs?

Update: i also tried to compare score from NegativeBinomial(analytic) and score_obs from NegativeBinomial(approx_fprime_cs), but score_obs crashed.

@josef-pkt

Copy link
Copy Markdown
Member

try a simple finite difference approx_fprime instead of the complex-step cs version. I think I remember an scipy issue about gammaln or loggamma for complex variables. For testing or checking any forward difference should be fine, approx_fprime_cs has higher precision when it works.

(Please copy the text from the console and not a picture)

@evgenyzhurko

Copy link
Copy Markdown
Contributor Author

I change approx_fprime_cs to approx_fprime and fit give me bad results:

                    GeneralizedPoisson Regression Results                     
==============================================================================
Dep. Variable:                      y   No. Observations:                   32
Model:             GeneralizedPoisson   Df Residuals:                       29
Method:                           MLE   Df Model:                            2
Date:                Wed, 31 May 2017   Pseudo R-squ.:                   1.000
Time:                        14:43:55   Log-Likelihood:                -163.19
converged:                      False   LL-Null:                   -8.6859e+14
                                        LLR p-value:                     0.000
==============================================================================
                 coef    std err          z      P>|z|      [0.025      0.975]
------------------------------------------------------------------------------
x1             3.0537        nan        nan        nan         nan         nan
x2            -0.4709        nan        nan        nan         nan         nan
x3             1.4259        nan        nan        nan         nan         nan
==============================================================================

@josef-pkt

josef-pkt commented May 31, 2017 •

Copy link
Copy Markdown
Member

a few comments (I just realized that github didn't process my send a while ago, temporary connection problems)

  • you need to push the code, so I can see the code to make a guess
  • most likely there are some overflow issues or boundary values that need clipping
  • the dataset might not be good for the initial development if it runs to easily into numerical problems. A larger sample where the model fits well is better for avoiding numerical problems. (possibly random generated to match the model) convergence warning in one of the results.
  • do you have an extra params in the score list(res_nm.params) + [0] ? is [0] a good value?

@josef-pkt

josef-pkt commented May 31, 2017 •

Copy link
Copy Markdown
Member

another issue (it will be easier when I don't have to guess what you are doing)

  • summary truncates and does not display all parameters in the table if param_names is too short, in this case it uses only the parameters for the regressors. NegativeBinomial should have the pattern how to adjust it.

  • it might be easier to inherit initially from GenericLikelihoodModel. It needs to know the number of parameters, e.g. by providing a start_params in fit, but then it makes some guesses, e.g. for param_names and degrees of freedom, and has extra methods like finite difference score and hessian built-in.

The main pattern is the same so it should be easy to switch back and forth between CountModel and GenericLikelihoodModel.

@coveralls

coveralls commented May 31, 2017 •

Copy link
Copy Markdown

Coverage Status

Coverage decreased (-0.03%) to 90.402% when pulling f8ebd2a on evgenyzhurko:generalized_poisson into ac25464 on statsmodels:master.

@coveralls

coveralls commented Jun 1, 2017 •

Copy link
Copy Markdown

Coverage Status

Coverage decreased (-0.03%) to 90.402% when pulling 3f3e3ba on evgenyzhurko:generalized_poisson into ac25464 on statsmodels:master.

offset = None
mod_poi = NegativeBinomial(self.endog, self.exog, offset=offset)
start_params = mod_poi.fit(disp=0).params
start_params = np.append(start_params, 0.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.

Does this still need the extra parameter 0.1?
AFAIU, we already have an extra params in NegativeBinomial, and for fixed p we also have only one extra params in Generalized Poisson.

@evgenyzhurko evgenyzhurko Jun 1, 2017 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

It's my mistake. I'll generate start_params using Poisson model. In case NegativeBinomial extra parameter 0.1 doesn't need.
Update: I'll change NegativeBinomial to Poisson in the next commit.

@evgenyzhurko

evgenyzhurko commented Jun 1, 2017 •

Copy link
Copy Markdown
Contributor Author

I tested following code and got results:

data = sm.datasets.strikes.load()

res_p = sm.Poisson(data.endog, data.exog).fit()
print res_p.summary()

res_nb = sm.NegativeBinomial(data.endog, data.exog).fit()
print res_nb.summary()

res_gp = sm.GeneralizedPoisson(data.endog, data.exog).fit()
print res_gp.summary()

Optimization terminated successfully.
         Current function value: 134.265999
         Iterations 15
                          Poisson Regression Results                          
==============================================================================
Dep. Variable:                      y   No. Observations:                   62
Model:                        Poisson   Df Residuals:                       61
Method:                           MLE   Df Model:                            0
Date:                Thu, 01 Jun 2017   Pseudo R-squ.:                  -4.759
Time:                        20:57:15   Log-Likelihood:                -8324.5
converged:                       True   LL-Null:                       -1445.5
                                        LLR p-value:                       nan
==============================================================================
                 coef    std err          z      P>|z|      [0.025      0.975]
------------------------------------------------------------------------------
x1           -39.2645      0.821    -47.831      0.000     -40.873     -37.656
==============================================================================
Optimization terminated successfully.
         Current function value: 7.831327
         Iterations: 25
         Function evaluations: 27
         Gradient evaluations: 27
/usr/local/lib/python2.7/dist-packages/statsmodels-0.8.0-py2.7-linux-x86_64.egg/statsmodels/base/model.py:504: ConvergenceWarning: Maximum Likelihood optimization failed to converge. Check mle_retvals
  "Check mle_retvals", ConvergenceWarning)
                     NegativeBinomial Regression Results                      
==============================================================================
Dep. Variable:                      y   No. Observations:                   62
Model:               NegativeBinomial   Df Residuals:                       61
Method:                           MLE   Df Model:                            0
Date:                Thu, 01 Jun 2017   Pseudo R-squ.:                 -0.6442
Time:                        20:57:15   Log-Likelihood:                -485.54
converged:                       True   LL-Null:                       -295.30
                                        LLR p-value:                       nan
==============================================================================
                 coef    std err          z      P>|z|      [0.025      0.975]
------------------------------------------------------------------------------
x1            -3.5935      2.982     -1.205      0.228      -9.438       2.251
alpha         40.3251      5.248      7.684      0.000      30.039      50.611
==============================================================================
Warning: Desired error not necessarily achieved due to precision loss.
         Current function value: 12.953166
         Iterations: 1
         Function evaluations: 106
         Gradient evaluations: 94
/usr/local/lib/python2.7/dist-packages/statsmodels-0.8.0-py2.7-linux-x86_64.egg/statsmodels/base/model.py:504: ConvergenceWarning: Maximum Likelihood optimization failed to converge. Check mle_retvals
  "Check mle_retvals", ConvergenceWarning)
/usr/local/lib/python2.7/dist-packages/statsmodels-0.8.0-py2.7-linux-x86_64.egg/statsmodels/base/model.py:504: ConvergenceWarning: Maximum Likelihood optimization failed to converge. Check mle_retvals
  "Check mle_retvals", ConvergenceWarning)
                    GeneralizedPoisson Regression Results                     
==============================================================================
Dep. Variable:                      y   No. Observations:                   62
Model:             GeneralizedPoisson   Df Residuals:                       61
Method:                           MLE   Df Model:                            0
Date:                Thu, 01 Jun 2017   Pseudo R-squ.:                  0.9902
Time:                        20:57:15   Log-Likelihood:                -540.68
converged:                      False   LL-Null:                       -54974.
                                        LLR p-value:                       nan
==============================================================================
                 coef    std err          z      P>|z|      [0.025      0.975]
------------------------------------------------------------------------------
x1           -39.2628      1.477    -26.586      0.000     -42.157     -36.368
==============================================================================
[Finished in 0.8s]

Is it normally that i got different results in Poisson/GP-p and NB.
About strikes dataset, i tested all datasets from datasets folder and only this dataset doesn't raise error RuntimeWarning: invalid value encountered in log.

@josef-pkt

Copy link
Copy Markdown
Member

If it's a dataset where convergence is difficcult, it is better to start with Nelder-Mead optimization first.

Also, you should include a constant in general, otherwise the model might be strongly misspecified

import numpy as np
import statsmodels.api as sm

data = sm.datasets.strikes.load()
exog = sm.add_constant(data.exog)

res_p = sm.Poisson(data.endog, exog).fit(method='nm', maxiter=1000)
print(res_p.summary())

res_nb = sm.NegativeBinomial(data.endog, exog).fit(method='nm', maxiter=1000)
print(res_nb.summary())

as a check whether the convergence makes sense:
If there is a constant included, then the mean prediction in Poisson is equal to the mean of endog.
NegativeBinomial and Generalized Poisson should be close.

>>> data.endog.mean()
42.661290322580648

>>> res_p.predict().mean()
42.661383469654041
>>> res_nb.predict().mean()
43.334451380296287

@evgenyzhurko

evgenyzhurko commented Jun 1, 2017 •

Copy link
Copy Markdown
Contributor Author

I tried different optimization, as a result nm, lbfgs and powell says that converged=True.

@josef-pkt

Copy link
Copy Markdown
Member

You need to add these two lines

            self.exog_names.append('alpha')
            self.k_extra = 1

https://github.com/statsmodels/statsmodels/blob/master/statsmodels/discrete/discrete_model.py#L1956
then your summary should also show alpha
The k_extra attribute is for some generic, inherited methods, I don't remember which.

@coveralls

coveralls commented Jun 1, 2017 •

Copy link
Copy Markdown

Coverage Status

Coverage decreased (-0.04%) to 90.399% when pulling 0000dac on evgenyzhurko:generalized_poisson into ac25464 on statsmodels:master.

@josef-pkt

Copy link
Copy Markdown
Member

Is it normally that i got different results in Poisson/GP-p and NB.
I tried different optimization, as a result nm, lbfgs and powell says that converged=True.

In general the parameters and prediction of the three models should be close to each other because they all have expected E(y |x) = exp( exog * params). If they are not close, then either the model is strongly misspecified or there is a bug.

@evgenyzhurko

Copy link
Copy Markdown
Contributor Author

@josef-pkt nm optimization gives well results for mean:

Endog:  42.6612903226
Poisson:  42.6613834697
NB2:  43.334475458
GP-p:  42.6611700783

but result for bsfg too bad:

Endog:  42.6612903226
Poisson:  42.6612883405
NB2:  43.3343371656
GP-p:  1.18863607791e+19

Is the analytic hessian can help to solve this problem?

@josef-pkt

Copy link
Copy Markdown
Member

I would leave convergence problems for later, when the basic model is ok.
What you can do (and I often do) is to use initially method='nm' to get close to the optimum, and then switch to newton (or bfgs) using the nm start_params. (I use this also in unit tests, when I'm just interested in results and not convergence issues.)

newton is good to improve the estimate in the neighborhood of the optimum. It uses score and hessian, and if newton works locally, then it is a good indicator that score and hessian are fine.

@evgenyzhurko

evgenyzhurko commented Jun 1, 2017 •

Copy link
Copy Markdown
Contributor Author

I tried to change method on Poisson model(in generating start_params) to same method as for GP-p, following code instead of https://github.com/evgenyzhurko/statsmodels/blob/0000dac068153d108bdd8e3a55e6786ac07a4af5/statsmodels/discrete/discrete_model.py#L1263

mod_poi = Poisson(self.endog, self.exog, offset=offset)
start_params = mod_poi.fit(disp=0, method=method).params

This way gives well result with all optimization method except newton(result is nan): good value of llf and close predict().mean() to endog. But in some case mean close to endog and converged=False.

@coveralls

coveralls commented Jun 26, 2017 •

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.07%) to 90.508% when pulling 67ec4ee on evgenyzhurko:generalized_poisson into ac25464 on statsmodels:master.

@josef-pkt

Copy link
Copy Markdown
Member

I found the problem with under dispersed test, which was in rvs for genpoisson and not in the Generalized Poisson model.

I will check tonight what we need for finalizing and merging the PR. I will likely make a PR against this branch. test coverage is low in a few places.

@coveralls

coveralls commented Jun 27, 2017 •

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.1%) to 90.54% when pulling 3af442e on evgenyzhurko:generalized_poisson into ac25464 on statsmodels:master.

@josef-pkt

Copy link
Copy Markdown
Member

you should have waited until I rebased my branch. There might be some duplicate commits now in your branch. (I need to check the branch/network tree to see.)

@coveralls

coveralls commented Jun 28, 2017 •

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.1%) to 90.583% when pulling bffb538 on evgenyzhurko:generalized_poisson into ac25464 on statsmodels:master.

@evgenyzhurko

Copy link
Copy Markdown
Contributor Author

@josef-pkt I can reset this merge if it's will require.

@sj

sj commented Jun 28, 2017

Copy link
Copy Markdown

@josef-pkt @evgenyzhurko: I just noticed that the lgtm.com prcheck reports that this PR introduces 7 new alerts. I've had a quick look — they're all true positives (I think), and at least two seem to indicate potential bugs. Some others are related to cyclic dependencies.

Details here: https://lgtm.com/projects/g/statsmodels/statsmodels/rev/pr-c8657bd5621ec3ed538650d0d05ce1fccdfae0c3

@josef-pkt

Copy link
Copy Markdown
Member

@evgenyzhurko Don't change anything right now. I will look again into merging in an hour or so. (I just merged VECM)

@josef-pkt

Copy link
Copy Markdown
Member

@sjvs I think these are general design issues or problems and not specific to this PR, and are not bugs. This PR follows mostly the pattern of the existing discrete models.

about circular imports: I saw these LGTM warnings for several cases in master and other PRs. I don't think we had actual problems with this, because api's are not imported by regular code, and AFAIK we don't have circular imports.
(alpha==alpha) that's an easy trick to include it in broadcasting, even though it does a redundant comparison.
In the super call we jump over CountModel, I'm not sure I remember, but I think we want to skip the wrapper that is in CountModel.fit

@sj

sj commented Jun 28, 2017

Copy link
Copy Markdown

@josef-pkt: thanks for confirming! To a noob like me they looked like relevant warnings (especially line 1354 of discrete_model.py about CountModel), but if you've checked them and are happy: 👍

Functionality for disabling queries to suppress certain types of alerts is coming to lgtm.com soon — that may be useful for disabling the circular imports warnings.

@josef-pkt

Copy link
Copy Markdown
Member

@sjvs specific end of line comments to disable some checks would be useful, like pylint.
for example using the wrong class in the super call is not an uncommon mistake, but in discrete it is part of the current design, so that should at most be selectively disabled.

@josef-pkt

Copy link
Copy Markdown
Member

@evgenyzhurko I think we should rebase and open a new PR for merging, and leave this PR alone to have a full reference to the development.
Based on browsing the commit history, I think it would look better squashing some of the earlier commits, e.g. a sequence of loglike commits that use several commits to correct mistakes, and the same for a sequence of score commits.
I don't quite understand the commit and merge pattern in the last few commits, but it looks ok, and will change a bit after rebasing the entire branch.

If you know how to do an interactive rebase, then you could open the new PR with partial squashing and rebased on master. Otherwise, I'll do it later today.

@sj

sj commented Jun 28, 2017

Copy link
Copy Markdown

@josef-pkt: it's on the roadmap for the next couple of months!

@josef-pkt josef-pkt closed this in b8058bc Jun 28, 2017
@josef-pkt

Copy link
Copy Markdown
Member

merged rebased version of this in #3795

@evgenyzhurko evgenyzhurko changed the title Added llf for Generalized Poisson model GSOC2017 Added llf for Generalized Poisson model Aug 29, 2017
@evgenyzhurko evgenyzhurko changed the title GSOC2017 Added llf for Generalized Poisson model GSOC2017 Generalized Poisson (GP-P) model Aug 29, 2017
@josef-pkt josef-pkt mentioned this pull request Apr 15, 2018
@bashtage bashtage added the rejected Used for PRs with changes that are not acceptable label Jul 27, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

rejected Used for PRs with changes that are not acceptable

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants