Ordinal Regression

[1]:
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.

[2]:
url = "https://stats.idre.ucla.edu/stat/data/ologit.dta"
data_student = pd.read_stata(url)
[3]:
data_student.head(5)
[3]:
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
[4]:
data_student.dtypes
[4]:
apply     category
pared         int8
public        int8
gpa        float32
dtype: object
[5]:
data_student['apply'].dtype
[5]:
CategoricalDtype(categories=['unlikely', 'somewhat likely', 'very likely'], ordered=True, categories_dtype=object)

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:

[6]:
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
         Gradient evaluations: 21
[6]:
OrderedModel Results
Dep. Variable: apply Log-Likelihood: -358.75
Model: OrderedModel AIC: 727.5
Method: Maximum Likelihood BIC: 747.5
Date: Mon, 18 Mar 2024
Time: 09:27:35
No. Observations: 400
Df Residuals: 395
Df Model: 3
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
unlikely/somewhat likely 1.2968 0.468 2.774 0.006 0.381 2.213
somewhat likely/very likely 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:

[7]:
num_of_thresholds = 2
mod_prob.transform_threshold_params(res_prob.params[-num_of_thresholds:])
[7]:
array([      -inf, 1.29684541, 2.50285885,        inf])

Logit ordinal regression:

[8]:
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()
[8]:
OrderedModel Results
Dep. Variable: apply Log-Likelihood: -358.51
Model: OrderedModel AIC: 727.0
Method: Maximum Likelihood BIC: 747.0
Date: Mon, 18 Mar 2024
Time: 09:27:35
No. Observations: 400
Df Residuals: 395
Df Model: 3
coef std err z P>|z| [0.025 0.975]
pared 1.0476 0.266 3.942 0.000 0.527 1.569
public -0.0586 0.298 -0.197 0.844 -0.642 0.525
gpa 0.6158 0.261 2.363 0.018 0.105 1.127
unlikely/somewhat likely 2.2035 0.780 2.827 0.005 0.676 3.731
somewhat likely/very likely 0.7398 0.080 9.236 0.000 0.583 0.897
[9]:
predicted = res_log.model.predict(res_log.params, exog=data_student[['pared', 'public', 'gpa']])
predicted
[9]:
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.50896793, 0.38494062, 0.10609145]])
[10]:
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.

[11]:
# 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()
[11]:
OrderedModel Results
Dep. Variable: apply Log-Likelihood: -360.84
Model: OrderedModel AIC: 731.7
Method: Maximum Likelihood BIC: 751.6
Date: Mon, 18 Mar 2024
Time: 09:27:35
No. Observations: 400
Df Residuals: 395
Df Model: 3
coef std err z P>|z| [0.025 0.975]
pared 0.4690 0.117 4.021 0.000 0.240 0.698
public -0.1308 0.149 -0.879 0.379 -0.422 0.161
gpa 0.2198 0.134 1.638 0.101 -0.043 0.483
unlikely/somewhat likely 1.5370 0.405 3.792 0.000 0.742 2.332
somewhat likely/very likely 0.4082 0.093 4.403 0.000 0.226 0.590
[12]:
# 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()
[12]:
OrderedModel Results
Dep. Variable: apply Log-Likelihood: -359.75
Model: OrderedModel AIC: 729.5
Method: Maximum Likelihood BIC: 749.5
Date: Mon, 18 Mar 2024
Time: 09:27:36
No. Observations: 400
Df Residuals: 395
Df Model: 3
coef std err z P>|z| [0.025 0.975]
pared 0.5167 0.161 3.202 0.001 0.200 0.833
public 0.1081 0.168 0.643 0.520 -0.221 0.438
gpa 0.3344 0.154 2.168 0.030 0.032 0.637
unlikely/somewhat likely 0.8705 0.455 1.912 0.056 -0.022 1.763
somewhat likely/very likely 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.

[13]:
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
         Gradient evaluations: 24
[13]:
OrderedModel Results
Dep. Variable: apply Log-Likelihood: -358.51
Model: OrderedModel AIC: 727.0
Method: Maximum Likelihood BIC: 747.0
Date: Mon, 18 Mar 2024
Time: 09:27:36
No. Observations: 400
Df Residuals: 395
Df Model: 3
coef std err z P>|z| [0.025 0.975]
pared 1.0476 0.266 3.942 0.000 0.527 1.569
public -0.0586 0.298 -0.197 0.844 -0.642 0.525
gpa 0.6158 0.261 2.363 0.018 0.105 1.127
unlikely/somewhat likely 2.2035 0.780 2.827 0.005 0.676 3.731
somewhat likely/very likely 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.

[14]:
data_student["apply_codes"] = data_student['apply'].cat.codes * 2 + 5
data_student["apply_codes"].head()
[14]:
0    9
1    7
2    5
3    7
4    7
Name: apply_codes, dtype: int8
[15]:
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
[15]:
OrderedModel Results
Dep. Variable: apply_codes Log-Likelihood: -358.51
Model: OrderedModel AIC: 727.0
Method: Maximum Likelihood BIC: 747.0
Date: Mon, 18 Mar 2024
Time: 09:27:37
No. Observations: 400
Df Residuals: 395
Df Model: 3
coef std err z P>|z| [0.025 0.975]
pared 1.0477 0.266 3.942 0.000 0.527 1.569
public -0.0587 0.298 -0.197 0.844 -0.642 0.525
gpa 0.6157 0.261 2.362 0.018 0.105 1.127
5.0/7.0 2.2033 0.780 2.826 0.005 0.675 3.731
7.0/9.0 0.7398 0.080 9.236 0.000 0.583 0.897
[16]:
resf_logit.predict(data_student.iloc[:5])
[16]:
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.

[17]:
data_student["apply_str"] = np.asarray(data_student["apply"])
data_student["apply_str"].head()
[17]:
0        very likely
1    somewhat likely
2           unlikely
3    somewhat likely
4    somewhat likely
Name: apply_str, dtype: object
[18]:
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)
[19]:
OrderedModel.from_formula("apply_str ~ 0 + pared + public + gpa", data_student,
                          distr='logit')
[19]:
<statsmodels.miscmodels.ordinal_model.OrderedModel at 0x73a78009d900>

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.

[20]:
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.

[21]:
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
         Gradient evaluations: 28
                             OrderedModel Results
==============================================================================
Dep. Variable:                  apply   Log-Likelihood:                -358.50
Model:                   OrderedModel   AIC:                             729.0
Method:            Maximum Likelihood   BIC:                             752.9
Date:                Mon, 18 Mar 2024
Time:                        09:27:37
No. Observations:                 400
Df Residuals:                     394
Df Model:                           4
===============================================================================================
                                  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
===============================================================================================
[22]:
modfd_logit.k_vars
[22]:
4
[23]:
modfd_logit.k_constant
[23]:
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.

[24]:
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
         Gradient evaluations: 26
                             OrderedModel Results
==============================================================================
Dep. Variable:                  apply   Log-Likelihood:                -358.50
Model:                   OrderedModel   AIC:                             731.0
Method:            Maximum Likelihood   BIC:                             758.9
Date:                Mon, 18 Mar 2024
Time:                        09:27:38
No. Observations:                 400
Df Residuals:                     393
Df Model:                           5
===============================================================================================
                                  coef    std err          z      P>|z|      [0.025      0.975]
-----------------------------------------------------------------------------------------------
C(dummy)[0.0]                  -0.6834        nan        nan        nan         nan         nan
C(dummy)[1.0]                  -0.6508        nan        nan        nan         nan         nan
pared                           1.0489        nan        nan        nan         nan         nan
public                         -0.0588        nan        nan        nan         nan         nan
gpa                             0.6153        nan        nan        nan         nan         nan
unlikely/somewhat likely        1.5349        nan        nan        nan         nan         nan
somewhat likely/very likely     0.7398        nan        nan        nan         nan         nan
===============================================================================================
/opt/hostedtoolcache/Python/3.10.13/x64/lib/python3.10/site-packages/statsmodels/base/model.py:595: HessianInversionWarning: Inverting hessian failed, no bse or cov_params available
  warnings.warn('Inverting hessian failed, no bse or cov_params '
[25]:
resfd2_logit.predict(data_student.iloc[:5])
[25]:
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
[26]:
resf_logit.predict()
[26]:
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.50896793, 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.

[27]:
from statsmodels.discrete.discrete_model import Logit
from statsmodels.tools.tools import add_constant

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

[28]:
mask_drop = data_student['apply'] == "somewhat likely"
data2 = data_student.loc[~mask_drop, :].copy()
# we need to remove the category also from the Categorical Index
data2['apply'] = data2['apply'].cat.remove_categories("somewhat likely")
data2["apply"].head()
[28]:
0     very likely
2        unlikely
5        unlikely
8        unlikely
10       unlikely
Name: apply, dtype: category
Categories (2, object): ['unlikely' < 'very likely']
[29]:
mod_log = OrderedModel(data2['apply'],
                        data2[['pared', 'public', 'gpa']],
                        distr='logit')

res_log = mod_log.fit(method='bfgs', disp=False)
res_log.summary()
[29]:
OrderedModel Results
Dep. Variable: apply Log-Likelihood: -102.87
Model: OrderedModel AIC: 213.7
Method: Maximum Likelihood BIC: 228.0
Date: Mon, 18 Mar 2024
Time: 09:27:38
No. Observations: 260
Df Residuals: 256
Df Model: 3
coef std err z P>|z| [0.025 0.975]
pared 1.2861 0.438 2.934 0.003 0.427 2.145
public 0.4014 0.444 0.903 0.366 -0.470 1.272
gpa 0.7854 0.489 1.605 0.108 -0.174 1.744
unlikely/very likely 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.

[30]:
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)
[31]:
res_logit.summary()
[31]:
Logit Regression Results
Dep. Variable: y No. Observations: 260
Model: Logit Df Residuals: 256
Method: MLE Df Model: 3
Date: Mon, 18 Mar 2024 Pseudo R-squ.: 0.07842
Time: 09:27:38 Log-Likelihood: -102.87
converged: True LL-Null: -111.62
Covariance Type: nonrobust LLR p-value: 0.0005560
coef std err z P>|z| [0.025 0.975]
pared 1.2861 0.438 2.934 0.003 0.427 2.145
public 0.4014 0.444 0.903 0.366 -0.470 1.272
gpa 0.7854 0.489 1.605 0.108 -0.174 1.744
const -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.

[32]:
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})
[33]:
res_logit_hac.bse.values - res_log_hac.bse
[33]:
pared                   9.022236e-08
public                 -7.249837e-08
gpa                     7.653233e-08
unlikely/very likely    2.800466e-07
dtype: float64

Last update: Mar 18, 2024