Skip to content

beta-regression - #2030

Closed
brentp wants to merge 18 commits into
statsmodels:masterfrom
brentp:betareg
Closed

brentp wants to merge 18 commits into
statsmodels:masterfrom
brentp:betareg

Conversation

@brentp

@brentp brentp commented Oct 6, 2014

Copy link
Copy Markdown
Contributor

This is an initial go at adding beta-regression starting from GenericLikelihoodModel for feedback.

Here is the mailing list discussion: https://groups.google.com/forum/#!topic/pystatsmodels/3qEp-0YpEIc
and gist: https://gist.github.com/brentp/089c7d6d69d78d26437f

Josef suggested adding analytical derivatives and moving out of miscmodels. I will require some hand-holding to implement that so I have left it in miscmodels for now.

Currently, it has a separate link for the precision parameter (a + b == phi), but the results are reported in the context of the link for the X covariates. I'm not sure how to separate them out in the summary()

The Z matrix for modeling the precision currently must be specified as a matrix. Perhaps it makes sense to allow a z_formula to the from_formula method.

I put the csv data for the tests in the miscmodels/tests directory.

The paper for R's betareg includes methods for bias-correction and bias-reduction, which I would like to implement eventually.

Comment thread statsmodels/miscmodels/betareg.py Outdated

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.

Z should be renamed into an exog_xxx
link_phi to link_xxx where xxx is not greek.

is phi dispersion or precision ?

@josef-pkt

Copy link
Copy Markdown
Member

phi is precision (should correspond to the sample size in simple beta posterior IIRC)

I don't see any real problems right now, this seems to be working fine.

My guess is that the TravisCI failures are bfgs related. I don't see a common pattern across failing tests yet, but I had problems with bfgs on TravisCI before.
All tests pass for me on python 2.7 on Windows 32 (I'm currently using scipy 0.13.3).

If the score and hessian, first and second derivatives of loglike, are available, then it would be useful to get them.

In general: We need better multi-equation or multi-parameter support in statsmodels, to handle second exog like Z here better in a generic way so we don't have to code everything into the specific models.
(This will be a separate issue.)
Currently the most advance example is MixedLM, IIRC. There will be many more models with two part exog or two part formulas.

for example:
from_formula should be able to take a second formula instead of a exog_xxx array.
In summary it should be possible to add a line separator and header for the second part of the model (similar to Multinomial Logit)

extra_params is specific to GenericLikelihoodModel, but Skipper recently separated param_names from exog_names.

@josef-pkt

Copy link
Copy Markdown
Member

I'm briefly browsing some articles that I downloaded some time ago.

Improved likelihood inference in beta regression
Silvia L.P. Ferrari, Eliane C. Pinheiro
Journal of Statistical Computation and Simulation
Vol. 81, Iss. 4, 2011

seems to have the score.
I didn't see score or hessian in the article that introduced phi as a function of explanatory variables
Smithson, M. and Verkuilen, J. 2006. A better lemon squeezer? Maximum likelihood regression with
beta-distributed dependent variables. Psychological Methods 11(1): 54-71.

http://www.ime.usp.br/~sferrari/13EMRslidesSilvia.pdf are slides with a large list of references for extensions to the simple beta regression and extensions.

@josef-pkt

Copy link
Copy Markdown
Member

I think we can stay with GenericLikelihoodModel for now. I'm not sure yet how it will fit in the class hierarchy, except for the top level LikelihoodModel.

Some things for extending the usage of the model:

a predict method: this should return the expected proportion/endog given the exogs. In this case the prediction is not directly used in the model definition, and the superclasses don't know whether there is a prediction relationship in the model.
If possible we should get a similar function for the estimated variance of endog (based on the estimated mu and phi)
The article "Improved likelihood inference in beta regression" has the expressions for E(y) and var(y) AFAICS, before equation (4).
Except looking closer they are for y_star which is the logit transformed endog.
(??? needs more checking)

related to predict: the parameterization is not the one of the standard beta distribution. We need a helper function or method that returns the alpha, beta parameterization (so we can use it with scipy.stats.distributions for example). Related: In the multiple imputation PR, we also add a method get_distribution to get the scipy.stats distribution directly.
(This is not yet available in master for GLM and discrete models. We have an open issue where I wrote the transformation for the parameterization of the NegativeBinomial.)

Eventually we will also need additional results attributes that we have for GLM and discrete models. For example different kinds of residuals that can be used for further inference or diagnostics.
(I haven't read anything about this for the beta regression yet.)

@josef-pkt

Copy link
Copy Markdown
Member

about the score:

"Improved likelihood inference in beta regression" equations (4) and (5):
these are dot products with the exogs, X and Z.
The part of the equations with the exogs is a two column score_factor (that's how I called it in my extenstions to GLM, and it should be added to all models that have a multiplicative score. In GLM score_factor is 1-D because we only have one estimated parameter.)
(Having this available will make it easy to add score_tests for it.)

@josef-pkt

Copy link
Copy Markdown
Member

@brentp
I don't want to sound like there is an overwhelming amount of work to do in this PR.
The parameter estimation and the associated inference all work already.

The extra work is to create a new model group for an additional data type similar to binary and count data in GLM and discrete, and to handle the two parameter/two exog structure.

@brentp

brentp commented Oct 9, 2014

Copy link
Copy Markdown
Contributor Author

@josef-pkt no problem. I'm happy for the feedback. I'll have to go through your comments in more detail as I have time. Here's a start of the list:

  • rename phi variables to precision
  • fix failures on python2.6, python3.3 (bfgs: maybe solved with initialization params)
  • add separator for precision summary and report precision parameters under their own link
  • add score() method referring to Improved likelihood inference in beta regression
  • add hessian() method
  • predict method and var
  • helper to get alpha, beta from precision
  • from_formula to take precision_formula

@brentp

brentp commented Oct 9, 2014

Copy link
Copy Markdown
Contributor Author

@josef-pkt

Copy link
Copy Markdown
Member

This also show the score function:
http://www.ime.usp.br/~sferrari/13EMRslidesSilvia.pdf

The score function on slide 11 is for constant phi. We still need the
additional part for the derivative of phi with respect to the
exog_precision parameters.

@josef-pkt

Copy link
Copy Markdown
Member

I just updated to the latest version and optimization doesn't work anymore because of the incorrect score.

Debugging tip:
I renamed the new score method to score_ so that score still is the inherited finite difference score.

>>> mod.score(rslt.params)
array([ -1.02195101e-05,  -3.11958241e-04,  -8.17873460e-05,
        -2.96286158e-06])
>>> mod.score_(rslt.params)
array([  1013.64971085,  57170.46660391,   3771.96802048, -45122.76520892])

in general: diagonal matrices in formulas/calculations can often be replaced by elementwise multiplication with a column array (shape (nobs, 1)).
However, its sometimes easier to stick with the diag version until debugging is finished so it's easier to compare with the written formula.

@josef-pkt

Copy link
Copy Markdown
Member

special functions:

the math psi in the expression for mu_star is the digamma function http://docs.scipy.org/doc/scipy-0.7.x/reference/generated/scipy.special.psi.html#scipy.special.psi which is the derivative of the gamma function.

The hessian requires the trigamma function psi-prime, which (after a google search) is available with the polygamma function
trigamma = lambda x: scipy.special.polygamma(1, x)

(too much greek)

@josef-pkt

Copy link
Copy Markdown
Member

FYI: I'm debugging score right now. I got the first part of the derivative working.

@brentp

brentp commented Oct 10, 2014

Copy link
Copy Markdown
Contributor Author

thanks. it's all greek to me.

you had suggested to add a function to pull out the a, b parameters for the Beta, what would the signature of that be?

def beta_params(self, params):
    ...
   return a, b

?

I'll add precision_formula kwarg to from_formula since that should be pretty simple.

@josef-pkt

Copy link
Copy Markdown
Member

As reference, the latest version for parameter tests in Beta regression
http://www.tandfonline.com/doi/abs/10.1080/00949655.2012.700456

(I didn't read yet. According to abstract score test and bootstrap are best in small samples)

@josef-pkt

Copy link
Copy Markdown
Member

def beta_params(self, params):

I think it should have the same signature as predict and include the two exog as keyword parameters, and use self.exog if the arguments are None.

@brentp

brentp commented Oct 10, 2014

Copy link
Copy Markdown
Contributor Author

http://supp.apa.org/psycarticles/supplemental/met_11_1_54/met_smithson1631_supplementalmaterial.doc
suggests using:

mu = eps + (1 - 2 * eps) * mu
phi = eps + (1 - eps) * phi

"to gently bound the predicted values away from 0 or 1 for mu, and 0 for phi."

@josef-pkt

Copy link
Copy Markdown
Member

two things:

start_params and convergence: I'm getting a non convergence warning in the last score test, with log-link, but the test doesn't fail (score is very large but both methods agree)
I saw the TODO comment in the source. trying out some simple changes to the start_params for the precision parameters didn't help.
In some models we started to use separate methods for start_params that we could do also here. Cases where the start_params require more work.

As alternative nm converges even with log link, and we need to do some preliminary estimation with nm and then switch to bfgs or newton. (we are planning on that pattern but haven't used it yet.)

unit tests:
I think we should rewrite the unit tests to our usual pattern with test classes. Currently every function estimates the model and there is a lot of redundant estimation. Also yield tests are not nice for debugging.

@josef-pkt

Copy link
Copy Markdown
Member

"to gently bound the predicted values away from 0 or 1 for mu, and 0 for phi."

there will still be some work todo for the 0, 1 boundaries. We will also need to check the data, endog. I saw another example/tutorial where they moved extreme observations into the interior, 1 - 'a small number'
In GLM and discrete we are np.clipping in similar cases. I don't know whether there is an advantage to the transformation that they propose.

In general, there might be something "fishy" if there are exact 0s and 1s in the data or prediction, and we might have to warn the user. I didn't look at anything related yet, but for Stata there is a user contributed package for zero and one inflated beta.

@josef-pkt

Copy link
Copy Markdown
Member

to add to previous comment:
you could use the transformation that they use, but add a comment in the code as a reminder
# TODO: check boundary issues

@josef-pkt

Copy link
Copy Markdown
Member

I got the hessian and hessian factors and will push them later.

@josef-pkt

Copy link
Copy Markdown
Member

comment to hessian
the observed information matrix, hessian agrees at around rtol=2e-6 except for the zeros with the numerical hessian
The expected information matrix differs a lot for some values (almost 100% for correlation, off diagonal blocks) bug or feature (my guess is feature since expected uses a subset of the calculations of observed. It looks too large and would could have a large impact on parameter inference)

@jseabold

Copy link
Copy Markdown
Member

It looks like maybe you merged master (at some point) in to this branch? Let me know if you need help sorting it out.

@brentp

brentp commented Nov 24, 2014

Copy link
Copy Markdown
Contributor Author

Yes, how can I fix this?

On Fri, Nov 21, 2014 at 12:25 PM, Skipper Seabold [email protected]
wrote:

It looks like maybe you merged master (at some point) in to this branch?
Let me know if you need help sorting it out.

—
Reply to this email directly or view it on GitHub
#2030 (comment)
.

@jseabold

Copy link
Copy Markdown
Member

Hmm. This is going to be tricky. The history doesn't make too much sense to me at a few points. It looks like you may have done a non-fast-forward merge on this branch at some point? Are you working across different machines?

Anyway, there are a few different ways to get back to a reasonable history I think, depending on your git-fu. The most manual way to do it where it's going to be mostly obvious what's going on is just to cherry-pick the commits you want to a new branch. First get your master up to date

git checkout master
git remote add upstream https://github.com/statsmodels/statsmodels.git
git fetch upstream
git merge --ff-only upstream/master

Now make a new branch.

git checkout -b betareg-tmp

From here you can see what commits are in betareg that aren't in current master.

git log --oneline betareg ^master

Now you'll just cherry-pick these by hand over to your betareg-tmp branch. You can also skip some commits, if you want. For example, it looks like there is a duplicate commit with the message betaregression. It's not really clear to me what happened there or what that merge is from. You can pull in the new commits to betareg-tmp by first making sure you're on that branch and then cherry-picking.

git checkout betareg-tmp
git cherry-pick 4567b9e

Then you just need to do that for each one you want. After that, you might push betareg-tmp to github and look at it, make sure the history looks right, etc. Then you can either make a new PR or delete your existing betareg branch, rename betareg-tmp to betareg and force push it. That will update this PR, but be careful with deleting the branch force pushing and make absolutely sure, you've got everything you want.

@josef-pkt

Copy link
Copy Markdown
Member

I like interactive rebase, which does essentially the same as cherry picking but git is doing most of the work, just removing lines with commits that we don't want.

@jseabold

Copy link
Copy Markdown
Member

Interactive rebase is an option. I tried both (and a hard rebase, fixing
the odd merge conflicts from the circular history). Given the volume of
commits merged from master and the circular history bit it was a bit
difficult to find the start for the interactive rebase and figure out what
needs to stay for what doesn't, so I thought the offline cherry-picking may
be a little less daunting.

@josef-pkt

Copy link
Copy Markdown
Member

I added a few more things in my branch. I will look at it a bit more tonight or tomorrow.

@yoavram

yoavram commented Jan 30, 2018

Copy link
Copy Markdown

Hi, I've used the gist and it works well, I'm interested in seeing this PR merged, is it still alive?

@josef-pkt

Copy link
Copy Markdown
Member

@yoavram It's stalled, and on the "need to come back to this" waiting list.
I don't remember why this stalled (I often have to get busy with other things and might forget)

master...josef-pkt:betareg_2030_3
has several more commits. It looks like I was trying to improve convergence and add some missing pieces.

It will need updating to current master. AFAIR, there were some ideas in here and in related work that have in the meantime been implemented in a more general way or for other cases.
(Plus I have three additional years of experience with convergence failures, and scipy optimizers have changed.)

@yoavram

yoavram commented Jan 31, 2018

Copy link
Copy Markdown

Ok makes sense. I’ll use this gist in the meantime.

@josef-pkt josef-pkt mentioned this pull request Jan 31, 2018
@josef-pkt

Copy link
Copy Markdown
Member

I rebased my branch of this and opened #4238

From a very brief look at a commented out test failure, I think it either needs more work on optimization, or, maybe better, needs a "nicer" testcase that doesn't use identity link.

@yoavram

yoavram commented Jan 31, 2018

Copy link
Copy Markdown

I think I can provide a test case using simulated data which uses logit link, would that be helpful?

@josef-pkt

Copy link
Copy Markdown
Member

@yoavram Yes, that would be helpful.
We need one "nice" test case verified against R or Stata or some other package that shows that the results are correct and pass across versions of scipy and numpy.
"not nice" cases are much more difficult, in GLM we warn now when a link is used that does not constrain the estimator to remain in the support of the distribution parameters or predictions. Some family-link combinations that don't force the support still don't converge in many cases.
Another problem is that bfgs and other scipy optimizers have changed across scipy versions and are not robust in all versions.

@mvogelsang

Copy link
Copy Markdown

just checking in to say that myself and plenty of people I know would be immensely grateful for a proper beta regression implementation to be available as part of a proper python package! AFAIK there literally isn't one anywhere else.
I've been using that gist, but it would be fantastic to see this get merged.

@josef-pkt

Copy link
Copy Markdown
Member

looks like a problem from the renaming, this should not be closed

dead because the original branch doesn't exist anymore

@bashtage

bashtage commented Mar 26, 2021 via email

Copy link
Copy Markdown
Member

@josef-pkt

Copy link
Copy Markdown
Member

I have them in my local clone, I just checked 2030 and I can create a branch from it.
I fetched all pr branches

@josef-pkt

Copy link
Copy Markdown
Member

This is the only branch that was affected based on the list of recently updated, closed branches

@Edwardp17

Copy link
Copy Markdown

Hi, just wondering if this is still open? I'm very interested in seeing this in the statsmodels library, it would be immensely useful

@josef-pkt

Copy link
Copy Markdown
Member

Still open. One of my favorite examples for planning and designing more general models, but I haven't done any work on that yet.

@Edwardp17

Edwardp17 commented May 11, 2021 •

Copy link
Copy Markdown

@josef-pkt wonderful, thank you for the response! I have been having some issues relating to a "HessianInversionWarning" with the gist, so I'm very excited for a more stable option - would there happen to be any active branches that are more updated?

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.

7 participants