Skip to content

overflow encountered in exp [Poisson] #3533

Closed

Description

@denadai2

I have this error and my fit doesn't work. I don't know the reason (same problem in negativebinomial). Stats,model 0.8.0

import pandas as pd
features = ['pp']
df = pd.read_csv('bug.csv')
X = (df[features] - df[features].mean())/df[features].std()
y = df['num'].values
X_sm = sm.add_constant(X[features].copy())
model = sm.Poisson(y, X_sm, ) #
res = model.fit()

Thanks
bug.csv.zip

/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/statsmodels/discrete/discrete_model.py:901: RuntimeWarning: overflow encountered in exp
/  return stats.poisson.cdf(y, np.exp(X))
//Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/statsmodels/discrete/discrete_model.py:1175: RuntimeWarning: overflow encountered in exp
/  L = np.exp(np.dot(X,params) + exposure + offset)
//Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/statsmodels/discrete/discrete_model.py:1112: RuntimeWarning: overflow encountered in exp
/  L = np.exp(np.dot(X,params) + offset + exposure)
//Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/scipy/stats/_discrete_distns.py:451: RuntimeWarning: invalid value encountered in greater_equal
/  return mu >= 0
//Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/statsmodels/base/optimizer.py:230: RuntimeWarning: invalid value encountered in greater
/  oldparams) > tol)):
//Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/scipy/stats/_distn_infrastructure.py:875: RuntimeWarning: invalid value encountered in greater
/  return (self.a < x) & (x < self.b)
//Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/scipy/stats/_distn_infrastructure.py:875: RuntimeWarning: invalid value encountered in less
/  return (self.a < x) & (x < self.b)
//Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/scipy/stats/_distn_infrastructure.py:1814: RuntimeWarning: invalid value encountered in less_equal
/  cond2 = cond0 & (x <= self.a)

Activity

  1. denadai2 commented on Mar 3, 2017

    @denadai2
    Author

    It seems (from my debug) that in _fit_newton, score(oldparams) gives nan everywhere at a certain interaction

  2. josef-pkt commented on Mar 3, 2017

    @josef-pkt
    Member

    sounds like the same issue as in #3337
    (we get many of those warnings now in the test run, which AFAIR were not printed before some recent version changes.)

    Does the optimization converge in your case or not?

  3. denadai2 commented on Mar 3, 2017

    @denadai2
    Author

    yes :)

    Optimization terminated successfully.
             Current function value: nan
             Iterations 2
                              Poisson Regression Results                          
    ==============================================================================
    Dep. Variable:                      y   No. Observations:                  198
    Model:                        Poisson   Df Residuals:                      196
    Method:                           MLE   Df Model:                            1
    Date:                Fri, 03 Mar 2017   Pseudo R-squ.:                     nan
    Time:                        18:52:08   Log-Likelihood:                    nan
    converged:                       True   LL-Null:                           nan
                                            LLR p-value:                       nan
    ==============================================================================
                     coef    std err          z      P>|z|      [0.025      0.975]
    ------------------------------------------------------------------------------
    const             nan        nan        nan        nan         nan         nan
    pp                nan        nan        nan        nan         nan         nan
    ==============================================================================
    
  4. josef-pkt commented on Mar 3, 2017

    @josef-pkt
    Member

    That looks bad.

    converged=True is completely misleading.

  5. denadai2 commented on Mar 3, 2017

    @denadai2
    Author

    True that. Let me know how I can help. It seems that the iteration goes well until a point where it goes crazy. In this case iteration 2 :)

  6. josef-pkt commented on Mar 3, 2017

    @josef-pkt
    Member

    You could try model.fit(method='nm', maxiter=5000, maxfun=5000

    I hope I remember the maxiter and maxfun keywords correctly.

    From looking at the numbers in the csv files I guess they are not very close to a Poisson distribution, looking at raw numbers is not very "precise".

    Main thing to check is whether GLM with default IRLS fit manages to converge to a reasonable looking result in this case.

    (for the future: In the next release we should be able to use better trust region newton method provided by scipy, which might manage to converge in some of these cases.)
    Given that you are already standardizing the explanatory variable, scaling itself cannot be a source for the convergence failure anymore.

  7. denadai2 commented on Mar 3, 2017

    @denadai2
    Author

    I'm using a Poisson fit just because it is simpler to see whether there is a bug (imho). I'll use a Negative Binomial, which has the same np.exp error.

    However, with maxiter + maxfun I have the same warnings + it seems it converges but the llnull is nan:

    Optimization terminated successfully.
             Current function value: 804.014365
             Iterations: 89
             Function evaluations: 167
                              Poisson Regression Results                          
    ==============================================================================
    Dep. Variable:                      y   No. Observations:                  198
    Model:                        Poisson   Df Residuals:                      196
    Method:                           MLE   Df Model:                            1
    Date:                Fri, 03 Mar 2017   Pseudo R-squ.:                     nan
    Time:                        19:13:47   Log-Likelihood:            -1.5919e+05
    converged:                       True   LL-Null:                           nan
                                            LLR p-value:                       nan
    ==============================================================================
                     coef    std err          z      P>|z|      [0.025      0.975]
    ------------------------------------------------------------------------------
    const          7.3400      0.002   3990.530      0.000       7.336       7.344
    pp             0.2585      0.002    142.892      0.000       0.255       0.262
    

    Is it normal?

    PS: is standardization a problem?

  8. josef-pkt commented on Mar 3, 2017

    @josef-pkt
    Member

    ll-null is nan is also a convergence failure, but there is no way for users to affect it, #3476

    I converged actually pretty fast, 89 iterations is good for "nm".

    The problem I think is that the gradient in your example is very large, and most gradient based optimization methods jump out of the range that doesn't result in overflow. This happens with our newton and it happened with bfgs and several others. bfgs has been fixed in the latest scipy releases, so it should work better now.

    My latest take on this is #3521. our newton works well in nice cases, but we need something more convenient for the difficult optimization cases.

  9. josef-pkt commented on Mar 3, 2017

    @josef-pkt
    Member

    @denadai2 Is the data in your csv file for public use, i.e. can we include it in statsmodels as a test case?

    Also, when you have a converged result from Poisson, then you can use it also as a start_params for NegativeBinomial, after adding an initial value for the dispersion coefficient, e.g. 0.5.

  10. josef-pkt commented on Mar 3, 2017

    @josef-pkt
    Member

    cross-link to list of optimization failures #1649

  11. denadai2 commented on Mar 3, 2017

    @denadai2
    Author

    Yes you can use the csv as test case :)
    However I have some doubts/issues:

    • I have converged = True, but ll-null is a converged failure. Is this a bug?
    • What should I use to avoid ll-null? Sorry I did not understand what could be the solution
    • I'm using statsmodel in a iterative way (to find variables that minimize the AICc). Thus, it would be really, really, awesome to have some checks/suggestion to have a fit()/fit_difficult() that works (in this case a converged = True/False that works can help)
    • I tried poisson + nb but I always have llnull = nan and overflow problems :(

    PS: u deserve beers :D

  12. josef-pkt commented on Mar 3, 2017

    @josef-pkt
    Member

    about ll-null: there is currently no workaround to prevent the convergence failure and nan. In the mailing list thread that is linked in #3476 describes a bit how users could compute them but no fully coded recipe.

    Note, converged=True as reported by the scipy optimizers and all nans is a serious bug, because it is misleading. The other bugs require ongoing efforts to reduce convergence failures in "not so nice" cases.

  13. josef-pkt commented on Mar 4, 2017

    @josef-pkt
    Member

    brief check of the example

    in the Poisson example
    with scipy 0.17.0 bfgs converges

    Optimization terminated successfully.
             Current function value: 884.916016
             Iterations: 9
             Function evaluations: 30
             Gradient evaluations: 19
    

    with statsmodels master using recently merged method="minimize" option

    res = model.fit(method="minimize", min_method='dogleg')
    Optimization terminated successfully.
             Current function value: 884.916016
             Iterations: 11
             Function evaluations: 12
             Gradient evaluations: 11
             Hessian evaluations: 10
    

    To get llnull, I changed the method to "nm" in DiscreteResults.llnull

                              Poisson Regression Results                          
    ==============================================================================
    Dep. Variable:                      y   No. Observations:                  270
    Model:                        Poisson   Df Residuals:                      268
    Method:                           MLE   Df Model:                            1
    Date:                Sat, 04 Mar 2017   Pseudo R-squ.:                  0.1061
    Time:                        00:20:47   Log-Likelihood:            -2.3893e+05
    converged:                       True   LL-Null:                   -2.6729e+05
                                            LLR p-value:                     0.000
    ==============================================================================
                     coef    std err          z      P>|z|      [0.025      0.975]
    ------------------------------------------------------------------------------
    const          6.9683      0.002   3575.004      0.000       6.964       6.972
    pp             0.4473      0.002    232.896      0.000       0.444       0.451
    ==============================================================================
    
  14. denadai2 commented on Mar 4, 2017

    @denadai2
    Author

    Ok I'm using last version (master) of statsmodels and scipy 0.18.1.
    Poisson with const + pp works IF I modify DiscreteResults.llnull.

    Now, before adding all the variables I have, we move to the Negative Binomial:
    I add

    model = sm.NegativeBinomial(y, X_sm, )
    start = res.params.append(pd.Series(0.9, index=['alpha']))
    res = model.fit(maxiter=2000, start_params=start, method="minimize")
    

    And the result is that the llnullmodel does not fit (even with the method='nm')

    Optimization terminated successfully.
             Current function value: 884.916016
             Iterations: 11
             Function evaluations: 12
             Gradient evaluations: 11
             Hessian evaluations: 10
    Optimization terminated successfully.
             Current function value: 6.452032
             Iterations: 12
             Function evaluations: 13
             Gradient evaluations: 13
    
    /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/statsmodels-0.8.0-py3.4-macosx-10.6-intel.egg/statsmodels/discrete/discrete_model.py:901: RuntimeWarning: overflow encountered in exp
      return stats.poisson.cdf(y, np.exp(X))
    /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/statsmodels-0.8.0-py3.4-macosx-10.6-intel.egg/statsmodels/discrete/discrete_model.py:1172: RuntimeWarning: overflow encountered in exp
      L = np.exp(np.dot(X,params) + exposure + offset)
    /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/statsmodels-0.8.0-py3.4-macosx-10.6-intel.egg/statsmodels/discrete/discrete_model.py:1112: RuntimeWarning: overflow encountered in exp
      L = np.exp(np.dot(X,params) + offset + exposure)
    /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/scipy/stats/_discrete_distns.py:451: RuntimeWarning: invalid value encountered in greater_equal
      return mu >= 0
    
    
                         NegativeBinomial Regression Results                      
    ==============================================================================
    Dep. Variable:                      y   No. Observations:                  270
    Model:               NegativeBinomial   Df Residuals:                      268
    Method:                           MLE   Df Model:                            1
    Date:                Sat, 04 Mar 2017   Pseudo R-squ.:                     nan
    Time:                        16:22:04   Log-Likelihood:                -1742.0
    converged:                       True   LL-Null:                           nan
                                            LLR p-value:                       nan
    ==============================================================================
                     coef    std err          z      P>|z|      [0.025      0.975]
    ------------------------------------------------------------------------------
    const          6.9013      0.145     47.616      0.000       6.617       7.185
    pp             0.7432      0.181      4.111      0.000       0.389       1.098
    alpha          5.6705      0.452     12.534      0.000       4.784       6.557
    ==============================================================================
    
    /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/statsmodels-0.8.0-py3.4-macosx-10.6-intel.egg/statsmodels/base/model.py:481: HessianInversionWarning: Inverting hessian failed, no bse or cov_params available
      'available', HessianInversionWarning)
    

    I naively try also to put method="minimize", min_method='dogleg' to fit llnull in DiscreteResults and I have:

    ValueError                                Traceback (most recent call last)
    <ipython-input-2-d821dbf330a6> in <module>()
         44 
         45 
    ---> 46 print(res.summary())
    
    /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/statsmodels-0.8.0-py3.4-macosx-10.6-intel.egg/statsmodels/discrete/discrete_model.py in summary(self, yname, xname, title, alpha, yname_list)
       2530                      ('Df Residuals:', None),
       2531                      ('Df Model:', None),
    -> 2532                      ('Pseudo R-squ.:', ["%#6.4g" % self.prsquared]),
       2533                      ('Log-Likelihood:', None),
       2534                      ('LL-Null:', ["%#8.5g" % self.llnull]),
    
    /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/statsmodels-0.8.0-py3.4-macosx-10.6-intel.egg/statsmodels/tools/decorators.py in __get__(self, obj, type)
         95         if _cachedval is None:
         96             # Call the "fget" function
    ---> 97             _cachedval = self.fget(obj)
         98             # Set the attribute in obj
         99             # print("Setting %s in cache to %s" % (name, _cachedval))
    
    /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/statsmodels-0.8.0-py3.4-macosx-10.6-intel.egg/statsmodels/discrete/discrete_model.py in prsquared(self)
       2380     @cache_readonly
       2381     def prsquared(self):
    -> 2382         return 1 - self.llf/self.llnull
       2383 
       2384     @cache_readonly
    
    /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/statsmodels-0.8.0-py3.4-macosx-10.6-intel.egg/statsmodels/tools/decorators.py in __get__(self, obj, type)
         95         if _cachedval is None:
         96             # Call the "fget" function
    ---> 97             _cachedval = self.fget(obj)
         98             # Set the attribute in obj
         99             # print("Setting %s in cache to %s" % (name, _cachedval))
    
    /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/statsmodels-0.8.0-py3.4-macosx-10.6-intel.egg/statsmodels/discrete/discrete_model.py in llnull(self)
       2401         # TestPoissonConstrained1a.test_smoke
       2402         res_null = mod_null.fit(disp=0, warn_convergence=False,
    -> 2403                                 maxiter=10000, method="minimize", min_method='dogleg')
       2404         return res_null.llf
       2405 
    
    /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/statsmodels-0.8.0-py3.4-macosx-10.6-intel.egg/statsmodels/discrete/discrete_model.py in fit(self, start_params, method, maxiter, full_output, disp, callback, cov_type, cov_kwds, use_t, **kwargs)
       2267                         maxiter=maxiter, method=method, disp=disp,
       2268                         full_output=full_output, callback=lambda x:x,
    -> 2269                         **kwargs)
       2270                         # TODO: Fix NBin _check_perfect_pred
       2271         if self.loglike_method.startswith('nb'):
    
    /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/statsmodels-0.8.0-py3.4-macosx-10.6-intel.egg/statsmodels/discrete/discrete_model.py in fit(self, start_params, method, maxiter, full_output, disp, callback, **kwargs)
        821         cntfit = super(CountModel, self).fit(start_params=start_params,
        822                 method=method, maxiter=maxiter, full_output=full_output,
    --> 823                 disp=disp, callback=callback, **kwargs)
        824         discretefit = CountResults(self, cntfit)
        825         return CountResultsWrapper(discretefit)
    
    /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/statsmodels-0.8.0-py3.4-macosx-10.6-intel.egg/statsmodels/discrete/discrete_model.py in fit(self, start_params, method, maxiter, full_output, disp, callback, **kwargs)
        202         mlefit = super(DiscreteModel, self).fit(start_params=start_params,
        203                 method=method, maxiter=maxiter, full_output=full_output,
    --> 204                 disp=disp, callback=callback, **kwargs)
        205 
        206         return mlefit # up to subclasses to wrap results
    
    /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/statsmodels-0.8.0-py3.4-macosx-10.6-intel.egg/statsmodels/base/model.py in fit(self, start_params, method, maxiter, full_output, disp, fargs, callback, retall, skip_hessian, **kwargs)
        457                                                        callback=callback,
        458                                                        retall=retall,
    --> 459                                                        full_output=full_output)
        460 
        461         #NOTE: this is for fit_regularized and should be generalized
    
    /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/statsmodels-0.8.0-py3.4-macosx-10.6-intel.egg/statsmodels/base/optimizer.py in _fit(self, objective, gradient, start_params, fargs, kwargs, hessian, method, maxiter, full_output, disp, callback, retall)
        191                             disp=disp, maxiter=maxiter, callback=callback,
        192                             retall=retall, full_output=full_output,
    --> 193                             hess=hessian)
        194 
        195         optim_settings = {'optimizer': method, 'start_params': start_params,
    
    /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/statsmodels-0.8.0-py3.4-macosx-10.6-intel.egg/statsmodels/base/optimizer.py in _fit_minimize(f, score, start_params, fargs, kwargs, disp, maxiter, callback, retall, full_output, hess)
        246 
        247     res = optimize.minimize(f, start_params, args=fargs, method=kwargs['min_method'],
    --> 248                             jac=score, hess=hess, callback=callback, options=options)
        249 
        250     xopt    = res.x
    
    /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/scipy/optimize/_minimize.py in minimize(fun, x0, args, method, jac, hess, hessp, bounds, constraints, tol, callback, options)
        459     elif meth == 'dogleg':
        460         return _minimize_dogleg(fun, x0, args, jac, hess,
    --> 461                                 callback=callback, **options)
        462     elif meth == 'trust-ncg':
        463         return _minimize_trust_ncg(fun, x0, args, jac, hess, hessp,
    
    /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/scipy/optimize/_trustregion_dogleg.py in _minimize_dogleg(fun, x0, args, jac, hess, **trust_region_options)
         35     return _minimize_trust_region(fun, x0, args=args, jac=jac, hess=hess,
         36                                   subproblem=DoglegSubproblem,
    ---> 37                                   **trust_region_options)
         38 
         39 
    
    /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/scipy/optimize/_trustregion.py in _minimize_trust_region(fun, x0, args, jac, hess, hessp, subproblem, initial_trust_radius, max_trust_radius, eta, gtol, maxiter, disp, return_all, callback, **unknown_options)
        172         # has reached the trust region boundary or not.
        173         try:
    --> 174             p, hits_boundary = m.solve(trust_radius)
        175         except np.linalg.linalg.LinAlgError as e:
        176             warnflag = 3
    
    /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/scipy/optimize/_trustregion_dogleg.py in solve(self, trust_radius)
         96         # This is the optimum for the quadratic model function.
         97         # If it is inside the trust radius then return this point.
    ---> 98         p_best = self.newton_point()
         99         if scipy.linalg.norm(p_best) < trust_radius:
        100             hits_boundary = False
    
    /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/scipy/optimize/_trustregion_dogleg.py in newton_point(self)
         58             g = self.jac
         59             B = self.hess
    ---> 60             cho_info = scipy.linalg.cho_factor(B)
         61             self._newton_point = -scipy.linalg.cho_solve(cho_info, g)
         62         return self._newton_point
    
    /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/scipy/linalg/decomp_cholesky.py in cho_factor(a, lower, overwrite_a, check_finite)
        130     """
        131     c, lower = _cholesky(a, lower=lower, overwrite_a=overwrite_a, clean=False,
    --> 132                             check_finite=check_finite)
        133     return c, lower
        134 
    
    /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/scipy/linalg/decomp_cholesky.py in _cholesky(a, lower, overwrite_a, clean, check_finite)
         18 
         19     if check_finite:
    ---> 20         a1 = asarray_chkfinite(a)
         21     else:
         22         a1 = asarray(a)
    
    /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/numpy/lib/function_base.py in asarray_chkfinite(a, dtype, order)
       1213     if a.dtype.char in typecodes['AllFloat'] and not np.isfinite(a).all():
       1214         raise ValueError(
    -> 1215             "array must not contain infs or NaNs")
       1216     return a
       1217 
    
    ValueError: array must not contain infs or NaNs
    
  15. denadai2 commented on Mar 4, 2017

    @denadai2
    Author

    To add more info for you: if I directly use

    import pandas as pd
    features = ['pp']
    df = pd.read_csv('bug.csv')
    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, )
    res = model.fit(maxiter=2000, method="minimize")
    

    I have

    Warning: Desired error not necessarily achieved due to precision loss.
             Current function value: nan
             Iterations: 0
             Function evaluations: 1
             Gradient evaluations: 1
    
    /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/statsmodels-0.8.0-py3.4-macosx-10.6-intel.egg/statsmodels/discrete/discrete_model.py in summary(self, yname, xname, title, alpha, yname_list)
       2548         # for parameters, etc
       2549         smry.add_table_params(self, yname=yname_list, xname=xname, alpha=alpha,
    -> 2550                              use_t=self.use_t)
       2551 
       2552         if hasattr(self, 'constraints'):
    
    /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/statsmodels-0.8.0-py3.4-macosx-10.6-intel.egg/statsmodels/iolib/summary.py in add_table_params(self, res, yname, xname, alpha, use_t)
        859         if res.params.ndim == 1:
        860             table = summary_params(res, yname=yname, xname=xname, alpha=alpha,
    --> 861                                    use_t=use_t)
        862         elif res.params.ndim == 2:
        863 #            _, table = summary_params_2dflat(res, yname=yname, xname=xname,
    
    /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/statsmodels-0.8.0-py3.4-macosx-10.6-intel.egg/statsmodels/iolib/summary.py in summary_params(results, yname, xname, alpha, use_t, skip_header, title)
        443     else:
        444         params = results.params
    --> 445         std_err = results.bse
        446         tvalues = results.tvalues  #is this sometimes called zvalues
        447         pvalues = results.pvalues
    
    /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/statsmodels-0.8.0-py3.4-macosx-10.6-intel.egg/statsmodels/tools/decorators.py in __get__(self, obj, type)
         95         if _cachedval is None:
         96             # Call the "fget" function
    ---> 97             _cachedval = self.fget(obj)
         98             # Set the attribute in obj
         99             # print("Setting %s in cache to %s" % (name, _cachedval))
    
    /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/statsmodels-0.8.0-py3.4-macosx-10.6-intel.egg/statsmodels/base/model.py in bse(self)
       1056     @cache_readonly
       1057     def bse(self):
    -> 1058         return np.sqrt(np.diag(self.cov_params()))
       1059 
       1060     @cache_readonly
    
    /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/statsmodels-0.8.0-py3.4-macosx-10.6-intel.egg/statsmodels/base/model.py in cov_params(self, r_matrix, column, scale, cov_p, other)
       1131         if (cov_p is None and self.normalized_cov_params is None and
       1132             not hasattr(self, 'cov_params_default')):
    -> 1133             raise ValueError('need covariance of parameters for computing '
       1134                              '(unnormalized) covariances')
       1135         if column is not None and (r_matrix is not None or other is not None):
    
    ValueError: need covariance of parameters for computing (unnormalized) covariances  
    
  16. josef-pkt commented on Mar 4, 2017

    @josef-pkt
    Member

    I will try to look at it later today, but I'm going on a 4 day skiing trip tomorrow and I don't know if I will have time until later next week.

    What I was trying to do is to add access to the llnull options

            fit_kwds = dict(disp=0, warn_convergence=False, method='nm', 
                            maxiter=10000)
            fit_kwds.update(getattr(self, "_null_fit_kwds", {}))
            print("fit_kwds", fit_kwds)
            res_null = mod_null.fit(**fit_kwds)
    

    and compute the constant for the llnull model directly
    here's a gist with the notebook https://gist.github.com/josef-pkt/b45d0b5ceb3b692c17af5f77a657e639
    For trying out the llnull options I was just working from the "outside" which is messy, and needs proper access like set_llnull_options.

  17. denadai2 commented on Mar 4, 2017

    @denadai2
    Author

    thx

  18. denadai2 commented on Mar 5, 2017

    @denadai2
    Author

    What if llnull() passes "good" start_params from the full model, to fit the null model?

  19. denadai2 commented on Mar 10, 2017

    @denadai2
    Author

    in def llnull(self) I solved with:

    start = [np.mean(model.exog)]
    if hasattr(model, 'k_extra'):
        start.append(0.5)
    res_null = mod_null.fit(disp=0, warn_convergence=False, start_params=start,
                                maxiter=10000, method="nm")
    

    BUT I'm not sure it crashes with other models, so I can't push it. moreover, maybe it is just a silly trick

  20. josef-pkt commented on Mar 10, 2017

    @josef-pkt
    Member

    do you use mean exog or mean of endog?

    link.inverse(endog.mean()) is the right estimate for a constant only, but we need to handle offset and exposure, and MNLogit has multivariate endog which might need to be special cased.

    start = [np.mean(model.exog)] might only work by chance in the example.

  21. denadai2 commented on Mar 21, 2017

    @denadai2
    Author

    endog! anyway, I'll try to push it ASAP, then you can help me testing it :)

  22. added this to the 0.9 milestone on Jul 29, 2017
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