Skip to content

divide by zero encountered in log #3337

Open

Description

@denadai2

I have this warnings:

/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/statsmodels/base/model.py:466: ConvergenceWarning: Maximum Likelihood optimization failed to converge. Check mle_retvals
"Check mle_retvals", ConvergenceWarning)
/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/statsmodels/discrete/discrete_model.py:2012: RuntimeWarning: divide by zero encountered in log
  llf = coeff + size*np.log(prob) + endog*np.log(1-prob)

with this code:

df = pd.read_csv('test.csv')
features = ['unemployed', 'pp']
X = (df[features] - df[features].mean())/df[features].std()
y = df['num'].values
X_sm = sm.add_constant(X[features].copy())
model = sm.NegativeBinomial(y, X_sm, offset=np.log(df['population'].values+1))

start = np.zeros(X_sm.values.shape[1]+1)
start[0] = np.log(np.mean(y))
res = model.fit(maxiter=1000, start_params=start, method='bfgs')

print(res.summary())

and this version:

'0.6.1'

can you help me?

test.csv.zip

Activity

  1. josef-pkt commented on Dec 22, 2016

    @josef-pkt
    Member

    I don't have time to check right now, maybe later today.
    Just some general comments based on my experience with this:

    Check the scaling of variables. There should not be large values in absolute terms because of the exponential transformation. Also, try to start with method='nm' and if you get something closer to convergence, use it with method='bfgs'.

    I was struggling for a while with this, but it is still not very robust in some cases with Poisson and NegativeBinomial.
    There was also a problem in some recent scipy versions where 'bfgs' did not have a robust enough step-size choice. That has been fixed in scipy, AFAIR.

    In some cases using GLM NegativeBinomial with irls and fixed nbin shape parameter works better for convergence.

    (One possible solution that seems to help in many cases is to standardize the exog. But the automatic support for this is still in prototype state.)

  2. josef-pkt commented on Dec 22, 2016

    @josef-pkt
    Member

    to clarify: I ran into many convergence issues with NegativeBinomial, but AFAIR, I haven't seen that specific traceback before, usually I got nans, IIRC. (or maybe I had displaying the zero division warnings turned off.)

  3. denadai2 commented on Dec 22, 2016

    @denadai2
    Author
    start = np.zeros(X_sm.values.shape[1]+1)
    start[0] = np.log(np.mean(y))
    res_nm = model.fit(maxiter=1000, start_params=start, method='nm')
    res = model.fit(start_params=res_nm.params, method='bfgs')
    

    I tried also this, but of course I have warnings. It's not clear to me how to perform a good regression and be "sure" to have good results

    (thanks)

  4. josef-pkt commented on Dec 22, 2016

    @josef-pkt
    Member

    Can you try to see if Poisson works?
    In the current master version (I don't remember when I changed this), I use the Poisson estimate for the start_params, but it also failed on badly scaled exog.
    Poisson doesn't get the extra complication from the nbin dispersion parameter, but can still run into exp overflow problems.

    However, given the traceback llf = coeff + size*np.log(prob) + endog*np.log(1-prob)
    I think we need an additional safeguard for prob = 0 or 1. I didn't look at the code yet where this happens.

  5. added this to the 0.9 milestone on Dec 22, 2016
  6. josef-pkt commented on Dec 22, 2016

    @josef-pkt
    Member

    (a suspicion:
    the prob in the traceback looks like a perfect separation/prediction corner case, which I've never really seen before,
    #1391, and maybe #1512
    Similar behavior will apply to NegativeBinomial as to Poisson
    )

  7. denadai2 commented on Dec 22, 2016

    @denadai2
    Author

    Poisson works without warnings, but I have to say that there is overdispersion so I need the NB model...

    Optimization terminated successfully.
             Current function value: 71.757157
             Iterations: 212
             Function evaluations: 382
    Optimization terminated successfully.
             Current function value: 71.757157
             Iterations: 4
             Function evaluations: 8
             Gradient evaluations: 8
                              Poisson Regression Results                          
    ==============================================================================
    Dep. Variable:                      y   No. Observations:                  110
    Model:                        Poisson   Df Residuals:                      107
    Method:                           MLE   Df Model:                            2
    Date:                Thu, 22 Dec 2016   Pseudo R-squ.:                  0.5833
    Time:                        20:54:18   Log-Likelihood:                -7893.3
    converged:                       True   LL-Null:                       -18942.
                                            LLR p-value:                     0.000
    ==============================================================================
                     coef    std err          z      P>|z|      [95.0% Conf. Int.]
    ------------------------------------------------------------------------------
    const         -4.7517      0.006   -796.837      0.000        -4.763    -4.740
    unemployed     0.4543      0.007     64.134      0.000         0.440     0.468
    pp            -0.8964      0.008   -118.628      0.000        -0.911    -0.882
    ==============================================================================
    

    NB (with warnings):

    Optimization terminated successfully.
             Current function value: 6.825812
             Iterations: 269
             Function evaluations: 463
    Optimization terminated successfully.
             Current function value: 6.602634
             Iterations: 7
             Function evaluations: 11
             Gradient evaluations: 11
                         NegativeBinomial Regression Results                      
    ==============================================================================
    Dep. Variable:                      y   No. Observations:                  110
    Model:               NegativeBinomial   Df Residuals:                      107
    Method:                           MLE   Df Model:                            2
    Date:                Thu, 22 Dec 2016   Pseudo R-squ.:                 0.09013
    Time:                        20:56:24   Log-Likelihood:                -726.29
    converged:                       True   LL-Null:                       -798.23
                                            LLR p-value:                 5.698e-32
    ==============================================================================
                     coef    std err          z      P>|z|      [95.0% Conf. Int.]
    ------------------------------------------------------------------------------
    const         -4.7394      0.063    -75.231      0.000        -4.863    -4.616
    unemployed     0.3697      0.055      6.672      0.000         0.261     0.478
    pp            -0.9328      0.064    -14.492      0.000        -1.059    -0.807
    alpha          0.4312      0.056      7.655      0.000         0.321     0.542
    ==============================================================================
    
  8. josef-pkt commented on Dec 22, 2016

    @josef-pkt
    Member

    Does the last summary() for NegativeBinomial mean that you managed to get it to converge?
    The results look good and close to the Poisson mean parameters.

    BTW: model.fit(cov_type='HC0') will produce correct standard errors for Poisson with dispersion.
    (It corrects for general heteroscedasticity rather than just for dispersion.)

  9. denadai2 commented on Dec 22, 2016

    @denadai2
    Author

    NB converged since the beginning. I don't understand all the warnings: why? Bug?
    (I explain it better: I'm trying to publish some results and I'd like to be sure about my results. Moreover, I'm trying to contribute)

    where can I see the cov_types documentation? Very interesting! Thanks

  10. josef-pkt commented on Dec 22, 2016

    @josef-pkt
    Member

    Ok, then I misunderstood.
    It is possible that during the optimization some parameter values are tried out that produce invalid results. However, several of the scipy optimizers are robust to some of these problems. So, there might be warnings during the optimization even though the final result is good. If the message is "converged", then the optimization didn't find any problems at the final solution.

    One way to cross-check the results is to look at the score, i.e. first order condition of the optimization, (or moment condition or estimating equation.
    e.g.
    model.score(results.params)
    which should be close to zero.
    Usually gradient or hessian based method like newton have better final local convergence, but might get thrown off away from the neighborhood of the optimum.
    Note, score is a method of the model, but only the result instance knows the estimated parameters.

    I don't find the docstring for the cov_type right now.
    A draft for a more elaborate explanation is here https://github.com/josef-pkt/misc/blob/robust_cov/notebooks/doc_robust_cov.ipynb
    There were still some changes after 0.6.1, so I'm don't remember exactly what was available then. Also, while writing the doc_robust_cov.ipynb I worked through some API/naming inconsistencies that are fixed in master, but not reflected in that notebook.

    The original version was a results method, but now the recommended and safer pattern is as a fit keyword. All models have mostly the same options, except HC1, HC2 and HC3 are only for OLS/WLS. In the other models all HCx are HC0.
    http://www.statsmodels.org/stable/generated/statsmodels.regression.linear_model.RegressionResults.get_robustcov_results.html#statsmodels.regression.linear_model.RegressionResults.get_robustcov_results

  11. denadai2 commented on Dec 24, 2016

    @denadai2
    Author

    super thanks

  12. removed this from the 0.9 milestone on Jan 1, 2017
  13. josef-pkt commented on Jan 1, 2017

    @josef-pkt
    Member

    I'm labeling this as FAQ issue.

    I'm keeping the bug label for now to check the 0 log 0 case in NegativeBinomial.

  14. denadai2 commented on Mar 3, 2017

    @denadai2
    Author

    thanks

  15. bashtage commented on May 10, 2019

    @bashtage
    Member

    Only a problem if user provides start params, otherwise works without warnings.

  16. josef-pkt commented on Dec 21, 2021

    @josef-pkt
    Member

    I'm looking at this again. I hadn't paid attention to the start_params in the original example.

    alpha (i.e. params[-1]) cannot be zero in NegativeBinomial(P). The loglikelihood and derivatives cannot be evaluated with alpha equal to zero or in the close neighborhood of zero.
    So the start_params for alpha has to be strictly positive, and the data needs to be overdispersed relative to Poisson so that parameter estimate don't try to converge to alpha <= 0.

    Note, alpha in NegativeBinomial does not use a log-link, params[-1] is the actual alpha.
    NegativeBinomialP has a use_transparams fit option, but, AFAIR, that is not fully implemented as user option.
    (not verified, and does not work with all optimizers)

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