Skip to content

BUG: GenericLikelihood Results hasattr for df_resid is always true, s… - #8476

Merged
josef-pkt merged 3 commits into
statsmodels:mainfrom
josef-pkt:fix_genericMLE_dfresid
Oct 31, 2022
Merged

josef-pkt merged 3 commits into
statsmodels:mainfrom
josef-pkt:fix_genericMLE_dfresid

Conversation

@josef-pkt

Copy link
Copy Markdown
Member

This fixes the immediate issue in #8475

no unit tests yet for it
df_model does not take into account that we have nonzero k_null.
see #8475 (comment)

There might still be other related problems for other, similar subclasses of GenericLikelihoodModel.

@josef-pkt

Copy link
Copy Markdown
Member Author

one unit test fails, check that df_resid is nan

self = <statsmodels.miscmodels.tests.test_generic_mle.TestTwoPeakLLHNoExog object at 0x7f2cd786e8b0>

    def test_fit(self):
        np.random.seed(42)
        llh_noexog = TwoPeakLLHNoExog(self.X,
                                      signal=self.pdf_a,
                                      background=self.pdf_b)
    
        res = llh_noexog.fit()
        assert_allclose(res.params, self.params, rtol=1e-1)
        # TODO: nan if exog is None,
>       assert_(np.isnan(res.df_resid))
E       AssertionError

statsmodels/miscmodels/tests/test_generic_mle.py:228: AssertionError

That test was added in PR #5143
This might be a good test case for this PR. 2 constant parameters,
Looks like a parametric deconvolution of 2 distributions, signal and background. Kind of, the estimate seems to be the number of observations in signal and number of observations in background.
issue and PR was for allowing bootstrap if exog is None.

@josef-pkt

josef-pkt commented Oct 29, 2022 •

Copy link
Copy Markdown
Member Author

more problems
df_resid in miscmodels PoissonZIGMLE does not include k_extra in my current version and raises warning "df_resid differs from nobs - k_params"

I'm not sure yet if df_resid should subtract k_extra in 0.14

Similarly miscmodels.tmodel.TLinearModel has df_resid without k_extra
In unrestricted MLE model k_extra should be 2 (degrees of freedom and scale)

@josef-pkt
josef-pkt force-pushed the fix_genericMLE_dfresid branch from 2a26b34 to 2fa33aa Compare October 31, 2022 15:09
@josef-pkt

josef-pkt commented Oct 31, 2022 •

Copy link
Copy Markdown
Member Author

Warning, backwards incompatible change in definition:

This changes now the definition of df_model to, essentially, k_params - k_constant - k_extra, i.e. only slope coefficients and not constant and extra parameters.

This also changes in OrderedModel. Other changes affect subclasses of GenericLikelihoodModel in miscmodels.
e.g. constant parameter distribution models, like Pareto, have df_model = 0. i.e. the model is a "null model".
considered as bug-fix
closes #8482

@josef-pkt

Copy link
Copy Markdown
Member Author

needs a note in release notes
also warning that some models in discrete (NB, GP) will be affected by this change in definition in the following release 0.15

@josef-pkt

Copy link
Copy Markdown
Member Author

two new failures with latest change
two subclasses of GenericLikelihoodModel outside of miscmodel

unit tests for aic fail, i.e. those aic are not robust to redefinition of df_model


2022-10-31T15:42:59.2891032Z _______________________ TestDiscretizedGammaEx.test_all ________________________
2022-10-31T15:42:59.2892396Z [gw0] linux -- Python 3.9.15 /opt/hostedtoolcache/Python/3.9.15/x64/bin/python
2022-10-31T15:42:59.2892951Z 
2022-10-31T15:42:59.2893597Z self = <statsmodels.distributions.tests.test_discrete.TestDiscretizedGammaEx object at 0x7fbc9c3ca550>
2022-10-31T15:42:59.2894145Z 
2022-10-31T15:42:59.2894631Z     def test_all(self):
2022-10-31T15:42:59.2895229Z         # expand frequencies to observations, (no freq_weights yet)
2022-10-31T15:42:59.2895817Z         freq = [46, 76, 24, 9, 1]
2022-10-31T15:42:59.2896372Z         y = np.repeat(np.arange(5), freq)
2022-10-31T15:42:59.2896946Z         # results from article table 7
2022-10-31T15:42:59.2897466Z         res1 = Bunch(
2022-10-31T15:42:59.2898004Z             params=[3.52636, 0.425617],
2022-10-31T15:42:59.2898722Z             llf=-187.469,
2022-10-31T15:42:59.2899286Z             chi2=1.701208,  # chisquare test
2022-10-31T15:42:59.2900201Z             df_model=2,
2022-10-31T15:42:59.2900961Z             p=0.4272,  # p-value for chi2
2022-10-31T15:42:59.2901558Z             aic=378.938,
2022-10-31T15:42:59.2902139Z             probs=[46.48, 73.72, 27.88, 6.5, 1.42])
2022-10-31T15:42:59.2902685Z     
2022-10-31T15:42:59.2903230Z         dp = DiscretizedCount(stats.gamma)
2022-10-31T15:42:59.2903828Z         mod = DiscretizedModel(y, distr=dp)
2022-10-31T15:42:59.2904439Z         res = mod.fit(start_params=[1, 1])
2022-10-31T15:42:59.2905005Z         nobs = len(y)
2022-10-31T15:42:59.2905503Z     
2022-10-31T15:42:59.2906259Z         assert_allclose(res.params, res1.params, rtol=1e-5)
2022-10-31T15:42:59.2907378Z         assert_allclose(res.llf, res1.llf, atol=6e-3)
2022-10-31T15:42:59.2908227Z >       assert_allclose(res.aic, res1.aic, atol=6e-3)
2022-10-31T15:42:59.2908857Z E       AssertionError: 
2022-10-31T15:42:59.2909614Z E       Not equal to tolerance rtol=1e-07, atol=0.006
2022-10-31T15:42:59.2910207Z E       
2022-10-31T15:42:59.2910738Z E       Mismatched elements: 1 / 1 (100%)
2022-10-31T15:42:59.2911436Z E       Max absolute difference: 4.00098586
2022-10-31T15:42:59.2912044Z E       Max relative difference: 0.01055842
2022-10-31T15:42:59.2912617Z E        x: array(382.938986)
2022-10-31T15:42:59.2913172Z E        y: array(378.938)
2022-10-31T15:42:59.2913562Z 
2022-10-31T15:42:59.2914190Z statsmodels/distributions/tests/test_discrete.py:434: AssertionError
2022-10-31T15:42:59.2918429Z ----------------------------- Captured stdout call -----------------------------
2022-10-31T15:42:59.2918982Z Optimization terminated successfully.
2022-10-31T15:42:59.2919398Z          Current function value: 1.201728
2022-10-31T15:42:59.2919782Z          Iterations: 55
2022-10-31T15:42:59.2920145Z          Function evaluations: 103
2022-10-31T15:42:59.2920636Z ___________________________ TestBetaMeth.test_basic ____________________________
2022-10-31T15:42:59.2921374Z [gw1] linux -- Python 3.9.15 /opt/hostedtoolcache/Python/3.9.15/x64/bin/python
2022-10-31T15:42:59.2921708Z 
2022-10-31T15:42:59.2922134Z self = <statsmodels.othermod.tests.test_beta.TestBetaMeth object at 0x7f1ce533c580>
2022-10-31T15:42:59.2922474Z 
2022-10-31T15:42:59.2922790Z     def test_basic(self):
2022-10-31T15:42:59.2923151Z         res1 = self.res1
2022-10-31T15:42:59.2923491Z         res2 = self.res2
2022-10-31T15:42:59.2923805Z     
2022-10-31T15:42:59.2924103Z         k_mean = 4
2022-10-31T15:42:59.2924473Z         p, se, zv, pv = res2.table_mean.T
2022-10-31T15:42:59.2925089Z         assert_allclose(res1.params[:k_mean], p, rtol=1e-6)
2022-10-31T15:42:59.2925781Z         assert_allclose(res1.bse[:k_mean], se, rtol=1e-6)
2022-10-31T15:42:59.2926470Z         assert_allclose(res1.tvalues[:k_mean], zv, rtol=1e-6)
2022-10-31T15:42:59.2927265Z         assert_allclose(res1.pvalues[:k_mean], pv, rtol=1e-5)
2022-10-31T15:42:59.2927812Z     
2022-10-31T15:42:59.2928181Z         p, se, zv, pv = res2.table_precision.T
2022-10-31T15:42:59.2928791Z         assert_allclose(res1.params[k_mean:], p, rtol=1e-6)
2022-10-31T15:42:59.2929439Z         assert_allclose(res1.bse[k_mean:], se, rtol=1e-6)
2022-10-31T15:42:59.2930078Z         assert_allclose(res1.tvalues[k_mean:], zv, rtol=1e-6)
2022-10-31T15:42:59.2930739Z         assert_allclose(res1.pvalues[k_mean:], pv, rtol=1e-5)
2022-10-31T15:42:59.2931141Z     
2022-10-31T15:42:59.2931675Z         assert_allclose(res1.llf, res2.loglik, rtol=1e-10)
2022-10-31T15:42:59.2932315Z >       assert_allclose(res1.aic, res2.aic, rtol=1e-10)
2022-10-31T15:42:59.2932739Z E       AssertionError: 
2022-10-31T15:42:59.2933288Z E       Not equal to tolerance rtol=1e-10, atol=0
2022-10-31T15:42:59.2933665Z E       
2022-10-31T15:42:59.2934025Z E       Mismatched elements: 1 / 1 (100%)
2022-10-31T15:42:59.2934427Z E       Max absolute difference: 4.
2022-10-31T15:42:59.2934827Z E       Max relative difference: 0.02037738
2022-10-31T15:42:59.2935368Z E        x: array(-192.296057)
2022-10-31T15:42:59.2935893Z E        y: array(-196.296057)

@josef-pkt

Copy link
Copy Markdown
Member Author

both DiscretizedModel and BetaModel explicitly define df_model in __init__, both as number of parameters, possibly minus constant.
That is it uses the "wrong" definition, not the new convention as k_params - k_null

df_resid is explicitly set as nobs - number of params

So, we just need to redefine df_model in those 2 models, and we need to add k_extra

aic is inherited from GenericLikelihoodModelResults and Resultsmixin

it uses the old df_modelwc in which I now also include k_extra: self.df_model + hasconst + k_extra

def aic(self):
        """Akaike information criterion"""
        return -2 * self.llf + 2 * (self.df_modelwc)

@josef-pkt
josef-pkt force-pushed the fix_genericMLE_dfresid branch from 2fa33aa to 7c875e4 Compare October 31, 2022 17:01
@josef-pkt

Copy link
Copy Markdown
Member Author

rerunning an old weibull, aft survival model notebook, try_aft_weibull_updated.ipynb
(minor updates for lifelines/pandas backwards incompatibilities)

Two ways to define df_model and df_resid to fix warnings about df mismatch

  • explicitly define df_model, k_extra and df_resid in __init__
  • use extra_params_names in super().__init__ call

Results look correct with either method.
Note, extra parameters are constant as in NBP, those versions are not multi-link models.

@josef-pkt

Copy link
Copy Markdown
Member Author

unit tests are green

1 pep-8/flake failure
statsmodels/miscmodels/tests/test_generic_mle.py:14:1: F401 'numpy.testing.assert_' imported but unused
I switched to pytest plain assert instead of numpy assert

looks almost ready to merge

@josef-pkt

Copy link
Copy Markdown
Member Author

something like this for the release notes:

The definition of model degrees of freedom, df_model, has changed in GenericLikelihoodModel and its subclasses and bugs and inconsistencies have been removed. df_model is now defined as the excess number of parameters over the null model. The null model is defined as constant only parameters. This means df_model now only counts slope parameters but does not include extra shape or scale parameters.
A similar redefinition will be applied to discrete models with extra parameters in the next version of statsmodels (0.15).
Note, this redefinition should not affect results statistics like aic because those use the total number of estimated parameters.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant