Skip to content

ENH/BUG Bootstrap clone rebased - #5143

Merged
josef-pkt merged 4 commits into
statsmodels:masterfrom
josef-pkt:bootstrap_clone_rebased
Sep 16, 2018
Merged

josef-pkt merged 4 commits into
statsmodels:masterfrom
josef-pkt:bootstrap_clone_rebased

Conversation

@josef-pkt

Copy link
Copy Markdown
Member

this is a rebased version of #4676

@josef-pkt

Copy link
Copy Markdown
Member Author

The notebook contains the output and needs to be removed, commit "DOC add example noexog GLLM notebook"

background=self.pdf_b)

res = llh_noexog.fit()
assert np.allclose(res.params, self.params, rtol=1e-1)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

use assert_allclose

@josef-pkt

Copy link
Copy Markdown
Member Author

aside: why are df_resid, df_model nan?

notebook: I prefer not to have dedented closing parenthesis.

@josef-pkt

Copy link
Copy Markdown
Member Author

AFAICS, notebook doesn't show usage of bootstrap cov_params/bse

@josef-pkt

Copy link
Copy Markdown
Member Author

The handling of exog=None in bootstrap looks good. It's just the minimal change without getting into the refactoring parts, see #4679 and discussion in original PR

@josef-pkt

Copy link
Copy Markdown
Member Author

we can squash into 3 parts:
changes to code
notebook
unit test

@josef-pkt

Copy link
Copy Markdown
Member Author

df_model, df_resid are nan:

there is an inconsistency between GenericLikelihoodModel and the results class

model.initialize has, i.e. attribute is always set

        if self.exog is not None:
            # assume constant
            er = np_matrix_rank(self.exog)
            self.df_model = float(er - 1)
            self.df_resid = float(self.exog.shape[0] - er)
        else:
            self.df_model = np.nan
            self.df_resid = np.nan

GenericLikelihoodModelResults.__init__ uses hasattr, i.e. we never get to the else part to set df_model equal to len(params)

        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

        if hasattr(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

df_resid does not affect params_table by default using use_t=False.
It shows up in summary where formatting is fixed in this PR
It is also required for t_test (but I don't remember if we only need the attribute or if it needs to have a non-nan value.)
It should also be needed for nested hypothesis test when df_constraints = diff of df_resid, but that might not be implemented for GenericLikelihoodModelResults.

])
('Df Residuals:', lambda: [num_to_str(results.df_resid)]),
# ('Df resid:', lambda: [results.df_resid]),
# ('df resid:', lambda: [results.df_resid]), #check capitalization

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Commented out versions necessary?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Commented out versions necessary?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't know. postponed and new open issue for reviewing GenericLikelihoodModel.
this PR makes the minimal changes to fix the bug to get it to work.

self.signal = signal
self.background = background
super(TwoPeakLLHNoExog, self).__init__(endog=endog, exog=exog,
*args, **kwargs)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Indentation

res_bs = res.bootstrap(nrep=50)
assert res_bs is not None
smry = res.summary()
assert smry is not None

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this useful?

@josef-pkt

Copy link
Copy Markdown
Member Author

I think there is a (theoretical) problem with the notebook example:
There is one parameter too many, is there?
The two parameters are mixing probabilities, but they should sum to a constant/one, so we only have one of them.
bootstrap params correlation

np.corrcoef(params_boot.T)
array([[ 1., -1.],
       [-1.,  1.]])

but the actual params estimates reflect the counts 30, 1000
bootstrap cov_params are far away from asymptotic cov_params

Something is strange,

@coveralls

coveralls commented Sep 8, 2018 •

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.03%) to 84.064% when pulling f68ca0b on josef-pkt:bootstrap_clone_rebased into 0c54c49 on statsmodels:master.

@codecov

codecov Bot commented Sep 8, 2018

Copy link
Copy Markdown

Codecov Report

Merging #5143 into master will increase coverage by 0.01%.
The diff coverage is 92.85%.

Impacted file tree graph

@@            Coverage Diff             @@
##           master    #5143      +/-   ##
==========================================
+ Coverage   81.41%   81.42%   +0.01%     
==========================================
  Files         582      582              
  Lines       90331    90386      +55     
  Branches    10107    10110       +3     
==========================================
+ Hits        73545    73600      +55     
+ Misses      14488    14481       -7     
- Partials     2298     2305       +7
Impacted Files Coverage Δ
statsmodels/iolib/summary.py 54.79% <100%> (+0.62%) ⬆️
statsmodels/base/model.py 87.02% <50%> (+1.72%) ⬆️
statsmodels/miscmodels/tests/test_generic_mle.py 97.65% <95.83%> (-1.1%) ⬇️
statsmodels/regression/mixed_linear_model.py 88.97% <0%> (-0.8%) ⬇️

Continue to review full report at Codecov.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update 25ebae9...8d87738. Read the comment docs.

@josef-pkt

josef-pkt commented Sep 8, 2018 •

Copy link
Copy Markdown
Member Author

I want to remove the doc notebook from this PR. My guess is that there is something wrong in the model or likelihood. The parameter estimates are fine and bootstrap works, but the hessian doesn't look correct for this problem.
Reparameterization to us n_signal and n_total as parameters makes the two parameters less correlated, using fraction and n_total would make it them pretty orthogonal.
However, n_total is just a estimate of nobs with very small bse 3e-5 in bootstrap but much larger bse=32 according to hessian. However, the bse for n_signal agree closely in this parameterization

bse_boot
array([  8.92083745e+00,   2.99404115e-05])

res.bse
array([  8.91235208,  32.09361211])

We cannot use an M-estimator, misspecified loglike cov_type because score_obs and/or loglike_obs is missing.

As a unit test case the example is fine, but I don't want to provide as a user example in the docs, when something is not clear or appropriate in the example.

(Another problem to make it clean is the support of the uniform distribution. My guess is that including the counts/nobs/n_total is to scale up the uniform pdf so the pdf of the uniform distribution is not closely tied to the support of it, i.e. uniform measure instead of uniform distribution.
Using the upper support, i.e. 1 / pdf of uniform might be another way. Standard MLE smooth asymptotics will not apply directly, but bootstrap might still work well.)

@josef-pkt

josef-pkt commented Sep 8, 2018 •

Copy link
Copy Markdown
Member Author

update: I added nloglikeobs method to get hc0, which is much closer to, even smaller than, bse_boot for n_total

res.bsejhj
array([  8.85731641e+00,   5.18898493e-07])

res_hc0.bse   # using fit(cov_type='hc0')
array([  8.85731641e+00,   5.17198070e-07])

bse_boot
array([  8.92083745e+00,   2.99404115e-05])

my current conclusion: The objective function works as M-estimator but is not a proper log-likelihood function.

@josef-pkt

josef-pkt commented Sep 10, 2018 •

Copy link
Copy Markdown
Member Author

checking current unit test

statsmodels.miscmodels.tests.test_generic_mle TestMyPareto1 which uses constraints is None
MyPareto has no exog
if I call bootstrap, then I get a different error
AttributeError: 'MyPareto' object has no attribute 'fixed_params'

my guess is that this is related to missing _init_keys or the current bootstrap cloneattr
The constrained handling is part of the user class, i.e. MyPareto.

using TestMyParetoRestriction
My first tries to fix MyPareto to get bootstrap with constraints to work are failing.
Also in bootstrap I get a lot of convergence failures or HessianInversionWarnings.
It looks like recreating the model in bootstrap is not picking up the constraint.

correction: I printed out the bootstrap results for the wrong model, i.e. for unconstrained. constrained bootstrap does have the reduced number of params

@josef-pkt

josef-pkt commented Sep 11, 2018 •

Copy link
Copy Markdown
Member Author

bootstrap for scale parameter in MyPareto with loc restriction looks not very normal
e.g. robust mad looks pretty different from bse_boots
asymptotic bse in model for scale is 4.89e-06

image

to qualify: data generating scale = 2
bse for scale is in the order of 1e-5 (asy), 1e-9 (mad boot) or 0.002 (bse_boot), i.e. pretty irrelevant in practical terms.
(nobs=500, bootstrap nrep=1000 but similar features for nobs=100)

@josef-pkt
josef-pkt force-pushed the bootstrap_clone_rebased branch from 8d87738 to 19fa94e Compare September 12, 2018 19:56
@josef-pkt

Copy link
Copy Markdown
Member Author

I copied the notebook to https://gist.github.com/josef-pkt/892fd3a6048cf55790a66e152ba3cc7d
and will delete it from here
It disappeared from this PR after interactive rebase

now squashed to 3 commits.

  • bug-fix
  • allow nan in summary
  • unit tests

@josef-pkt

Copy link
Copy Markdown
Member Author

test is missing random seed in method (class has seed but not the test method with bootstrap)

@josef-pkt
josef-pkt force-pushed the bootstrap_clone_rebased branch from c29f2f4 to f68ca0b Compare September 15, 2018 02:26
@josef-pkt

Copy link
Copy Markdown
Member Author

All green,

I'm leaving the writing of nice examples for another day. E.g. expanding on MyPareto

@josef-pkt
josef-pkt merged commit a146631 into statsmodels:master Sep 16, 2018
Comment thread statsmodels/base/model.py
results = []
print(self.model.__class__)
hascloneattr = True if hasattr(self, 'cloneattr') else False
hascloneattr = True if hasattr(self.model, 'cloneattr') else False

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is cloneattr documented somewhere?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, it's not advertised.
discussion in the original PR

endog = self.endog
return self.nlnlike(params, endog)

def nlnlike(self, params, endog):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why defining both this and nloglike?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

small advantage, nlnlike can be used with different endog

but essentially I didn't rewrite the example in the unit test.
I have a partial rewrite in my notebook, for the future.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants