Skip to content

ENH: Ordinal models - #6982

Closed
Bolzano-Weierstrass wants to merge 13 commits into
statsmodels:masterfrom
Bolzano-Weierstrass:ordinal_models
Closed

Bolzano-Weierstrass wants to merge 13 commits into
statsmodels:masterfrom
Bolzano-Weierstrass:ordinal_models

Conversation

@Bolzano-Weierstrass

Copy link
Copy Markdown
Contributor

see PR #2600 and issue #807

Picked up the ordinal regression model started a few years ago.
Mostly focused on the bodywork and left the engine untouched as the results seem correct.
It is currently in miscmodels and relies on GenericLikelihoodModel.

In this PR:

  • added support for the Pandas ecosystem, endog can be a categorical Serie and exog can be a Serie or a DataFrame.

  • added a minimal Result class that embellishes .summary() by using variables names if the inputs are from Pandas.

  • added tests: formula mode, Pandas inputs, custom distributions, ...

  • tested against R MASS package

@coveralls

coveralls commented Aug 23, 2020 •

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.02%) to 88.325% when pulling bcd1fa2 on Bolzano-Weierstrass:ordinal_models into 1659994 on statsmodels:master.

@lgtm-com

lgtm-com Bot commented Aug 23, 2020

Copy link
Copy Markdown

This pull request introduces 3 alerts when merging 49d6360 into 1659994 - view on LGTM.com

new alerts:

  • 3 for Variable defined multiple times

@@ -0,0 +1,97 @@
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 24 11:17:06 2015

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Could you do a notebook? We don't really use ex_... Python files anymore and they dont' show up in the docs.

@lgtm-com

lgtm-com Bot commented Aug 25, 2020

Copy link
Copy Markdown

This pull request introduces 3 alerts when merging bcd1fa2 into 26d901a - view on LGTM.com

new alerts:

  • 3 for Variable defined multiple times

@josef-pkt

Copy link
Copy Markdown
Member

I just checked out the branch.
The notebook looks good, having support for arbitrary continuous distributions is pretty nice.

Having ordered categorical support from pandas is very useful. When I wrote this initially, that support had just started.

I need to go through the code, but my impression is that with enough unit tests we can move it from misc_models into discrete
I don't remember what post-estimation results we have and would be good to have.
OrderedResults currently just inherits from GenericLikelihoodModelResults

@josef-pkt

Copy link
Copy Markdown
Member

from_formula

  • using a categorical/string variable as endog does not work, patsy converts it into some dummy/treatment coding
  • using numeric code as endog, e.g. data['apply'].values.codes works with from_formula
    • in that case summary breaks because of length mismatch, names hasn't been expanded to include thresholds
    • using numeric endog looses the names of category levels.
  • the model requires that there is no constant. AFAIR, patsy adds an implicit constant for categoricals if "-1" is in the formula.
    That might make constant/one threshold unidentified. AFAIR, we have no-constant case in survival, need to compare code.
    (I guess we could reparameterize to include an explicit constant, but that sounds difficult)
    MASS polr requires a constant, but then seems to remove or reparameterize it? I guess, formulas then ensure that there is no implicit constant in the slope variables.

currently I see two ways to have original endog in formula

  • use patsy only for the dmatrix/exog part and require left hand side in formula is just a name for data data[lhs_name]
  • convert patsy 2-dim conversion to dummies back to an index, e.g. endog=endog.argmax(1)

wrapper for returning pandas results is missing.

@josef-pkt

Copy link
Copy Markdown
Member

score and hessian http://people.stern.nyu.edu/wgreene/OrderedChoiceModeling.pdf section 5.9.5 p. 142
perfect prediction p. 139
robust cov p. 128, uses just score_obs and hessian, generic for MLE
green also has some diagnostics

aside: In the notebook example, the hessian of polr and our hessian are very different for ordinal probit. I haven't looked at details or possible parameterization or scaling issues

@josef-pkt

Copy link
Copy Markdown
Member

patsy attaches design_info also for and to the endog, but we don't attach it in the model and we don't use it anywhere AFAIK.
From this we could get the name of the endog column in data, and the names of the category levels.

If we leave missing value handling to patsy, then we cannot use the original data directly. But we could also run into problems with inherited nan handling, i.e. we are delegating most of the formula data handling up to the Model class and it might be difficult to override specific parts. I haven't tried yet. (users can just do .dropna, so lower priority)

not clear to me:
What's the current ordering of category levels using numpy arrays, i.e. how does numpy order "uniques"
unique, index = np.unique(self.endog, return_inverse=True)
Do we need and option to reorder?
By now the recommended way is to use pandas ordered Categorical.
Can we trust patsy to preserve the ordering? not sure

@josef-pkt

Copy link
Copy Markdown
Member

formulatools has functions like _remove_intercept_patsy to check for and remove intercept in design_info. ( I never looked at those before)
It might be better that users include an intercept and we remove it if there are categorical variables that shouldn't include an implicit constant.

@josef-pkt

Copy link
Copy Markdown
Member

another possibility: because of patsy's eval, using the full name apply.values.codes works, and patsy treats it as numerical.
We can internally adjust the formula to add .values.codes
We would just need to extract the level names.

import patsy
y, x = patsy.dmatrices("apply.values.codes ~ pared + public + gpa - 1", data_student, return_type="dataframe")
y.design_info

@josef-pkt

josef-pkt commented Sep 3, 2020 •

Copy link
Copy Markdown
Member

ynames in predict, currently missing

predict is inherited from base.Model, that returns conditionally a pandas Series or DataFrame with appropriate index but no column names. We can add the ynames there.

            if predict_results.ndim == 1:
                return pd.Series(predict_results, index=exog_index)
            else:
                return pd.DataFrame(predict_results, index=exog_index)

We just raise an exception in the formula if endog is not a pandas Categorical or numeric. We don't want some weird patsy behavior to sneak in as for Binomial. see #2181 and related issues

@josef-pkt

Copy link
Copy Markdown
Member

@Bolzano-Weierstrass Do you have any changes left for this PR?

I think it's easier if I take over this PR, for now, to add changes that require more of the statsmodels internals and inheritance.

If you have additional improvements and enhancements, then we could add them after I made my changes to integrate it better with the statsmodels structure.

@Bolzano-Weierstrass

Copy link
Copy Markdown
Contributor Author

@Bolzano-Weierstrass Do you have any changes left for this PR?

I think it's easier if I take over this PR, for now, to add changes that require more of the statsmodels internals and inheritance.

If you have additional improvements and enhancements, then we could add them after I made my changes to integrate it better with the statsmodels structure.

Sounds good, thanks !

@josef-pkt

Copy link
Copy Markdown
Member

@Bolzano-Weierstrass question on using pandas Categorical.

I would like to get the codes as Series with the same index and name as the original Categorical Series,
something like
endog = data_student['apply'].cat.codesinstead ofendog = np.asarray(endog.values.codes)`

Does it preserve the index and missing values?
In the example .cat.codes doesn't have the series name anymore. I guess we can copy it directly.

The advantage would be that super classes of OrderedModel will use the standard data handling for pandas endog, e.g. attaching the name if available. The index might be used with the missing handling, but I'm not sure about that.
Also using that in formulas would preserve the pandas name, e.g. use cat instead of values in the unit test example that uses data['apply'].values.codes

I found .cat.codes by google search and have no experience with pandas.Categorial

@Bolzano-Weierstrass

Copy link
Copy Markdown
Contributor Author

Missing values are given the code -1 no matter what and the index is indeed preserved.
Also .cat.codes gives codes to the values according to the order of the categories list .cat.categories. This can be rather arbitrary if the Serie has ordered=False, if ordered=True, the order is set by the user so it is safer.

@josef-pkt

Copy link
Copy Markdown
Member

Thanks,

Missing values are given the code -1

This means our nan/missing detection will not find it.
I will raise an exception if codes.min() == -1, because we cannot support it in the current structure and code flow.
-1 would still be valid in indexing, but index the wrong thing, I guess without raising an exception in the computations.

@josef-pkt

Copy link
Copy Markdown
Member

I'm going to allow pandas endog that is not Categorical. Any reason against it?

data_student['apply_codes'] = data_student['apply'].cat.codes
mod_probp = OrderedModel(data_student['apply_codes'],
                        data_student[['pared', 'public', 'gpa']],
                        distr='probit')
res_probp = mod_probp.fit(method='bfgs')
print(res_probp.summary())
                             OrderedModel Results                             
==============================================================================
Dep. Variable:            apply_codes   Log-Likelihood:                -358.75
Model:                   OrderedModel   AIC:                             723.5
Method:            Maximum Likelihood   BIC:                             735.5
Date:                Sat, 05 Sep 2020                                         
Time:                        18:23:52                                         
No. Observations:                 400                                         
Df Residuals:                     397                                         
Df Model:                           2                                         
==============================================================================
                 coef    std err          z      P>|z|      [0.025      0.975]
------------------------------------------------------------------------------
pared          0.5981      0.158      3.789      0.000       0.289       0.908
public         0.0102      0.173      0.059      0.953      -0.329       0.349
gpa            0.3582      0.157      2.285      0.022       0.051       0.665
0/1            1.2968      0.468      2.774      0.006       0.381       2.213
1/2            0.1873      0.074      2.530      0.011       0.042       0.332
==============================================================================

@josef-pkt

Copy link
Copy Markdown
Member

@Bolzano-Weierstrass Thanks for working on this, especially unit tests and showing how to use pandas Categorical

miscmodels version merged #7035
follow-up issue #7069

@josef-pkt josef-pkt closed this Oct 8, 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.

4 participants