# Ordinal Regression¶

:

import numpy as np
import pandas as pd
import scipy.stats as stats

from statsmodels.miscmodels.ordinal_model import OrderedModel


Loading a stata data file from the UCLA website.This notebook is inspired by https://stats.idre.ucla.edu/r/dae/ordinal-logistic-regression/ which is a R notebook from UCLA.

:

url = "https://stats.idre.ucla.edu/stat/data/ologit.dta"

:

data_student.head(5)

:

apply pared public gpa
0 very likely 0 0 3.26
1 somewhat likely 1 0 3.21
2 unlikely 1 1 3.94
3 somewhat likely 0 0 2.81
4 somewhat likely 0 0 2.53
:

data_student.dtypes

:

apply     category
pared         int8
public        int8
gpa        float32
dtype: object

:

data_student['apply'].dtype

:

CategoricalDtype(categories=['unlikely', 'somewhat likely', 'very likely'], ordered=True)


This dataset is about the probability for undergraduate students to apply to graduate school given three exogenous variables: - their grade point average(gpa), a float between 0 and 4. - pared, a binary that indicates if at least one parent went to graduate school. - and public, a binary that indicates if the current undergraduate institution of the student is public or private.

apply, the target variable is categorical with ordered categories: unlikely < somewhat likely < very likely. It is a pd.Serie of categorical type, this is preferred over NumPy arrays.

The model is based on a numerical latent variable $$y_{latent}$$ that we cannot observe but that we can compute thanks to exogenous variables. Moreover we can use this $$y_{latent}$$ to define $$y$$ that we can observe.

For more details see the the Documentation of OrderedModel, the UCLA webpage or this book.

## Probit ordinal regression:¶

:

mod_prob = OrderedModel(data_student['apply'],
data_student[['pared', 'public', 'gpa']],
distr='probit')

res_prob = mod_prob.fit(method='bfgs')
res_prob.summary()

Optimization terminated successfully.
Current function value: 0.896869
Iterations: 17
Function evaluations: 21

:

Dep. Variable: Log-Likelihood: apply -358.75 OrderedModel 727.5 Maximum Likelihood 747.5 Wed, 06 Oct 2021 10:58:54 400 395 5
coef std err z P>|z| [0.025 0.975] 0.5981 0.158 3.789 0.000 0.289 0.908 0.0102 0.173 0.059 0.953 -0.329 0.349 0.3582 0.157 2.285 0.022 0.051 0.665 1.2968 0.468 2.774 0.006 0.381 2.213 0.1873 0.074 2.530 0.011 0.042 0.332

In our model, we have 3 exogenous variables(the $$\beta$$s if we keep the documentation’s notations) so we have 3 coefficients that need to be estimated.

Those 3 estimations and their standard errors can be retrieved in the summary table.

Since there are 3 categories in the target variable(unlikely, somewhat likely, very likely), we have two thresholds to estimate. As explained in the doc of the method OrderedModel.transform_threshold_params, the first estimated threshold is the actual value and all the other thresholds are in terms of cumulative exponentiated increments. Actual thresholds values can be computed as follows:

:

num_of_thresholds = 2
mod_prob.transform_threshold_params(res_prob.params[-num_of_thresholds:])

:

array([      -inf, 1.29684541, 2.50285885,        inf])


## Logit ordinal regression:¶

:

mod_log = OrderedModel(data_student['apply'],
data_student[['pared', 'public', 'gpa']],
distr='logit')

res_log = mod_log.fit(method='bfgs', disp=False)
res_log.summary()

:

Dep. Variable: Log-Likelihood: apply -358.51 OrderedModel 727.0 Maximum Likelihood 747.0 Wed, 06 Oct 2021 10:58:54 400 395 5
coef std err z P>|z| [0.025 0.975] 1.0476 0.266 3.942 0.000 0.527 1.569 -0.0586 0.298 -0.197 0.844 -0.642 0.525 0.6158 0.261 2.363 0.018 0.105 1.127 2.2035 0.780 2.827 0.005 0.676 3.731 0.7398 0.080 9.236 0.000 0.583 0.897
:

predicted = res_log.model.predict(res_log.params, exog=data_student[['pared', 'public', 'gpa']])
predicted

/home/kevin/git/statsmodels/statsmodels/miscmodels/ordinal_model.py:419: FutureWarning: Support for multi-dimensional indexing (e.g. obj[:, None]) is deprecated and will be removed in a future version.  Convert to a numpy array before indexing instead.
xb = xb[:, None]

:

array([[0.54884071, 0.35932276, 0.09183653],
[0.30558191, 0.47594216, 0.21847593],
[0.22938356, 0.47819057, 0.29242587],
...,
[0.69380357, 0.25470075, 0.05149568],
[0.54884071, 0.35932276, 0.09183653],
[0.50896794, 0.38494062, 0.10609145]])

:

pred_choice = predicted.argmax(1)
print('Fraction of correct choice predictions')
print((np.asarray(data_student['apply'].values.codes) == pred_choice).mean())

Fraction of correct choice predictions
0.5775


## Ordinal regression with a custom cumulative cLogLog distribution:¶

In addition to logit and probit regression, any continuous distribution from SciPy.stats package can be used for the distr argument. Alternatively, one can define its own distribution simply creating a subclass from rv_continuous and implementing a few methods.

:

# using a SciPy distribution
res_exp = OrderedModel(data_student['apply'],
data_student[['pared', 'public', 'gpa']],
distr=stats.expon).fit(method='bfgs', disp=False)
res_exp.summary()

:

Dep. Variable: Log-Likelihood: apply -360.84 OrderedModel 731.7 Maximum Likelihood 751.6 Wed, 06 Oct 2021 10:58:55 400 395 5
coef std err z P>|z| [0.025 0.975] 0.4690 0.117 4.021 0.000 0.240 0.698 -0.1308 0.149 -0.879 0.379 -0.422 0.161 0.2198 0.134 1.638 0.101 -0.043 0.483 1.5370 0.405 3.792 0.000 0.742 2.332 0.4082 0.093 4.403 0.000 0.226 0.590
:

# minimal definition of a custom scipy distribution.
class CLogLog(stats.rv_continuous):
def _ppf(self, q):
return np.log(-np.log(1 - q))

def _cdf(self, x):
return 1 - np.exp(-np.exp(x))

cloglog = CLogLog()

# definition of the model and fitting
res_cloglog = OrderedModel(data_student['apply'],
data_student[['pared', 'public', 'gpa']],
distr=cloglog).fit(method='bfgs', disp=False)
res_cloglog.summary()

:

Dep. Variable: Log-Likelihood: apply -359.75 OrderedModel 729.5 Maximum Likelihood 749.5 Wed, 06 Oct 2021 10:58:56 400 395 5
coef std err z P>|z| [0.025 0.975] 0.5167 0.161 3.202 0.001 0.200 0.833 0.1081 0.168 0.643 0.520 -0.221 0.438 0.3344 0.154 2.168 0.030 0.032 0.637 0.8705 0.455 1.912 0.056 -0.022 1.763 0.0989 0.071 1.384 0.167 -0.041 0.239

## Using formulas - treatment of endog¶

Pandas’ ordered categorical and numeric values are supported as dependent variable in formulas. Other types will raise a ValueError.

:

modf_logit = OrderedModel.from_formula("apply ~ 0 + pared + public + gpa", data_student,
distr='logit')
resf_logit = modf_logit.fit(method='bfgs')
resf_logit.summary()

Optimization terminated successfully.
Current function value: 0.896281
Iterations: 22
Function evaluations: 24

:

Dep. Variable: Log-Likelihood: apply -358.51 OrderedModel 727.0 Maximum Likelihood 747.0 Wed, 06 Oct 2021 10:58:56 400 395 5
coef std err z P>|z| [0.025 0.975] 1.0476 0.266 3.942 0.000 0.527 1.569 -0.0586 0.298 -0.197 0.844 -0.642 0.525 0.6158 0.261 2.363 0.018 0.105 1.127 2.2035 0.780 2.827 0.005 0.676 3.731 0.7398 0.080 9.236 0.000 0.583 0.897

Using numerical codes for the dependent variable is supported but loses the names of the category levels. The levels and names correspond to the unique values of the dependent variable sorted in alphanumeric order as in the case without using formulas.

:

data_student["apply_codes"] = data_student['apply'].cat.codes * 2 + 5

:

0    9
1    7
2    5
3    7
4    7
Name: apply_codes, dtype: int8

:

OrderedModel.from_formula("apply_codes ~ 0 + pared + public + gpa", data_student,
distr='logit').fit().summary()

Optimization terminated successfully.
Current function value: 0.896281
Iterations: 421
Function evaluations: 663

:

Dep. Variable: Log-Likelihood: apply_codes -358.51 OrderedModel 727.0 Maximum Likelihood 747.0 Wed, 06 Oct 2021 10:58:58 400 395 5
coef std err z P>|z| [0.025 0.975] 1.0477 0.266 3.942 0.000 0.527 1.569 -0.0587 0.298 -0.197 0.844 -0.642 0.525 0.6157 0.261 2.362 0.018 0.105 1.127 2.2033 0.780 2.826 0.005 0.675 3.731 0.7398 0.080 9.236 0.000 0.583 0.897
:

resf_logit.predict(data_student.iloc[:5])

:

0 1 2
0 0.548841 0.359323 0.091837
1 0.305582 0.475942 0.218476
2 0.229384 0.478191 0.292426
3 0.616118 0.312690 0.071191
4 0.656003 0.283398 0.060599

Using string values directly as dependent variable raises a ValueError.

:

data_student["apply_str"] = np.asarray(data_student["apply"])

:

0        very likely
1    somewhat likely
2           unlikely
3    somewhat likely
4    somewhat likely
Name: apply_str, dtype: object

:

data_student.apply_str = pd.Categorical(data_student.apply_str, ordered=True)
data_student.public = data_student.public.astype(float)
data_student.pared = data_student.pared.astype(float)

:

OrderedModel.from_formula("apply_str ~ 0 + pared + public + gpa", data_student,
distr='logit')

:

<statsmodels.miscmodels.ordinal_model.OrderedModel at 0x7fdfb333deb0>


## Using formulas - no constant in model¶

The parameterization of OrderedModel requires that there is no constant in the model, neither explicit nor implicit. The constant is equivalent to shifting all thresholds and is therefore not separately identified.

Patsy’s formula specification does not allow a design matrix without explicit or implicit constant if there are categorical variables (or maybe splines) among explanatory variables. As workaround, statsmodels removes an explicit intercept.

Consequently, there are two valid cases to get a design matrix without intercept.

• specify a model without explicit and implicit intercept which is possible if there are only numerical variables in the model.

• specify a model with an explicit intercept which statsmodels will remove.

Models with an implicit intercept will be overparameterized, the parameter estimates will not be fully identified, cov_params will not be invertible and standard errors might contain nans.

In the following we look at an example with an additional categorical variable.

:

nobs = len(data_student)
data_student["dummy"] = (np.arange(nobs) < (nobs / 2)).astype(float)


explicit intercept, that will be removed:

Note “1 +” is here redundant because it is patsy’s default.

:

modfd_logit = OrderedModel.from_formula("apply ~ 1 + pared + public + gpa + C(dummy)", data_student,
distr='logit')
resfd_logit = modfd_logit.fit(method='bfgs')
print(resfd_logit.summary())

Optimization terminated successfully.
Current function value: 0.896247
Iterations: 26
Function evaluations: 28
OrderedModel Results
==============================================================================
Dep. Variable:                  apply   Log-Likelihood:                -358.50
Model:                   OrderedModel   AIC:                             729.0
Method:            Maximum Likelihood   BIC:                             752.9
Date:                Wed, 06 Oct 2021
Time:                        10:58:59
No. Observations:                 400
Df Residuals:                     394
Df Model:                           6
===============================================================================================
coef    std err          z      P>|z|      [0.025      0.975]
-----------------------------------------------------------------------------------------------
C(dummy)[T.1.0]                 0.0326      0.198      0.164      0.869      -0.356       0.421
pared                           1.0489      0.266      3.945      0.000       0.528       1.570
public                         -0.0589      0.298     -0.198      0.843      -0.643       0.525
gpa                             0.6153      0.261      2.360      0.018       0.104       1.126
unlikely/somewhat likely        2.2183      0.785      2.826      0.005       0.680       3.757
somewhat likely/very likely     0.7398      0.080      9.237      0.000       0.583       0.897
===============================================================================================

:

modfd_logit.k_vars

:

4

:

modfd_logit.k_constant

:

0


implicit intercept creates overparameterized model

Specifying “0 +” in the formula drops the explicit intercept. However, the categorical encoding is now changed to include an implicit intercept. In this example, the created dummy variables C(dummy)[0.0] and C(dummy)[1.0] sum to one.

OrderedModel.from_formula("apply ~ 0 + pared + public + gpa + C(dummy)", data_student, distr='logit')


To see what would happen in the overparameterized case, we can avoid the constant check in the model by explicitly specifying whether a constant is present or not. We use hasconst=False, even though the model has an implicit constant.

The parameters of the two dummy variable columns and the first threshold are not separately identified. Estimates for those parameters and availability of standard errors are arbitrary and depends on numerical details that differ across environments.

Some summary measures like log-likelihood value are not affected by this, within convergence tolerance and numerical precision. Prediction should also be possible. However, inference is not available, or is not valid.

:

modfd2_logit = OrderedModel.from_formula("apply ~ 0 + pared + public + gpa + C(dummy)", data_student,
distr='logit', hasconst=False)
resfd2_logit = modfd2_logit.fit(method='bfgs')
print(resfd2_logit.summary())

Optimization terminated successfully.
Current function value: 0.896247
Iterations: 24
Function evaluations: 26
OrderedModel Results
==============================================================================
Dep. Variable:                  apply   Log-Likelihood:                -358.50
Model:                   OrderedModel   AIC:                             731.0
Method:            Maximum Likelihood   BIC:                             758.9
Date:                Wed, 06 Oct 2021
Time:                        10:59:00
No. Observations:                 400
Df Residuals:                     393
Df Model:                           7
===============================================================================================
coef    std err          z      P>|z|      [0.025      0.975]
-----------------------------------------------------------------------------------------------
C(dummy)[0.0]                  -0.6834    635.515     -0.001      0.999   -1246.269    1244.902
C(dummy)[1.0]                  -0.6508    635.515     -0.001      0.999   -1246.237    1244.935
pared                           1.0489      0.266      3.944      0.000       0.528       1.570
public                         -0.0588      0.298     -0.197      0.844      -0.643       0.525
gpa                             0.6153      0.261      2.360      0.018       0.104       1.126
unlikely/somewhat likely        1.5349    635.516      0.002      0.998   -1244.054    1247.124
somewhat likely/very likely     0.7398      0.080      9.237      0.000       0.583       0.897
===============================================================================================

:

resfd2_logit.predict(data_student.iloc[:5])

:

0 1 2
0 0.544858 0.361972 0.093170
1 0.301918 0.476667 0.221416
2 0.226434 0.477700 0.295867
3 0.612254 0.315481 0.072264
4 0.652280 0.286188 0.061532
:

resf_logit.predict()

:

array([[0.54884071, 0.35932276, 0.09183653],
[0.30558191, 0.47594216, 0.21847593],
[0.22938356, 0.47819057, 0.29242587],
...,
[0.69380357, 0.25470075, 0.05149568],
[0.54884071, 0.35932276, 0.09183653],
[0.50896794, 0.38494062, 0.10609145]])

[ ]:




## Binary Model compared to Logit¶

If there are only two levels of the dependent ordered categorical variable, then the model can also be estimated by a Logit model.

The models are (theoretically) identical in this case except for the parameterization of the constant. Logit as most other models requires in general an intercept. This corresponds to the threshold parameter in the OrderedModel, however, with opposite sign.

The implementation differs and not all of the same results statistic and post-estimation features are available. Estimated parameters and other results statistic differ mainly based on convergence tolerance of the optimization.

:

from statsmodels.discrete.discrete_model import Logit


We drop the middle category from the data and keep the two extreme categories.

:

mask_drop = data_student['apply'] == "somewhat likely"
# we need to remove the category also from the Categorical Index
data2['apply'].cat.remove_categories("somewhat likely", inplace=True)

/home/kevin/anaconda/lib/python3.8/site-packages/pandas/core/arrays/categorical.py:2630: FutureWarning: The inplace parameter in pandas.Categorical.remove_categories is deprecated and will be removed in a future version. Removing unused categories will always return a new Categorical object.
res = method(*args, **kwargs)

:

apply pared public gpa apply_codes apply_str dummy
0 very likely 0.0 0.0 3.26 9 very likely 1.0
2 unlikely 1.0 1.0 3.94 5 unlikely 1.0
5 unlikely 0.0 1.0 2.59 5 unlikely 1.0
8 unlikely 0.0 0.0 3.00 5 unlikely 1.0
10 unlikely 1.0 1.0 3.65 5 unlikely 1.0
:

mod_log = OrderedModel(data2['apply'],
data2[['pared', 'public', 'gpa']],
distr='logit')

res_log = mod_log.fit(method='bfgs', disp=False)
res_log.summary()

:

Dep. Variable: Log-Likelihood: apply -102.87 OrderedModel 213.7 Maximum Likelihood 228.0 Wed, 06 Oct 2021 10:59:01 260 256 4
coef std err z P>|z| [0.025 0.975] 1.2861 0.438 2.934 0.003 0.427 2.145 0.4014 0.444 0.903 0.366 -0.470 1.272 0.7854 0.489 1.605 0.108 -0.174 1.744 4.4147 1.485 2.974 0.003 1.505 7.324

The Logit model does not have a constant by default, we have to add it to our explanatory variables.

The results are essentially identical between Logit and ordered model up to numerical precision mainly resulting from convergence tolerance in the estimation.

The only difference is in the sign of the constant, Logit and OrdereModel have opposite signs of he constant. This is a consequence of the parameterization in terms of cut points in OrderedModel instead of including and constant column in the design matrix.

:

ex = add_constant(data2[['pared', 'public', 'gpa']], prepend=False)
mod_logit = Logit(data2['apply'].cat.codes, ex)

res_logit = mod_logit.fit(method='bfgs', disp=False)

:

res_logit.summary()

:

Dep. Variable: No. Observations: y 260 Logit 256 MLE 3 Wed, 06 Oct 2021 0.07842 10:59:01 -102.87 True -111.62 nonrobust 0.000556
coef std err z P>|z| [0.025 0.975] 1.2861 0.438 2.934 0.003 0.427 2.145 0.4014 0.444 0.903 0.366 -0.470 1.272 0.7854 0.489 1.605 0.108 -0.174 1.744 -4.4148 1.485 -2.974 0.003 -7.324 -1.505

Robust standard errors are also available in OrderedModel in the same way as in discrete.Logit. As example we specify HAC covariance type even though we have cross-sectional data and autocorrelation is not appropriate.

:

res_logit_hac = mod_logit.fit(method='bfgs', disp=False, cov_type="hac", cov_kwds={"maxlags": 2})
res_log_hac = mod_log.fit(method='bfgs', disp=False, cov_type="hac", cov_kwds={"maxlags": 2})

:

res_logit_hac.bse.values - res_log_hac.bse

:

pared                   1.088138e-07
public                  1.329897e-08
gpa                     4.202709e-09
unlikely/very likely    1.331628e-07
dtype: float64