Skip to content

WIP: formula_info as model argument, was: Ordinal model rebased - #7021

Open
josef-pkt wants to merge 17 commits into
statsmodels:mainfrom
josef-pkt:ordinal_model_rebased
Open

josef-pkt wants to merge 17 commits into
statsmodels:mainfrom
josef-pkt:ordinal_model_rebased

Conversation

@josef-pkt

Copy link
Copy Markdown
Member

rebased version of #6982 , based on PR #2600 and issue #807

@josef-pkt

Copy link
Copy Markdown
Member Author

not many comments about specification and implementation choices in PRs and issues
#807 (comment) has links and mentions Stata versus Greene parameterization.

Main restriction here. This cannot be used for proportions or counts. The endog has to be a single choice.
The advantage of the implementation is computational, i.e. we don't have to compute all cases for every observation.

@coveralls

coveralls commented Sep 3, 2020 •

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.003%) to 88.353% when pulling c05cead on josef-pkt:ordinal_model_rebased into 3d6a493 on statsmodels:master.

@josef-pkt

Copy link
Copy Markdown
Member Author

problem without constant

we cannot estimate a Null model

this works but produces nan standard errors (coeff on const is zero), but loglike is computed

# null model
mod_prob = OrderedModel(data_student['apply'].values.codes, np.ones((400,1)),
                        distr='logit')

setting exog=None currently raises
Note: threshold only Null model has an explicit method of moment solution
IIUC, then that is already computed in OrderedModel.start_params

We could add an offset variable right away which could be zeros, and the linear part would have a non-empty value.
We need the offset anyway later for estimating constrained models.

@lgtm-com

lgtm-com Bot commented Sep 3, 2020

Copy link
Copy Markdown

This pull request introduces 3 alerts when merging cc353cc into 3d6a493 - view on LGTM.com

new alerts:

  • 3 for Variable defined multiple times

@josef-pkt

Copy link
Copy Markdown
Member Author

strange: appveyor fails only on 3.8 with missing module, should fail everywhere
results folder is missing __init__.py

___________ ERROR collecting miscmodels/tests/test_ordinal_model.py ___________
ImportError while importing test module 'C:\Python38\lib\site-packages\statsmodels\miscmodels\tests\test_ordinal_model.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
C:\Python38\lib\importlib\__init__.py:127: in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
C:\Python38\lib\site-packages\statsmodels\miscmodels\tests\test_ordinal_model.py:9: in <module>
    from .results.results_ordinal_model import data_store as ds
E   ModuleNotFoundError: No module named 'statsmodels.miscmodels.tests.results'
=========================== short test summary info ===========================

@josef-pkt josef-pkt left a comment

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.

TBC

Comment thread statsmodels/miscmodels/ordinal_model.py Outdated
for x, y in zip(endog.values.categories[:-1],
endog.values.categories[1:])]
names['yname'] = endog_name
names['xname'] = names['xname'] + threshold_name

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.

exog does not need a model specific treatment. This should be handled by the generic framework.
threshold_names should use labels in __init__ independent of input format

thresh = np.concatenate(([-np.inf], thresh, [np.inf]))
xb = self.exog.dot(params[:-(self.k_levels - 1)])[:, None]
low = thresh[:-1] - xb
upp = thresh[1:] - xb

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.

separate out this part, DRY
it is also used in every loglike related function

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.

maybe not here
predict computes all integration bounds, loglike only two per observation

in predict low up could be selected after computing thresh - xb instead of computing it twice

Comment thread statsmodels/miscmodels/ordinal_model.py Outdated
thresh = np.concatenate((th_params[:1],
np.exp(th_params[1:]))).cumsum()
thresh = np.concatenate(([-np.inf], thresh, [np.inf]))
xb = self.exog.dot(params[:-(self.k_levels - 1)])[:, None]

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.

BUG: this should use exog argument if not None, not self.exog

def prob(self, low, upp):
"""interval probability
"""
return np.maximum(self.cdf(upp) - self.cdf(low), 0)

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.

need something analogous for pdf for score and hessian

@bashtage

bashtage commented Sep 3, 2020

Copy link
Copy Markdown
Member

Probably because that run tests from an install, not from the source tree. Porbbaly missing and __init__.py

@josef-pkt

Copy link
Copy Markdown
Member Author

Probably because that run tests from an install, not from the source tree.

Good that we have some CI that does this, otherwise we might not check for missing files in install distribution.

@josef-pkt

Copy link
Copy Markdown
Member Author

I opened issue #7023 to see whether we can easily convert link classes to distribution classes (difference in method names)
open for later

Comment thread statsmodels/miscmodels/ordinal_model.py Outdated
thresh = np.concatenate(([-np.inf], thresh, [np.inf]))
thresh_i_low = thresh[self.endog]
thresh_i_upp = thresh[self.endog + 1]
xb = self.exog.dot(params[:-(self.k_levels - 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.

outsource linpred,
then we need to add offset only at a single method.

@josef-pkt

josef-pkt commented Sep 3, 2020 •

Copy link
Copy Markdown
Member Author

problem with derivatives, score with respect to threshold parameters

Because I use the exp increment parameterization for the constant in the integration bounds, the derivatives are different from Greene. a change in one threshold parameter affect all higher integration bounds and so derivative for those is not zero.
Without the incremental parameterization a treshold parameter affects only two bounds.

so for score I still have to compute all probabilities, also those that belong to a different interval than the observation.

One possibility would be to use the exp increment parameterization only during the optimization with numerical derivatives, and get score and hessian for the simple threshold constant for post-estimation.
We do that in some count models.

Or use analytical score for exog parameters (which I have now) and numerical derivatives for threshold parameters. I did this somewhere. maybe (?) in count models

edit I think for score_test and similar we only need the score_factor with repect to the exog parameters. It is unlikely in this case that we want to test restrictions on the threshold constants.
e.g. we can still do an added variable test, if we have score_obs for the existing parameters and use score_factor for the added variables.
For hessian_factor we would need the derivative of the pdf.
probit and logit implement hessian, we might need additional distribution methods for the general case.

@josef-pkt

josef-pkt commented Sep 3, 2020 •

Copy link
Copy Markdown
Member Author

Stata ologit allows for offset and constraints

I added offset now, and it can be used to estimate the null model (currently only params of null results are tested)

score_obs based on numerical differences is available from GenericLikelihoodModel, but it will not be available when we change super class to LikelihoodModel. I needed to add loglikeobs (no underline _obs)

with inherited score_obs, we inherit generic robust cov
res_prob_hc = mod_prob.fit(method='bfgs', cov_type="HC0") works
needs unit tests

Stata allows cov type "robust" (i.e. HC1 IIRC) and "cluster"

With offset available fit_constrained might also work generically, except it might not handle extra params, I don't remember. Need to check another time.

@josef-pkt

Copy link
Copy Markdown
Member Author

df_resid looks wrong,
aic, bic of null model is nan, even though there are two parameters and llf looks fine

full model: df_resid is 400 - 3 and doesn't count the 2 threshold parameters, df_model subtracts 1 for constant ! (by default)
null model: df_model is nan

res_prob.df_resid, res_prob.df_model, res_prob.model.df_resid, res_prob.model.df_model
(397.0, 2.0, 397.0, 2.0)
res_prob_null.df_resid, res_prob_null.df_model, res_prob_null.model.df_resid, res_prob_null.model.df_model
(nan, nan, nan, nan)

res_prob_null.llf, res_prob.llf
(-370.60264131581323, -358.74756379018913)

@josef-pkt

Copy link
Copy Markdown
Member Author

current parameter names are misleading because those are not the internal names

e.g. summary shows "gpa", internal is "x3"

res_prob.t_test("gpa=0") this raises exception, unkown token
res_prob.t_test("x3=0") this works

@josef-pkt
josef-pkt force-pushed the ordinal_model_rebased branch 2 times, most recently from 25f20d8 to c05cead Compare September 5, 2020 20:19
@pep8speaks

pep8speaks commented Sep 5, 2020 •

Copy link
Copy Markdown

Hello @josef-pkt! Thanks for updating this PR. We checked the lines you've touched for PEP 8 issues, and found:

Line 13:1: F401 'statsmodels.base.model.LikelihoodModel' imported but unused

Comment last updated at 2020-09-15 14:59:47 UTC

@josef-pkt

josef-pkt commented Sep 7, 2020 •

Copy link
Copy Markdown
Member Author

I have an uncommitted change in __init__ that converts 2-dim endog back to a 1-dim array. This works in the examples, however, it's too risky to let in unintended cases through patsy's formula handling.
The only case I would like to support is using a pandas categorical endog and numerical endog in formulas. That looks a bit messy to implement.

            elif self.endog.ndim == 2:
                # TODO: check if we really want to do this from formula
                k_levels = self.endog.shape[1]
                self.endog = self.endog.argmax(1)
                labels = [str(i) for i in range(k_levels)]
                # fix yname
                self.data.ynames = self.data.ynames[0].split("[")[0]

One problem is to access the original endog before patsy transformed it, currently that's difficult.
Although, I just saw that we store the original dataframe in mod_probf.data.frame.

I guess the cleanest solution would be to add the option for not using patsy for endog to statsmodels.formula.formulatools. handle_formula_data which is called by Model.__init__

also, I can add a user facing set_labels method to OrderedModel, so users can get proper labels even with integer endog. That needs to change the threshold names in param_names.

edit
The formula handling hasn't removed design info from orig_endog.


mod_probf.data.orig_endog.design_info
DesignInfo(['apply[unlikely]', 'apply[somewhat likely]', 'apply[very likely]'],
           factor_infos={EvalFactor('apply'): FactorInfo(factor=EvalFactor('apply'),
                                    type='categorical',
                                    state=<factor state>,
                                    categories=('unlikely',
                                                'somewhat likely',
                                                'very likely'))},
           term_codings=OrderedDict([(Term([EvalFactor('apply')]),
                                      [SubtermInfo(factors=(EvalFactor('apply'),),
                                                   contrast_matrices={EvalFactor('apply'): ContrastMatrix(array([[1., 0., 0.],
                                                                                            [0., 1., 0.],
                                                                                            [0., 0., 1.]]),
                                                                                     ['[unlikely]',
                                                                                      '[somewhat likely]',
                                                                                      '[very likely]'])},
                                                   num_columns=3)])]))

die = mod_probf.data.orig_endog.design_info

die.factor_infos.keys(), die.factor_infos.values()
(dict_keys([EvalFactor('apply')]),
 dict_values([FactorInfo(factor=EvalFactor('apply'),
            type='categorical',
            state=<factor state>,
            categories=('unlikely', 'somewhat likely', 'very likely'))]))

list(die.factor_infos.values())[0].categories
('unlikely', 'somewhat likely', 'very likely')


type(mod_probf.data.frame["apply"]), mod_probf.data.frame["apply"].dtype
(pandas.core.series.Series,
 CategoricalDtype(categories=['unlikely', 'somewhat likely', 'very likely'], ordered=True))

@josef-pkt

josef-pkt commented Sep 7, 2020 •

Copy link
Copy Markdown
Member Author

I tried subclassing LikelihoodModel, but it fails because there are no default numerical derivative in score

edit
subclassing LikelihoodModelResults is also not trivial. The __init__ signature differs and how mlefit is converted to fit results like params and normalized_cov_params.

checking with DiscreteResults(base.LikelihoodModelResults.__init__ doesn't call super
signature is similar to GenericLikelihoodModelResults, and differs from LikelihoodModelResults

@josef-pkt

Copy link
Copy Markdown
Member Author

tricky:
model.data.frame and formula is not available in a model.__init__ because from_formula adds the attribute after creating the instance.
I cannot use the attribute to change things inside __init__.

        mod = cls(endog, exog, *args, **kwargs)
        mod.formula = formula

        # since we got a dataframe, attach the original
        mod.data.frame = data
        return mod

@josef-pkt
josef-pkt force-pushed the ordinal_model_rebased branch from c05cead to 6fc1e65 Compare September 7, 2020 20:12
@josef-pkt

Copy link
Copy Markdown
Member Author

I made some changes in how frame is attached to model.data in formula handling. This might need more review.
Now, only numerical or pandas ordered Categorical are allowed as endog in formulas, anything else should raise a ValueError.

@josef-pkt

josef-pkt commented Sep 7, 2020 •

Copy link
Copy Markdown
Member Author

looks pretty bad unit test fail all over the place (but pytest output in this case is much too verbose to get an overview)

one case in missing handling in statsmodels.formula.tests.test_formula.TestFormulaDict

another case, MixedLM uses an allowed list

_allowed_kwargs = ["missing_idx", "design_info", "formula"]
        for x in kwargs.keys():
            if x not in _allowed_kwargs:
>               raise ValueError(
                    "argument %s not permitted for MixedLM initialization" % x)
E               ValueError: argument frame not permitted for MixedLM initialization

I need to continue another day, I need to recompile statsmodels, but that's not possible because I have too many open python interpreters/notebooks to shut them down now.

@lgtm-com

lgtm-com Bot commented Sep 7, 2020

Copy link
Copy Markdown

This pull request introduces 1 alert when merging 6fc1e65 into 7d727fd - view on LGTM.com

new alerts:

  • 1 for Unused import

@josef-pkt

josef-pkt commented Sep 14, 2020 •

Copy link
Copy Markdown
Member Author

fixing the allowed kwargs is easy, but

it looks like there is a more tricky problem with missing value handling, several test failures for that. frame is an extra array in __initi__ in my current code, which seems to get automatically included in nan handling
I can work around that by wrapping it into something that is not considered as data array, e.g. 'frame': np.array({"data": data})
(needs ndim, dict raises error)
update this was my mistake because I didn't unwrap the DataFrame before attaching inside model.__init__

next problem: pickling (all other unit tests in base pass

..\..\\statsmodels\statsmodels_py37\statsmodels\statsmodels\
base\tests\test_shrink_pickle.py . [ 87%]
.........................F.FF.FF.FF.FF.F...                              [ 97%]

failing test are all in formula handling in pickling

..\..\josef_new\eclipse_ws\statsmodels\statsmodels_py37\statsmodels\statsmodels\
base\tests\test_shrink_pickle.py::TestPickleFormula::test_remove_data_pickle FAI
LED [ 61%]
..\..\josef_new\eclipse_ws\statsmodels\statsmodels_py37\statsmodels\statsmodels\
base\tests\test_shrink_pickle.py::TestPickleFormula::test_remove_data_docstring
PASSED [ 63%]
..\..\josef_new\eclipse_ws\statsmodels\statsmodels_py37\statsmodels\statsmodels\
base\tests\test_shrink_pickle.py::TestPickleFormula::test_pickle_wrapper FAILED
[ 65%]
..\..\josef_new\eclipse_ws\statsmodels\statsmodels_py37\statsmodels\statsmodels\
base\tests\test_shrink_pickle.py::TestPickleFormula2::test_remove_data_pickle FA
ILED [ 68%]
..\..\josef_new\eclipse_ws\statsmodels\statsmodels_py37\statsmodels\statsmodels\
base\tests\test_shrink_pickle.py::TestPickleFormula2::test_remove_data_docstring
 PASSED [ 70%]
..\..\josef_new\eclipse_ws\statsmodels\statsmodels_py37\statsmodels\statsmodels\
base\tests\test_shrink_pickle.py::TestPickleFormula2::test_pickle_wrapper FAILED
 [ 72%]
..\..\josef_new\eclipse_ws\statsmodels\statsmodels_py37\statsmodels\statsmodels\
base\tests\test_shrink_pickle.py::TestPickleFormula3::test_remove_data_pickle FA
ILED [ 75%]
..\..\josef_new\eclipse_ws\statsmodels\statsmodels_py37\statsmodels\statsmodels\
base\tests\test_shrink_pickle.py::TestPickleFormula3::test_remove_data_docstring
 PASSED [ 77%]
..\..\josef_new\eclipse_ws\statsmodels\statsmodels_py37\statsmodels\statsmodels\
base\tests\test_shrink_pickle.py::TestPickleFormula3::test_pickle_wrapper FAILED
 [ 79%]
..\..\josef_new\eclipse_ws\statsmodels\statsmodels_py37\statsmodels\statsmodels\
base\tests\test_shrink_pickle.py::TestPickleFormula4::test_remove_data_pickle FA
ILED [ 81%]
..\..\josef_new\eclipse_ws\statsmodels\statsmodels_py37\statsmodels\statsmodels\
base\tests\test_shrink_pickle.py::TestPickleFormula4::test_remove_data_docstring
 PASSED [ 84%]
..\..\josef_new\eclipse_ws\statsmodels\statsmodels_py37\statsmodels\statsmodels\
base\tests\test_shrink_pickle.py::TestPickleFormula4::test_pickle_wrapper FAILED
 [ 86%]
..\..\josef_new\eclipse_ws\statsmodels\statsmodels_py37\statsmodels\statsmodels\
base\tests\test_shrink_pickle.py::TestPickleFormula5::test_remove_data_pickle FA
ILED [ 88%]
..\..\josef_new\eclipse_ws\statsmodels\statsmodels_py37\statsmodels\statsmodels\
base\tests\test_shrink_pickle.py::TestPickleFormula5::test_remove_data_docstring
 PASSED [ 90%]
..\..\josef_new\eclipse_ws\statsmodels\statsmodels_py37\statsmodels\statsmodels\
base\tests\test_shrink_pickle.py::TestPickleFormula5::test_pickle_wrapper FAILED
 [ 93%]

Might be better to add some internal or formula_info keyword to model.__init__ instead of another specific keyword

eg. in MixedLM, with my addition of frame

_allowed_kwargs = ["missing_idx", "design_info", "formula", "frame"]

those are added in from_formula

        kwargs.update({'missing_idx': missing_idx,
                       'missing': missing,
                       'formula': formula,  # attach formula for unpckling
                       'design_info': design_info,
                       'frame': np.array({"data": data})  # try dict to avoid missing
                       })

I think that should work, if we have a formula_info keyword, then eventually we might be able to reuse it for user provided formula info.
e.g. user calls patsy design_matrix and gives us the design_info, or
formula info based on other than patsy's formula handling.

Also, then from_formula can just provide the info to __init__ instead of attaching it after creating the instance.

@josef-pkt

Copy link
Copy Markdown
Member Author

locally, unit tests for base, regression and miscmodels now pass

This is still a version with an explicit frame keyword from from_formula to model.__init__

@lgtm-com

lgtm-com Bot commented Sep 15, 2020

Copy link
Copy Markdown

This pull request introduces 3 alerts when merging f63c243 into 4328705 - view on LGTM.com

new alerts:

  • 1 for Unused local variable
  • 1 for Unused import
  • 1 for Module is imported with 'import' and 'import from'

@josef-pkt

josef-pkt commented Sep 15, 2020 •

Copy link
Copy Markdown
Member Author

frame can be None, in constrained estimation (Poisson, GLM) and in conditional Poisson and in mediation
https://travis-ci.org/github/statsmodels/statsmodels/jobs/727232933

frame is needed for unpickling with formulas, so there might be problems in those cases, unless it is an auxiliary model that doesn't need to be pickled (as inconstrained), but that's unlikely.

There are cases where frame is not a pandas Dataframe.
I left a debugging exception in base.Model._handle_data that casues failures in several unit tests

>                if not isinstance(data.frame, pd.DataFrame):
>                   raise
E                   RuntimeError: No active exception to reraise

frame has to be something that patsy can handle as data, e.g. DataFrame or dict, otherwise unpickling will not work.

@josef-pkt

Copy link
Copy Markdown
Member Author

I'm giving up here, adding frame as keyword to Model.__init__ affects too many parts.
This needs more systematic refactoring #7033,
and more unit tests for unpickling which might be broken in some cases #7034

needs checking where "frame" is used and what types of it are allowed

@josef-pkt

josef-pkt commented Sep 15, 2020 •

Copy link
Copy Markdown
Member Author

I continue with ordinal model in #7035
I leave this PR unchanged, so I can look at it again for adding formula_info

@josef-pkt josef-pkt changed the title ENH: Ordinal model rebased WIP: formula_tools as model argument, was: Ordinal model rebased Sep 15, 2020
@lgtm-com

lgtm-com Bot commented Sep 15, 2020

Copy link
Copy Markdown

This pull request introduces 2 alerts when merging 7e64c98 into 4328705 - view on LGTM.com

new alerts:

  • 1 for Unused import
  • 1 for Module is imported with 'import' and 'import from'

@josef-pkt josef-pkt changed the title WIP: formula_tools as model argument, was: Ordinal model rebased WIP: formula_info as model argument, was: Ordinal model rebased Sep 15, 2020
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.

5 participants