Skip to content

BUG: GLM fit property llnull incorrect when model includes varying exposure #6953

Closed

Description

@arkhanna

Describe the bug

The llnull property of GLMResults objects is documented to provide "Log-likelihood of the model fit with a constant as the only regressor." However, if the model was fit with (non-constant) exposure, the llnull value provided is incorrect as it gives the log-likelihood of the null model assuming a constant exposure. (This would suggest that the null model constructed and fit to provide this value fails to pass the exposures.) I believe the null model should be fit with the same exposures as the original model and llnull should be the log likelihood of the null model with the same exposures.

Code Sample, a copy-pastable example if possible

from scipy.stats import poisson
import numpy as np
import statsmodels.api as sm

x0 = [np.sin(i/20)+2 for i in range(1000)]
exposure = np.random.randint(100,200, size=1000)  # Variable exposures for each observation
y = [np.sum(poisson.rvs(mu=x, size=e)) for x,e in zip(x0, exposure)]
X = add_constant(x0)

model = sm.GLM(endog=y, exog=X, exposure=exposure, family=sm.families.Poisson()).fit()
null_model = sm.GLM(endog=y, exog=X[:,0], exposure=exposure, family=sm.families.Poisson()).fit()
null_model_without_exposure = sm.GLM(endog=y, exog=X[:,0], family=sm.families.Poisson()).fit()

print('Model LL-Null: {}'.format(model.llnull))
print('Null Model LL: {}'.format(null_model.llf))
print('Null Model w/o Exposure LL: {}'.format(null_model_without_exposure.llf))

Expected Output

We expect model.llnull to be equal to null_model.llf.

Observed Output

But instead, we see model.llnull is equal to null_model_without_exposure.llf:

# Observed output
Model LL-Null: -29535.63477012838
Null Model LL: -23814.49858149883
Null Model w/o Exposure LL: -29535.6347701283

Output of import statsmodels.api as sm; sm.show_versions()

Details
INSTALLED VERSIONS
------------------
Python: 3.7.6.final.0
OS: Darwin 19.5.0 Darwin Kernel Version 19.5.0: Thu Apr 30 18:25:59 PDT 2020; root:xnu-6153.121.1~7/RELEASE_X86_64 x86_64
byteorder: little
LC_ALL: None
LANG: None

statsmodels
===========

Installed: 0.12.0.dev0+542.gf378da1ec (/Users/---/lib/python3.7/site-packages/statsmodels)

Required Dependencies
=====================

cython: Not installed
numpy: 1.18.1 (/Users/---/lib/python3.7/site-packages/numpy)
scipy: 1.4.1 (/Users/---/lib/python3.7/site-packages/scipy)
pandas: 1.0.1 (/Users/---/lib/python3.7/site-packages/pandas)
    dateutil: 2.8.1 (/Users/---/lib/python3.7/site-packages/dateutil)
patsy: 0.5.1 (/Users/---lib/python3.7/site-packages/patsy)

Optional Dependencies
=====================

matplotlib: 3.1.3 (/Users/---/python3.7/site-packages/matplotlib)
    backend: module://ipykernel.pylab.backend_inline 
cvxopt: Not installed
joblib: 0.14.1 (/Users/---/python3.7/site-packages/joblib)

Developer Tools
================

IPython: 7.12.0 (/Users/---/lib/python3.7/site-packages/IPython)
    jinja2: 2.11.1 (/Users/---/python3.7/site-packages/jinja2)
sphinx: 2.4.0 (/Users/---/python3.7/site-packages/sphinx)
    pygments: 2.5.2 (/Users/---/python3.7/site-packages/pygments)
pytest: 5.4.2 (/Users/---/python3.7/site-packages/pytest)
virtualenv: Not installed

Activity

  1. added
    type-bug-wrong
    on Aug 6, 2020
  2. josef-pkt commented on Aug 6, 2020

    @josef-pkt
    Member

    Thanks for the report

    looks serious.
    There is code in GLMResults.null that is supposed to handle this case.

    I don't see any problem with the code yet.

  3. josef-pkt commented on Aug 6, 2020

    @josef-pkt
    Member

    Found the bug

    in GLMResults.null

            if hasattr(self, '_offset_exposure'):
                return GLM(endog, exog, family=self.family,
                           **kwargs).fit().fittedvalues
    

    should check the model not the results instance

            if hasattr(self.model, '_offset_exposure'):
                return GLM(endog, exog, family=self.family,
                           **kwargs).fit().fittedvalues
    

    so it always takes the else path which assumes constant offset and exposure.

    the same bug should occure if offset is used.

  4. josef-pkt commented on Aug 6, 2020

    @josef-pkt
    Member

    That change fixes llnull in the example

    bug introduced in #4601 while fixing other bugs with llnull

    need test cases with varying offset and varying exposure
    the if branch has no test coverage
    https://coveralls.io/builds/32583777/source?filename=statsmodels%2Fgenmod%2Fgeneralized_linear_model.py#L1638

  5. added this to the 0.12 milestone on Aug 6, 2020
  6. bashtage commented on Aug 7, 2020

    @bashtage
    Member

    All GLM have _offset_exposure defined in __init__. What model would not have this attribute? Is the else even needed?

  7. bashtage commented on Aug 7, 2020

    @bashtage
    Member

    I merged the fix in but still needs a test. I didn't see how one could hit both paths.

  8. added a commit that references this issue on Aug 7, 2020
  9. bashtage commented on Aug 7, 2020

    @bashtage
    Member

    Test in #6959 from code above. It only hits the if path. I think the else path is unhittable, and so should be removed.

  10. bashtage commented on Aug 7, 2020

    @bashtage
    Member

    Reopening to see if @josef-pkt knows if the else branch can be hit.

  11. josef-pkt commented on Aug 7, 2020

    @josef-pkt
    Member

    I will look at it again today.

    I'm not sure the else path is worth the effort. If it is, then we would have to adjust the if condition to check that offset_exposure is user provided or not constant.

  12. modified the milestones: 0.12, 0.13 on Apr 6, 2021
  13. josef-pkt commented on Jul 11, 2021

    @josef-pkt
    Member

    llnull needs more code review across models when extra options are used

    note:

    • GLMResults llnull uses scale of results from full model self.scale
    • null deviance does not include scale

    check test coverage for models that don't have fixed scale=1, e.g. gaussian, gamma

  14. josef-pkt commented on Sep 3, 2021

    @josef-pkt
    Member

    I'm enabling the WLS case for the null model again in #7682.
    That version has the advantage of handling perfect prediction without raising an exception.

    new issue for review and refactoring of GLM null model

    closing this, original bug has been fixed in #6957

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

    comp-genmodprio-elevtype-bug-wrong

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions