Skip to content

MixedGLM Likelihood Inference #2464

Open

Description

@gjhunt

I'm posting this issue as a place to discuss and think about our strategy for likelihood-based inference for generalized linear mixed models. Right now I've got a working likelihood function for a MixedGLM class on this branch on my statsmodels fork.

Firstly a suite of tests needs to be written to test this likliehood function. Preliminary tests seem to agree with R, however.

We will need to implement a score function for the likelihood. Right now we are using Laplace approximation to calculate the integrals for the likelihood function. We'll have to think whether or not we can use the same laplace approximation for the score. If these integrals don't fit the form of the laplace approximation then do we need to use some more complicated quadrature or do we go to numerical derivatives. In the former case -- if we are going to implement something more complicated than Laplace -- then we probably should re-write the log-likelihood so that it uses this method too. The seemingly popular choice is Gauss-Hermite. Some investigation into R needs to be done to determine how they do this.

Another issue we'll have to think about is efficiency. We should start thinking about timing the runtime for various methods. This will probably come especially into play when we start trying to get the MLEs for the various parameters. However a couple of kinks need to be worked out before we can do this. Along these lines are refactoring the code currently which is probably a bit more human-readable than time efficient.

Associated with the MLEs is that we need to determine how to deal with the scale parameter of the overdispersed exponential family. Currently we are just treating these as fixed. Its not clear what precisely glmer in R is doing but it seems like they are trying to do some sort of profiling out of sigma. Although its not clear that anyone currently knows how to deal with the scale parameter. glmer github issue

Activity

  1. josef-pkt commented on Jun 23, 2015

    @josef-pkt
    Member

    Thanks @gjhunt

    I think starting to add unit tests is the most important item to do soon, once the basic models are running. Then you can also open a PR, which will trigger the TravisCI test run and it will be easier to comment on the code directly.

    To make trying out and reviewing the code easier, it would also be helpful to have ready made examples. You could add it or them to the internal examples directory, so it's easier to keep them up to date. A notebook in a gist would, of course, also be helpful for this.

    I don't understand what the problem with the scale is:
    For Poisson and Binomial we don't support yet over or underdispersion. (QMLE is only in the cov_type).
    For models that require a scale different from 1, we have to estimate it as part of the fit. The current GLM takes it as a separate estimate during fit from the family (scale is treated as a "nuisance parameter").
    Is the option in Mixed to estimate the scale as one of the parameters in the optimization, or alternatively use an auxiliary estimate as in the current non-mixed version?

  2. added this to the 0.8 milestone on Jun 23, 2015
  3. josef-pkt commented on Jun 23, 2015

    @josef-pkt
    Member

    to the scale estimate
    The lme4/glmer github issue sounds like they use the auxiliary estimate, "Pearson-method-of-moments", instead of estimating it as part of the optimization parameters.

  4. kshedden commented on Jun 23, 2015

    @kshedden
    Contributor

    The issue with the scale I believe is that in MixedGLM the parameter estimates depend on the scale. In contrast, in GLM, the parameter estimates don't depend at all on the scale. So in GLM, you can estimate the parameters without worrying about the scale, then estimate the scale, then update your standard errors to account for the scale (but no need to update the parameter estimates). This is a non-iterative process. In contrast, for MixedGLM you fit the model once, estimate the scale, then go back and refit the model with the new scale estimate, and potentially iterate this process. These iterations might not even be convergent.

  5. gjhunt commented on Jun 23, 2015

    @gjhunt
    Author

    The scale thing probably isn't a huge issue given the present state of MixedGLM. I believe that glmer just fixes the scale at 1 for binomial and poisson so we can do that presently for our implementation. Anyways poisson and binomial are probably some of the more important use-cases for glmm.

    I believe that glmer uses some method of moments estimator based on the residuals to estimate the scale. E.g. for negative binomial they do something like estimate the fe_params, cov_re, calculate the residuals and use this for the MoM estimator. They then repeat this process once i.e. they re-estimate the parameters using the updated scale. Or something to this effect. I haven't looked enough into the code to know exactly how they are handling this for the rest of the cases but I think it something similar.

  6. josef-pkt commented on Jun 23, 2015

    @josef-pkt
    Member

    In IRLS, we update the scale during the iteration (even if it isn't really necessary)
    self.scale = self.estimate_scale(mu)
    AFAICS, this corresponds to profiling out the scale which is replaced by the Pearson residual estimate or based on deviance residuals.

    NegativeBinomial is a bit different, because we keep the dispersion parameter fixed throughout, AFAIK, I just opened #2465 to make it easy to update the NegativeBinomial parameter.

  7. kshedden commented on Jul 4, 2015

    @kshedden
    Contributor

    I realized something I think is interesting regarding the connection between the Laplace approximations that Greg is using for MixedGLM and the penalized likelihood formulation of mixed linear models. We have noted regarding MixedLM that Doug Bates has presented a marginal likelihood and a penalized likelihood version of the model. In MixedLM, we are using the marginal likelihood, but Bates now prefers the penalized likelihood approach. I'm not in a hurry to go back and refactor the MixedLM code (and not sure that this would even be advantageous for us), but luckily I think it turns out that the Laplace approximation, in the special case of a Gaussian GLM, gives you the penalized likelihood. So we will get the penalized likelihood Mixed Linear Model for free as part of Greg's work here.

    The Laplace approximation has an auxiliary optimization that is currently handled by BFGS in Greg's code. In the Gaussian case this auxiliary optimization can be solved in closed form. No need to implement this now, but eventually we should.

  8. kshedden commented on Jul 4, 2015

    @kshedden
    Contributor

    I believe Greg is still working on the MixedGLM likelihood, but the plan was to move to derivatives next. Given that the LMER people seem to be using derivative-free methods I'm not sure we want to do this. Implementing the derivative (and Hessian) calculations in MixedLM has been a huge undertaking and they are also fairly slow in interpreted Python due to the nested loops and many temporaries.

    Unfortunately the only derivative-free optimizer in scipy is Nelder-Mead, which is quite inefficient. Using numerical derivatives with gradient-based optimizers is also not very efficient. The near state of the art I understand for derivative free optimization of unconstrainted smooth functions is Powell's NEWUOA. His code is ambiguously licensed so we can't just copy it, but I'm thinking of doing a fresh implementation based on his tech report.

    http://www.damtp.cam.ac.uk/user/na/NA_papers/NA2004_08.pdf

    So I think Greg's time on the GSOC is better spend pinning down the likelihood rather than implementing derivatives.

  9. josef-pkt commented on Jul 4, 2015

    @josef-pkt
    Member

    In my experience with other models, derivative and even hessian free methods are numerically not very accurate (if the likelihood function is relatively flat). In many cases the accuracy of the final estimates improves if we add a few refinement steps at the end of the optimization with optimizers that use accurate derivatives and hessians.
    Also, in most cases derivative free methods need a large number of iterations, and using approximate derivatives (or hessian) converges usually in a shorter time.

    I'm not sure how this works out here, given that we have a larger numerical error already through the approximation of the integration.

    I would suggest to avoid getting stuck in numerical details in the first round and try to get a "working" solution and the associated unit tests, and leave analytical derivatives for later once we see that we might need them. (From what I read about analytical derivatives in similar GLM/discrete mixed models, those are pretty expensive and might be better approximated by, for example, complex step derivatives.

  10. gjhunt commented on Jul 4, 2015

    @gjhunt
    Author

    So I'm still primarily working on getting some unit tests in place for the loglike function etc. Since Laplace's approximation uses the maximum of the exponentiated function we calculate its derivative and pass it to scipy.optimize. We have a unit test to test this analytic derivative against some numerically found derivative. This was failing. After staring at it for a couple of days and working out some examples I realized that the numeric derivatives were wrong (although not always horribly so). So I'm a little more wary of numerical derivatives than I was previously. They seem very dependent on epsilon size. That said, I like the motto "fake it until you make it." If we can get away with numerical derivatives then that should be our first implementation. I don't know which is faster (I assume analytic is more accurate) but I do know which is easier to implement.

    Since I'm fairly certain our loglike function is correctly implemented I wanted to see if I could get it to give me the MLEs for our parameters. I spent a day or two hacking around and I've pushed a really hack-y fit function to my glmm branch of my fork:

    https://github.com/gjhunt/statsmodels/blob/glmm/statsmodels/regression/mixed_glm.py#L1617

    Its very simple and just uses scipy.optimize using Nelder-Mead. Here's an example in python:

    https://github.com/gjhunt/statsmodels/blob/glmm/statsmodels/regression/scrap/testll/glmm_binom_example2.py

    and the associated R example:

    https://github.com/gjhunt/statsmodels/blob/glmm/statsmodels/regression/scrap/testll/glmm_binom_example2.R

    R seems to fit this on the order of seconds while our implementation does so on the order of minutes. It seems to take about 300 evaluations of the loglike. R estimates the parameters as

    -1.20589, -0.05199 for the fe_params
    3.678724 for the cov_re

    statsmodels gets

    [-1.21094234 -0.05208696]
    [[ 3.70015336]]

    If R is the 'truth' then its not far off.

    As far as what my time is best spend doing, assuming I can still get some guidance from the community, I'd like to continue contributing (time-willing) after GSOC. I think statsmodels is useful and I like programming. So I think arbitrary GSOC deadlines can effectively be ignored if convenient. That is to say, I think we should do solely what makes the most sense from a software engineering standpoint.
    Although I'll repeat my mantra and say that I think a quick and dirty working implementation is much preferable to a non-complete elegant one. Then we can iteratively refine.

  11. josef-pkt commented on Jul 4, 2015

    @josef-pkt
    Member

    The complex step derivatives are very accurate, and work except for some scipy.special functions.
    For time series models like ARIMA which also don't have analytical derivatives, we ended up with complex step derivatives and lbfgs as default optimizer.

    I think that would work also pretty well (but maybe not very fast) for MixedGLM. It might provide enough accuracy to get a good working solution for the beginning.

  12. kshedden commented on Jul 4, 2015

    @kshedden
    Contributor

    @gjhunt I don't see your failing unit tests in your glmm branch. Can you push the testing code (should be in regression/tests/test_mixedglm.py) so I can take a look? It would also be good to share with us exactly by how much and in what conditions it is failing (maybe just cut/paste the test output here).

    I think what you are saying is that the numeric derivatives are used in a test, not in the actual code. I believe this is correct, we don't need to get ahead of ourselves and implement the score yet (numeric or otherwise), but there is an optimization sub-problem in the likelihood (due to Laplace). This sub-problem has its own gradient (not directly visible to caller) which we can check against the analogous numeric derivative. We need more detailed information on the extent to which this is failing. The numeric derivatives are very accurate in my experience, but we have to be realistic about tolerances (relative is more important than absolute, maybe 10^-2 relative tolerance should be OK). Also, this needs to work with a variety of link functions, families, etc. It would be informative to know if the errors are much worse with some link functions than with others.

    Your results with Nelder-Mead are encouraging and I would not worry at this point about timing, we can optimize later. Again, it would be good for us to know if this positive result can be obtained for a variety of different link functions and families.

    I am thinking that this branch can serve as a testing ground for an alternative approach to mixed models compared to what we did in MixedLM. MixedLM is group-based, and while the addition of variance components opens up a wide range of additional models, it is still not as general as glmer in R. I think we should aim to provide full generality in this branch, which will be easier since we don't plan initially to implement derivatives. I need to think about this a bit and give you some guidance, but it will probably involve dropping the notion of a group and doing everything with sparse matrices. However the basic structure of the Laplace calculations will go through as-is.

    Also, if I am correct about the connection between Laplace and Bates' penalized likelihood, it may turn out that the score is easier to implement when we get there compared to what we had in MixedLM.

    For reference, the MixedLM code is typically around 3-5x slower than R for comparable models. R's code is written in C so we are very unlikely to beat it in pure Python, especially with the groups-based implementation that is heavy on loops and temporaries. Eventually we will refactor some parts using cython. I have found that statsmodels GLM is about as fast as R, so pure python can approach a C implementation when almost everything is linear algebra.

  13. kshedden commented on Jul 4, 2015

    @kshedden
    Contributor

    The complex step derivative is very accurate. But the optimization experts usually say that if analytic derivatives are not available, it is better to use a derivative-free method than to use numeric derivatives in a gradient-based method like CG/BFGS. Unfortunately scipy does not have the latest derivative-free methods. A good overview of this topic is linked below. We still need the complex step derivative to obtain the Fisher information, but I would avoid using it in the actual fitting. Right now, lacking alternatives, we can stick with Nelder Mead for optimization.

    http://rd.springer.com/article/10.1007/s10898-012-9951-y

  14. josef-pkt commented on Jul 4, 2015

    @josef-pkt
    Member

    @kshedden AFAIU, One difference I thought of MixedGLM to MixedLM is that it will only work for groups, because we need explicit integration instead of the "closed form" solution in MixedLM.

    From my interpretation, there is still a large advantage of the group based MixedLM structure compared to Bates and penalized representation, in the sense that we never need to form the explicit "fixed effects", realizations of the random effects.
    The part that uses penalized likelihood will get closer to what we are doing in penalized splines (GAM) which are often implemented on top of a Mixed model.

    AFAIU, Stata is also using a double structure, with memory efficient fast group structure, and less efficient joint structure for crossed effects.

    In case this GSOC project is running out of time, I really prefer one working and tested version that might have strong limitations, which can be refined over two more releases, than having another project with a three quarter finished version and too low unit test coverage. I think that should be easily feasible.

  15. josef-pkt commented on Jul 4, 2015

    @josef-pkt
    Member

    But the optimization experts usually say that if analytic derivatives are not available, it is better to use a derivative-free method than to use numeric derivatives in a gradient-based method like CG/BFGS.

    However this does not correspond at all to my experience in statsmodels.

    Nelder-Mead is robust and converges from almost all starting values. scipy also has global optimizers.
    But for smooth problems, where it's just too complicated to calculate an analytical likelihood, smooth derivative based optimization still beats derivative free methods. In the article abstract they talk about 2500 function evaluations, while we usually work much lower.
    Most of our likelihood functions are well behaved except for corner cases and scaling problems.
    (We don't have messy nonlinear functions and difficult discrete mixtures yet. oops. I'm not sure about global optimization if there is a difficult finite point mixing structure. I used basinhopping for that in a different context.)

  16. gjhunt commented on Jul 6, 2015

    @gjhunt
    Author

    So for testing the gradients in the Laplace optimization sub-problem I got rid of the absolute tolerance in assert_allclose i.e. I set it to 1E2 and the relative tolerance seems to be good down to somewhere about 1E-14. So that's good. Although statsmodels.tools.numdiff.approx_fprime is occasionally giving 'nan' which I'll have to track down.

    I assume for the tests for MixedGLM you want me to mimic the MixedLM testing structure?

  17. kshedden commented on Jul 6, 2015

    @kshedden
    Contributor

    Setting atol to 1e2 gives a vacuous test, see the details for how this
    works here:

    http://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.testing.assert_allclose.html

    You need a small atol, not large to give a meaningful test.

    On Mon, Jul 6, 2015 at 11:36 PM, gjhunt [email protected] wrote:

    So for testing the gradients in the Laplace optimization sub-problem I got
    rid of the absolute tolerance in assert_allclose i.e. I set it to 1E2 and
    the relative tolerance seems to be good down to somewhere about 1E-14. So
    that's good. Although statsmodels.tools.numdiff.approx_fprime is
    occasionally giving 'nan' which I'll have to track down.

    I assume for the tests for MixedGLM you want me to mimic the MixedLM
    testing structure?

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

  18. gjhunt commented on Jul 6, 2015

    @gjhunt
    Author

    Yup. You're right. I didn't read the docs closely enough. So the example I'm working with is:

    https://github.com/gjhunt/statsmodels/blob/glmm/statsmodels/regression/scrap/testll/glmm_binom_example3.py

    It fails for something like 3 out of 10 examples. I'm running with atol=0, rtol=1E-1. Usually the element-wise max difference is actually quite small although its still failing with rtol what it is. Not sure what to make of this.

  19. josef-pkt commented on Jul 10, 2015

    @josef-pkt
    Member

    @gjhunt If your unit tests are working, then you should open a PR so we can make inline comments.
    Currently it's only possible to comment on a commit, but not on the entire diff.

  20. gjhunt commented on Jul 10, 2015

    @gjhunt
    Author

    Yea. I was thinking the same thing. I'll put a PR in. The canonical linked binomial and poisson tests are working but non-canonical links aren't working yet.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions