Skip to content

MNLogit Overflow #3635

Closed
Closed

Description

@jbrockmendel

https://groups.google.com/forum/#!topic/pystatsmodels/FAnjBe_RynE

This user is getting np.nan for the prsquared in MNLogit. It looks like the problem is in the mod_null model with only a constant regressor. In the call to fit, the third vector of params it evaluates is array([ -7.61152072e+09, -1.14406917e+09, 5.60530684e+07, 6.72625670e+07, 1.12107442e+07, 2.24214857e+07, 1.12107442e+07]).

Paraphrasing loglike here:

Xb = np.dot(self.exog, params)
prob = self.cdf(Xb)
logprob = np.log(prob)
return np.sum(self.wendog * logprob)

self.exog here is just a vector of ones, so we take evaluate cdf on the params:

eXB = np.column_stack((np.ones(len(Xb)), np.exp(Xb)))
cdf = eXb/eXb.sum(1)[:, None]

With this particular vector of params, np.exp(Xb) is array([ 0., 0., inf, inf, inf, inf, inf]), so we get a np.inf/np.inf and cdf returns array([[ 0., 0., nan, nan, nan, nan, nan]])

In this particular example, one of the endog outcomes is overwhelmingly more likely than the others. Aside from numerical issues which are addressable-albeit-ugly, is this class of model going to have robustness issues with highly imbalanced outcomes?

Before working around the overflow, I want to double-check a difference between the univariate and multivariate code. Logit.loglike and Probit.loglike are essentially identical:

        q = 2*self.endog - 1
        X = self.exog
        return np.sum(np.log(self.cdf(q*np.dot(X, params))))

But MNLogit leaves out the q. Is the sign baked in to the MNLogit penalty somewhere else?

Activity

  1. josef-pkt commented on May 2, 2017

    @josef-pkt
    Member

    (without having looked at the details for this case)

    • probabilities close to 0 or 1 are usually or often symptoms of perfect separation/prediction where MLE fails.
    • the code is most likely not optimized for numerical accuracy in edge cases. It's slow to figure out and fix numerical improvements that differ from "textbook implementations" (aside: the distributions in scipy are getting pretty good in edge cases after contributors and maintainers improved the behavior in edge cases over many years.)
      e.g. maybe logcdf(...) would be more stable that log(cdf(...)).
      Also, cdf has to be bound in interval [0, 1] and inf is out of bounds.
  2. jbrockmendel commented on May 2, 2017

    @jbrockmendel
    ContributorAuthor

    I'm going to hold off on worrying about the overflow here until I understand the difference that makes the q unnecessary here.

    In the mean-time to thank you (and Chad) for putting up with me, I'm putting together a PR that gets rid of the for-loop in MNLogit.hessian.

  3. josef-pkt commented on Sep 22, 2017

    @josef-pkt
    Member

    maybe related: llnull problems fixed for basic count models in #3921 when there are convergence problems

    np.sum(np.log(self.cdf(q*np.dot(X, params))))

    the q here uses a special trick for binary models (I had to recently look at it). I think that does not work for MNLogit because of more than two choices.

  4. jbrockmendel commented on Sep 22, 2017

    @jbrockmendel
    ContributorAuthor

    Not sure if the llnull is related, but I'll take a look. FYI I've gotten the overflow issues fixed, but haven't gotten a good fix for underflows.

    I've been holding off on pushing these and related changes upstream until the backlog of PRs gets resolved -- don't want to inundante you. Let me know if you'd prefer to plow ahead on the MNLogit area.

  5. josef-pkt commented on Sep 22, 2017

    @josef-pkt
    Member

    I might put MNLogit soon on my high priority list, given that I have been back in discrete for some time.

    related #3923 for Logit if it's mainly an overflow issue

  6. josef-pkt commented on Sep 22, 2017

    @josef-pkt
    Member

    AFAICS we can rewrite the MNLogit cdf to avoid evaluating exp(xb)
    also given that the main use in loglike is for logcdf we should define it as a separate method (same for Logit). Better cdf is still needed in score.

    Note, specific bug fixes with unit tests are much easier to review and merge than large refactorings and cleanups.

  7. josef-pkt commented on Sep 22, 2017

    @josef-pkt
    Member

    AFAICS, underflow needs clipping to cdf > 0, (or the use of 0log0 = 0)

  8. jbrockmendel commented on Sep 23, 2017

    @jbrockmendel
    ContributorAuthor

    AFAICS, underflow needs clipping to cdf > 0, (or the use of 0log0 = 0)

    The problem I'm referring to is floats that analytically are strictly positive but are rounded to zero by np.float64. These generally show up when the outcome classes are sufficiently unbalanced, but that's a reasonably common use case that is worth getting right.

    Even (especially) if there is perfect separation, many users may be interested in prediction without identification. In that case, there may be better options than raising.

    Note, specific bug fixes with unit tests are much easier to review and merge than large refactorings and cleanups.

    I'll take a look at my outstanding PRs and see if any of them can be split into smaller chunks. Even if its a small amount, it'd be nice to maintain forward momentum.

  9. josef-pkt commented on Sep 23, 2017

    @josef-pkt
    Member

    The problem I'm referring to is floats that analytically are strictly positive but are rounded to zero by np.float64.

    Do you have an example or test case for this?
    I assume that it is related to the overflow that has some choice probabilities at essentially 1 at floating point precision, which forces the other the be numerically zero, even if they would be e-xx where xx is very large. The smallest number in double precision 1e-xx > 0 is small enough that it doesn't round down by itself for any real live sample, I guess.
    I think this is computationally the same problem as perfect prediction or partial (perfect) separation

    Even (especially) if there is perfect separation, many users may be interested in prediction without identification. In that case, there may be better options than raising.

    I completely agree here. I added an option to turn perfect separation into a warning instead of an exception in binary models exactly for this reason. We don't have perfect separation detection for MNLogit yet.

  10. jbrockmendel commented on Sep 24, 2017

    @jbrockmendel
    ContributorAuthor

    Do you have an example or test case for this?

    The mailing list message that started this thread includes an excel doc Sample.xlsx

    df = pd.read_excel('Sample.xlsx')
    exog = df[['X', 'Y', 'Z']]
    exog = sm.add_constant(exog)
    endog = df['Count']
    >>> df['Count'].value_counts()
    1    766
    2     89
    3     22
    5      6
    4      5
    7      2
    9      1
    6      1
    

    So this is pretty imbalanced. Groups 2 and 3 might be OK numerically, but we're going to have trouble by the time we get to 6,7,9.

    model = sm.MNLogit(endog, exog=exog)
    res = model.fit(retall=True)
    # after 4 iterations it will "converge" to infinity
    # we'll grab the last non-NaN params vector
    hist = res.mle_retvals['allvecs']
    params = hist[-2].reshape(model.exog.shape[-1], -1)
    Xb = model.exog.dot(params)
    eXb = np.exp(Xb)
    
    >>> print(eXb[:3])
    [[ inf  inf   0.  inf   0.   0.  inf]
     [ inf  inf   0.  inf   0.   0.  inf]
     [ inf  inf   0.  inf   0.   0.  inf]]
    

    So its FU, but not necessarily BAR. We may be able to salvage some information if, say, eXb[0, 1 ] / eXb[1, 1] is (analytically) finite.

    The approach I've been taking is to subtract Xb.max(1) before exponentiating. There are some corner cases I'll ignore for now.

    Xb2 = Xb - Xb.max(1)[:, None]
    eXb2 = np.exp(Xb2)
    
    >>> eXb2[:3]
    array([[ 1.,  0.,  0.,  0.,  0.,  0.,  0.],
           [ 1.,  0.,  0.,  0.,  0.,  0.,  0.],
           [ 1.,  0.,  0.,  0.,  0.,  0.,  0.]])
    

    So we're still going to have problems with calculating the Hessian, but we're in a much better position than we were with inf/inf.

    Gotta run, will follow up later.

  11. jbrockmendel commented on Sep 25, 2017

    @jbrockmendel
    ContributorAuthor

    Looks like a lot of this actually got discussed in #3778. The upshot being that this normalization gets rid of the overflow, but the zeros here are the result of an underflow.

    The zeros will still lead to nans coming out in loglike (or loglikeobs), see discussion in #3778 for a workaround.

    But for score and hessian, I haven't found a good way to get anything meaningful. In some cases we can get higher-precision floats, but that comes with its own set of problems.

  12. jbrockmendel commented on Sep 25, 2017

    @jbrockmendel
    ContributorAuthor

    The workaround I've been poking at is to combine the smaller groups and iterate on conditional probabilities. In this case:

    endog2 = endog == 1
    model2 = sm.MNLogit(endog=endog2, exog=exog)
    res2 = model2.fit()
    print(res2.summary())
                              MNLogit Regression Results                          
    ==============================================================================
    Dep. Variable:                  Count   No. Observations:                  892
    Model:                        MNLogit   Df Residuals:                      888
    Method:                           MLE   Df Model:                            3
    Date:                Sun, 24 Sep 2017   Pseudo R-squ.:                  0.1078
    Time:                        18:50:33   Log-Likelihood:                -324.08
    converged:                       True   LL-Null:                       -363.25
                                            LLR p-value:                 6.927e-17
    ==============================================================================
       Count=1       coef    std err          z      P>|z|      [0.025      0.975]
    ------------------------------------------------------------------------------
    const          0.9729      0.318      3.061      0.002       0.350       1.596
    X             -0.0437      0.031     -1.417      0.157      -0.104       0.017
    Y              0.0567      0.025      2.291      0.022       0.008       0.105
    Z              1.6841      0.533      3.157      0.002       0.639       2.730
    ==============================================================================
    

    So we've at least got something meaningful. But this has its own set of problems, including the fact that the next iteration still diverges.

    exog3 = exog[endog != 1]
    endog3 = endog[endog != 1] == 2
    model3 = sm.MNLogit(endog=endog3, exog=exog3)
    res3 = model3.fit()
    Optimization terminated successfully.
             Current function value: nan
             Iterations 21
    
  13. josef-pkt commented on Sep 25, 2017

    @josef-pkt
    Member

    A suggestion for a MNLogit bug-fix PR that should be relatively simple to merge, based on this, #3778. and related issues like 3924 for corner cases in discrete in general

    • don't ignore user provided callback: I just fixed this in count models, and it needs fixing wherever else is shows up (I needed to fix it because it had bugs for one model and we cut of possible workarounds by users)
    • rearrange terms in cdf (subtract max or similar) (scipy is doing something similar for logexpsum (or something like that name)
    • clip cdf away from boundaries
    • use example as test case and check that it runs, and fix whatever else is needed to get it to run
      (if we can identify perfect separation case in MNLogit, then we could warn or raise similar to Logit, but I don't know anything specific about MNLogit, and when parameters are not identified in that model.)

    Given that I'm now mostly familiar with the issues, reviewing and helping should now be relatively easy for me.

    warning: getting unit tests to run across versions for corner or "not nice" cases can get tedious (in my recent experience)

  14. jbrockmendel commented on Sep 25, 2017

    @jbrockmendel
    ContributorAuthor

    These are good ideas. One more to add before I call it a day; we can discuss strategy tomorrow.

    This needs double-checking, but I think in the following procedure can check for perfect separation. Sticking with the earlier example:

    from scipy import spatial
    mask = endog == 1
    cloud = exog[mask].values[:, 1:]  # drop constant
    hull = spatial.Delaunay(cloud)
    

    I had expected that spatial.ConvexHull(cloud) would have a is_in_hull method or something, but the internet pointed me towards Delaunay. A point is in the convex hull of cloud iff hull.find_simplex(pt) >= 0 (well actually, the post only gives one direction of the iff. I need to look at the docs to be sure)

    pts = exog[~mask].values[:, 1:]
    outside = hull.find_simplex(pts) < 0
    

    It turns out that outside is all False in this case, which suggests that no group is perfectly separated from group 1. It may still be that group2 is perfectly separated from group3, or ...

    The Delaunay call is pretty quick in this ~700 point example. I haven't looked at how it scales. I imagine that there are near-optimality algorithms using the convex hulls of random subsets.

  15. josef-pkt commented on Sep 25, 2017

    @josef-pkt
    Member

    If there is a good, but computationally more complex check, then we might want to put it in post-estimation results to make it available to users, and eg. warn in summary instead of repeatedly computing it during optimization.

    (Using ConvexHull or Delauay for boundary problems sounds interesting and might be also potentially useful for compositional (interior of simplex) data which has a very similar structure as MNLogit, except continuous.)

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

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions