Skip to content

BUG: GLM families Gamma, inverseGaussian have wrong derivatives #4616

Closed

Description

@josef-pkt

edit: see comments at end

The main problem is that loglike and others use the estimated score inside the function, i.e. we concentrate out scale by using a pearson_chi2 by default.
This means for gradient optimization that the derivative with respect to the mean parameters includes the indirect effect of mean parameters on scale and therefore on loglike. The derivative of the loglike as is are not partial derivatives with respect to mean parameters only.
solution: fix scale during optimization

original description:

companion to #4614

I am adding a test to compare score and hessian with numerical derivatives.
The loop over models is in test_glm test_gradient_irls.

Gamma and InverseGaussian have large differences between score and numerical derivative score.
Poisson with sqrt link has some numerical problems, but the power/sqrt link looks fine (based on reading the code)

Other cases than these pass the assert for both score and hessian at rtol=0.05. Tightening the rtol showed failures at around rtol=0.03.

This is on top of the fixes of #4614 that I have currently in my branch.

               if not (family_class, link) in [(fam.Poisson, lnk.sqrt),
                                               (fam.Gamma, lnk.log),
                                               (fam.Gamma, lnk.identity),
                                               (fam.Gamma, lnk.inverse_power),
                                               (fam.InverseGaussian, lnk.log),
                                               (fam.InverseGaussian, lnk.identity),
                                               (fam.InverseGaussian, lnk.inverse_power)]:
                   check_score_hessian(rslt_irls)

Activity

  1. added
    type-bug-wrong
    on May 10, 2018
  2. added this to the 0.9 milestone on May 10, 2018
  3. josef-pkt commented on May 10, 2018

    @josef-pkt
    MemberAuthor

    I'm not sure I'm able to dig into Gamma and InverseGaussian for 0.9. I never looked much at the details for those two families.

    It is also possible that there is just the scale missing in one of the computation that I do in the test case. I.e. I haven't checked if loglike, score and hessian treat scale in the same way.

  4. josef-pkt commented on May 10, 2018

    @josef-pkt
    MemberAuthor

    GLM loglike, score_factor and hessian_factor all use the estimated scale

    if scale is None:
        scale = self.estimate_scale(mu)
    
  5. josef-pkt commented on May 10, 2018

    @josef-pkt
    MemberAuthor

    Also,
    loglike is explicitly coded in the family loglike_obs.
    score and hessian are based on link and variance functions and their derivatives and don't use the likelihood function directly.

  6. josef-pkt commented on May 11, 2018

    @josef-pkt
    MemberAuthor

    I'm giving up for now on this.
    I checked all the coded formulas for Gamma and partially for InverseGaussian, and don't find a mistake in any of the formulas.
    many of those formulas are based on SPSS Algorithm manual. I rederived Gamma loglike and some other parts but I didn't find any typos in the SPSS manual either.

    So I have not guess where a bug or problem might be hiding.
    We need more test cases to check that it is not just a numerical problem in the specific test cases.

  7. josef-pkt commented on May 11, 2018

    @josef-pkt
    MemberAuthor

    another observation:

    for GLM-Gamma in a modified test case
    If I use method='nm' with max_start_irls=10, then it finds a params with higher llf than the irls params.

    The loglike estimates the scale inside the loglike, so the scale estimate depends on params. So, we use a concentrated likelihood (although we use pearson_chi2 estimate for scale by default). So, the loglike optimization takes the effect on scale of changing parameters into account.

    However, as in the normal case, this should not matter for the mean parameters because the FOC/score is multiplicative in scale also in the Gamma case (and should be so for all GLM/LEF models here).

    However, score at "nm" params is large, while score at irls params is less than 1e-8

    another check
    explicit computation of score_factor for Gamma with log link agrees well with model.score_factor at irls params

    (Pdb) sf = (results.resid_response / results.fittedvalues)
    (Pdb) sf[:10]
    array([-0.68089391, -0.51622608,  1.38959439,  0.85883397,  0.76594999,
           -0.76268795,  0.17776557, -0.1347308 , -0.12027292, -0.06716199])
    (Pdb) results.model.score_factor(results.params)[:10]
    array([-1.49943656, -1.13681184,  3.06010759,  1.89128884,  1.68674355,
           -1.67956003,  0.39146802, -0.29669862, -0.26486008, -0.14790136])
    (Pdb) sf[:10] / results.model.score_factor(results.params)[:10]
    array([ 0.45409985,  0.45409985,  0.45409985,  0.45409985,  0.45409985,
            0.45409985,  0.45409985,  0.45409985,  0.45409985,  0.45409985])
    (Pdb) results.scale
    0.45409984586831165
    (Pdb) results.model.family.link
    <statsmodels.genmod.families.links.log object at 0x0000000009A845F8>
    
    (Pdb) np.max(np.abs(sf/results.scale / results.model.score_factor(results.params)-1))
    1.3322676295501878e-15
    
  8. josef-pkt commented on May 11, 2018

    @josef-pkt
    MemberAuthor

    Ok, my guess is that we need to fix the scale during fit_gradient optimization, so we don't pick up the partial effect of params on scale on loglike.
    I.e. we need partial derivative of loglike w.r.t. params (keeping scale fixed), which we have in the score/score_factor methods.

    My guess is that the indirect partial effect of scale is large enough in Gamma and InverseGaussian cases that it distorts the connection between loglike derivative and score.
    Side effect is that it distorts gradient based optimization and makes convergence more difficult. Which means we can check the difficult test cases in test_glm.py test_gradient_irls to see whether those improve.

  9. josef-pkt commented on May 11, 2018

    @josef-pkt
    MemberAuthor

    That seems to be it.
    fixing the scale in the unit test check_score_hessian, reduces the number of failures by 4
    3 cases are left, which I guess might be mostly numerical problems:

                   if not (family_class, link) in [(fam.Poisson, lnk.sqrt),
                                                   # (fam.Gamma, lnk.log),
                                                   # (fam.Gamma, lnk.identity),
                                                   (fam.Gamma, lnk.inverse_power),
                                                   # (fam.InverseGaussian, lnk.log),
                                                   (fam.InverseGaussian, lnk.identity),
                                                   # (fam.InverseGaussian, lnk.inverse_power)
                                                    ]:
                       check_score_hessian(rslt_irls)
    
  10. josef-pkt commented on May 11, 2018

    @josef-pkt
    MemberAuthor

    see #3357 for scale estimate inside IRLS loop
    #3359 for general scale issues

  11. josef-pkt commented on May 11, 2018

    @josef-pkt
    MemberAuthor

    A qualifier to how important the moving scale is:

    at the MLE w.r.t. scale, the derivative of loglike with respect to scale is also zero.
    If the pearson scale is close to the MLE scale, then the indirect effect coming from the response of scale to changes in params is also very small (theoretically) at the estimated parameters.

    So, the effect is non-trivial only when we are away from the MLE, i.e. during optimization, or in my test case because I evaluate score at params that are away from MLE (to avoid score close to zero).

    There should be something similar for the Hessian, but I cannot do the math in my head. At the MLE the first derivative parts are small, and the second derivative cross-effect is small because in LEF the scale and mean parameters are separable (roughly: zero expected asymptotic correlation or off-diagonal block of expected hessian is zero).

    One guess: speed of convergence of Newton method should be larger with fixed scale than in the current setting with concentrated out scale.
    Maybe not: score and hessian are already computed assuming locally fixed scale, and newton just uses those two.
    'bfgs' and 'lbfgs' however might have problems, because score is explicit (derivative based on fixed scale) and hessian approximation is based on loglike (derivative based on variable scale)

  12. thequackdaddy commented on May 11, 2018

    @thequackdaddy
    Member

    @josef-pkt Very informative write-up.

    First, I'm not that strong on some of the math here. Matrix differentiation is confusing as heck to me, and I always screw up the math.

    But I found this PPT that I thought was very good. See page 18 for the score function, 20 for the OIM, and 21 for the EIM.

    For newton, I think you have 1 / scale in both the numerator and denominator, so I think for newton you can guess something, and it shouldn't affect the estimate.

    Am I wrong?

  13. thequackdaddy commented on May 11, 2018

    @thequackdaddy
    Member

    Also, using that PPT, I got a different calculation of the OIM from the source code.

    I got something like like this...

    I was able to come up with this for the OIM...

    OIM = 1 / scale * ( 1 / (g'(mu) ** 2 * V(mu)) + (endog - mu) * (g'(mu) * V'(mu) + g''(mu) * V(mu)) / (g'(mu) ** 3 * V(mu) ** 2))
    

    I think that math agrees with your guess that the line... oim_factor = eim_factor * (1 + tmp) should really be oim_factor = eim_factor + tmp.

  14. josef-pkt commented on May 11, 2018

    @josef-pkt
    MemberAuthor

    @thequackdaddy
    Thanks for the link, that looks like a good summary.
    Unfortunately, what we have currently are some inconsistencies because with adjust the dispersion parameters phi inside the gradient optimization loop, which is almost always taken as fixed in the GLM literature during derivation and optimization.
    (AFAICT, my chasing bugs in formulas for Gamma and InverseGaussian was a dead end with the only benefit that I now remember some more of those details.)

    This is now essentially a continuation of the scale cleanup that we started for 0.9.
    For most usecases it doesn't matter what's left after #4620 bug fixes, but we want to have this conceptually clean when we want to extend the use of var_weights and scale and estimate them either by MLE or by an iterative loop that alternates between scale/var estimation and mean parameter estimation.
    (Besides the immediate effect of figuring out how to write unit tests and maybe help bfgs to converge better.)

  15. josef-pkt commented on May 12, 2018

    @josef-pkt
    MemberAuthor

    another try

    I'm setting scaletype=1. during optimization in fit_gradient and switch test_gradient_irls to bfgs instead of newton.
    The following still fail at given assert tolerance. Some look like just small differences in precision, but in some cases params are not close

    (Gamma, log), (Gamma, identity) scale just a bit too far for tolerance rtol=1e-06, atol=1e-06
    (Poisson, sqrt) 3rd decimal in params differs at params around 1.
    (Gamma, lnk.inverse_power): params by around 20% (eyeballing)

                   if (family_class, link) in [(fam.Poisson, lnk.sqrt),
                                                   (fam.Gamma, lnk.log),
                                                   (fam.Gamma, lnk.identity),
                                                   (fam.Gamma, lnk.inverse_power),
    
  16. josef-pkt commented on May 17, 2018

    @josef-pkt
    MemberAuthor

    I ran into the same problem again in penalized.
    Writing unit tests comparing to numerical derivative without fixing the scale results in test failures.
    case GLM Gaussian with L2 penalization

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    FAQcomp-genmodtype-bug-wrong

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions