Skip to content

BUG: default df_resid, df_model in GenericLikelihoodModel #8475

Closed

Description

@josef-pkt

It looks like the current GenericLikelihoodModel does not set df_resid, df_model correctly.
see also #7767 and #7759 for df and #4679 for more refactoring

I converted an old gist from a blog article to work with current version.
It uses GenericLikelihoodModel for ZIP (without regressors)
https://www.austinrochford.com/posts/2015-03-03-mle-python-statsmodels.html

my notebook for checking this is mle_custom_zip.ipynb

fitting the model emits warnings

...statsmodels\base\model.py:2733: UserWarning: df_model + k_constant differs from nparams
  warnings.warn("df_model + k_constant differs from nparams")
...statsmodels\statsmodels\base\model.py:2735: UserWarning: df_resid differs from nobs - nparams
  warnings.warn("df_resid differs from nobs - nparams")

and df_resid, df_model are wrong

N, model.df_resid, model.df_model, results.df_resid, results.df_model
(1000, 1000.0, -1.0, 1000.0, -1.0)

The model code does not set anything related to df_xxx,

class ZeroInflatedPoisson(GenericLikelihoodModel):
    def __init__(self, endog, exog=None, **kwds):
        if exog is None:
            exog = np.zeros_like(endog)
            
        super(ZeroInflatedPoisson, self).__init__(endog, exog, **kwds)
    
    def nloglikeobs(self, params):
        pi = params[0]
        lambda_ = params[1]

        return -np.log(zip_pmf(self.endog, pi=pi, lambda_=lambda_))
    
    def fit(self, start_params=None, maxiter=10000, maxfun=5000, **kwds):
        if start_params is None:
            lambda_start = self.endog.mean()
            excess_zeros = (self.endog == 0).mean() - stats.poisson.pmf(0, lambda_start)
            
            start_params = np.array([excess_zeros, lambda_start])
            
        return super(ZeroInflatedPoisson, self).fit(start_params=start_params,
                                                    maxiter=maxiter, maxfun=maxfun, **kwds)

One guess for the bug is that the model code specifies neither n_params/k_params, nor a start_params with correct len.
using explicit start_params does not help. The __init__ does not seem to have an option to set k_params.

I guess there is some problem also if exog=None.

fit sets the _set_extra_params_names correctly, but does not change df_xxx.

Activity

  1. added this to the 0.14 milestone on Oct 28, 2022
  2. josef-pkt commented on Oct 28, 2022

    @josef-pkt
    MemberAuthor

    likely problem

    GenericLikelihoodModelResults has

            if hasattr(model, 'df_model'):
                self.df_model = model.df_model
            else:
                self.df_model = len(mlefit.params)
                # retrofitting the model, used in t_test TODO: check design
                self.model.df_model = self.df_model
    

    hasattr might never apply,
    creating the model will always set df_resid, df_model, but they could be nan if exog is None.

    However exog is a column of zeros even though it is not used (except for k_params, df_xxx setting)

    model2 = ZeroInflatedPoisson(x)
    model2.df_resid
    1000.0
    model2.df_model
    -1.0
    model2.exog.shape, model.exog.mean(), model.exog.var()
    ((1000, 1), 0.0, 0.0)
    
  3. josef-pkt commented on Oct 28, 2022

    @josef-pkt
    MemberAuthor

    more experimenting:

    If df_resid depends on exog, then it is correct:

    exog=np.zeros((N, 2))   # rank is zero, no change for df_xxx
    exog=np.ones((N, 2))   # rank is one, df_resid decreases by one, df_model=0
    exog=np.random.randn(N, 2)   # rank is one, df_resid decreases by two, df_model=1
    
    model2 = ZeroInflatedPoisson(x, exog=exog) # no effect for df_xxx: hasconst=False) #, nparams=2)
    

    using extra_params_names does not help for df_resid

    model2 = ZeroInflatedPoisson(x, extra_params_names=["pi", "lambda"])
    results2 = model2.fit()
    N, model2.df_resid, model2.df_model, results2.df_resid, results2.df_model
    
    Optimization terminated successfully.
             Current function value: 1.586641
             Iterations: 37
             Function evaluations: 70
    ...\statsmodels\statsmodels\base\model.py:1031: ValueWarning: more exog_names than parameters
      warnings.warn('more exog_names than parameters', ValueWarning)
    
    (1000, 1000.0, -1.0, 1000.0, -1.0)
    
  4. josef-pkt commented on Oct 28, 2022

    @josef-pkt
    MemberAuthor

    back to hasattr in Generic Results class:

    I just realized that setting exog to column of zeros is in custom code, i.e. user defined subclass.
    When I drop this, then I get the nan in model.df_resid and model.df_model

    model2 = ZeroInflatedPoisson(x, extra_params_names=["pi", "lambda"])
    results2 = model2.fit()
    N, model2.df_resid, model2.df_model, results2.df_resid, results2.df_model
    Optimization terminated successfully.
             Current function value: 1.586641
             Iterations: 37
             Function evaluations: 70
    (1000, nan, nan, nan, nan)
    
    # with start_params, no effect
    model2 = ZeroInflatedPoisson(x, extra_params_names=["pi", "lambda"])
    results2 = model2.fit(start_params=np.array([0.5, 2]))
    N, model2.df_resid, model2.df_model, results2.df_resid, results2.df_model
    Optimization terminated successfully.
             Current function value: 1.586641
             Iterations: 36
             Function evaluations: 69
    (1000, nan, nan, nan, nan)
    
    repr(model2.exog)
    'None'
    

    This means that the hasattr check needs to be replaced or combined with a nan check in GenericLikelihoodModelResults.__init__

    To confirm that the hasattr check works, if I del the two df_xxx, then the df are correctly set.

    '
    model2 = ZeroInflatedPoisson(x, extra_params_names=["pi", "lambda"])
    del model2.df_resid
    del model2.df_model
    results2 = model2.fit(start_params=np.array([0.5, 2]))
    N, model2.df_resid, model2.df_model, results2.df_resid, results2.df_model
    
    Optimization terminated successfully.
             Current function value: 1.586641
             Iterations: 36
             Function evaluations: 69
    (1000, 998, 2, 998, 2)
    

    One remaining (old) problem, df_model and hasconst.
    by default the code often assumes hasconst is true and we have one constant.
    see df_model should be excess compared to df_null. issue ?

  5. josef-pkt commented on Oct 28, 2022

    @josef-pkt
    MemberAuthor

    adding the nan check, df_resid works correctly in the example case

            if hasattr(model, 'df_resid') and not np.isnan(model.df_resid):
                self.df_resid = model.df_resid
            else:
                self.df_resid = self.endog.shape[0] - self.df_model
                # retrofitting the model, used in t_test TODO: check design
                self.model.df_resid = self.df_resid
    

    However, df_model will be 2 in this case, i.e. the same as k_params.
    However, if we add df_null or k_null, and define df_model as number of "excess" parameters, df_model = k_params - k_null, then df_model should be zero in this case.

    BetaReg seems to define df_model currently as self.df_model = self.nparams - 1
    see #7584 (comment) and related comments

  6. josef-pkt commented on Oct 28, 2022

    @josef-pkt
    MemberAuthor

    case 1 exog, 1 extra parameter:
    df_resid subtracts only 1 parameter, i.e. the exog parameters

    AFAICS, there is no k_extra handling in generic MLE as in discrete negbin, GPP, ...
    Asides:
    base.model has k_extra only in LikelihoodModel._fit_zeros
    LikelihoodModel also has _fit_collinear which I have not use in years and is, I guess, not advertised at all.

    model2 = ZeroInflatedPoisson(x, exog=np.ones(N), extra_params_names=["lambda"])
    results2 = model2.fit()
    N, model2.df_resid, model2.df_model, results2.df_resid, results2.df_model, model2.exog_names
    Optimization terminated successfully.
             Current function value: 1.586641
             Iterations: 37
             Function evaluations: 70
    (1000, 999.0, 0.0, 999.0, 0.0, ['const', 'lambda'])
    

    compared to discrete count models: NBP, GPP

    AFAICS, exog_extra is handled in individual results methods like aic, but does not affect df_model.
    That means extra params are correctly excluded from the model excess over the Null model, e.g. in llr_pvalue.
    But we don't have generic code based on k_params, i.e. the number of all estimated parameters.
    I don't see (yet) in the code if or where k_extra is included in df_resid computation.

  7. josef-pkt commented on Oct 28, 2022

    @josef-pkt
    MemberAuthor

    nparams is set in GenericLikelihoodModel._set_extra_params_names based on len(self.exog_names). It only applies if the user provides extra_params_names
    However, AFAIR, nparams is not really used anymore. (It was an idea that didn't take hold yet. Newer convention is k_params.)

    example previous model has correct nparams

    model2.nparams
    2
    

    we can add setting k_extra in the same or similar way.

  8. changed the title [-]BUG: default df_resid in GenericLikelihoodModel[/-] [+]BUG: default df_resid, df_model in GenericLikelihoodModel[/+] on Oct 31, 2022
  9. josef-pkt commented on Dec 5, 2022

    @josef-pkt
    MemberAuthor

    one more

    unit test run on azur has warnings for copula models

    statsmodels/distributions/copula/tests/test_model.py::TestEVHR::test
    statsmodels/distributions/copula/tests/test_model.py::TestEVAsymMixed::test
    statsmodels/distributions/copula/tests/test_model.py::TestEVAsymLogistic::test
    statsmodels/distributions/copula/tests/test_model.py::TestFrank::test
    statsmodels/distributions/copula/tests/test_model.py::TestGaussian::test
    statsmodels/distributions/copula/tests/test_model.py::TestClayton::test
    statsmodels/distributions/copula/tests/test_model.py::TestGumbel::test
      /home/vsts/work/1/s/statsmodels/base/model.py:2741: UserWarning: df_model + k_constant + k_extra differs from k_params
        warnings.warn("df_model + k_constant + k_extra "
    
    statsmodels/distributions/copula/tests/test_model.py::TestEVHR::test
    statsmodels/distributions/copula/tests/test_model.py::TestEVAsymMixed::test
    statsmodels/distributions/copula/tests/test_model.py::TestEVAsymLogistic::test
    statsmodels/distributions/copula/tests/test_model.py::TestFrank::test
    statsmodels/distributions/copula/tests/test_model.py::TestGaussian::test
    statsmodels/distributions/copula/tests/test_model.py::TestClayton::test
    statsmodels/distributions/copula/tests/test_model.py::TestGumbel::test
      /home/vsts/work/1/s/statsmodels/base/model.py:2745: UserWarning: df_resid differs from nobs - k_params
        warnings.warn("df_resid differs from nobs - k_params")
    
  10. bashtage commented on Jul 30, 2026

    @bashtage
    Member

    Fixed by PR #8476 (same PR as #8482): added NaN checks and k_extra bookkeeping, with a regression test in test_generic_mle.py::TestTwoPeakLLHNoExog::test_fit confirming correct df_resid/df_model values. Closing as fixed.

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

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions