Ordinal regression: ordered outcomes and proportional odds
Low, medium, high is more than three labels. Ordinal logistic regression uses the order with one set of slopes, provided the proportional-odds assumption holds.
What runs in CodeSplash
- Ordinal logistic regression (proportional odds) Verified in Python and R
You will be able to
- Explain cumulative logits and thresholds
- State the proportional-odds assumption and read the Brant test
- Interpret a single odds ratio that applies across cut-points
- Say why a linear model on the codes can mislead
Read first
A ladder of cut-points
ReadThink of housing satisfaction as a continuous feeling chopped into Low, Medium and High by two thresholds. A predictor shifts the feeling up or down.
The model compares "at or below this level" for each cut-point:
Each cut-point has its own threshold , and every cut-point shares the same slopes. That's the proportional oddsProportional oddsThe assumption that a predictor has the same odds ratio at every cut-point of an ordered outcome. assumption.
Count the savings
PredictPredict first
Three outcome levels and six predictor columns. An ordinal model has two thresholds plus one slope per column. How many parameters does it estimate? A multinomial model would need 14.
Make your guess between 1 and 30 parameters, then reveal.
Reveal
, which is the 8 on the card below. It uses the ordering to spend far fewer parameters.
Read the card
In the appχ²(6, N = 1681) = 169.73, p < .001, McFadden R² = .05
- LR χ²
- 169.73
- p
- < .001
- McFadden R²
- 0.0465
- Brant p
- .201
- AIC
- 3495.15
Effect size
- McFadden R² 0.0465
Plots
View data
| Odds ratio | high | Term | low |
|---|---|---|---|
| 1.762 | 2.163 | Infl: Medium | 1.435 |
| 3.628 | 4.655 | Infl: High | 2.828 |
| 0.5642 | 0.7127 | Type: Apartment | 0.4466 |
| 0.6934 | 0.9398 | Type: Atrium | 0.5115 |
| 0.3359 | 0.4520 | Type: Terrace | 0.2496 |
| 1.434 | 1.729 | Cont: High | 1.189 |
Assumptions
- Proportional odds — Brant χ²(6) = 8.53, p = .201.
- Observations per category — Smallest outcome category: Medium with 446 rows.
- Multicollinearity — Largest VIF 1.03 (Cont).
Coefficients
| Term | B | SE | z | p | Odds ratio | 95% CI low | 95% CI high | Brant p |
|---|---|---|---|---|---|---|---|---|
| Infl: Medium | 0.5664 | 0.1047 | 5.412 | < .001 | 1.762 | 1.435 | 2.163 | .573 |
| Infl: High | 1.289 | 0.1272 | 10.136 | < .001 | 3.628 | 2.828 | 4.655 | .658 |
| Type: Apartment | −0.5724 | 0.1192 | −4.800 | < .001 | 0.5642 | 0.4466 | 0.7127 | .494 |
| Type: Atrium | −0.3662 | 0.1552 | −2.360 | .018 | 0.6934 | 0.5115 | 0.9398 | .094 |
| Type: Terrace | −1.091 | 0.1515 | −7.202 | < .001 | 0.3359 | 0.2496 | 0.4520 | .860 |
| Cont: High | 0.3603 | 0.0955 | 3.771 | < .001 | 1.434 | 1.189 | 1.729 | .257 |
Positive B: higher outcome categories more likely. P(Y ≤ j) = F(ζ_j − x'B); Wald z tests; Brant p per term.
Cut-points (thresholds ζ)
| Split | ζ | SE |
|---|---|---|
| Low|Medium | −0.4961 | 0.1248 |
| Medium|High | 0.6907 | 0.1255 |
- Cumulative logit model (MASS::polr parameterization); outcome order: Low < Medium < High; categorical predictors against their first level.
The exact R script · R R version 4.5.1 (2025-06-13)
# Ordinal logistic regression (proportional odds)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method regression.ordinal 2.0.1 · spec 91aa7e0a91455ca8
# Dataset: housing (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/housing.parquet", col_select = c("Sat", "Infl", "Type", "Cont")))
n_input <- nrow(df)
df[["Sat"]] <- factor(df[["Sat"]], levels = c("Low", "Medium", "High")) # stored level order
df[["Infl"]] <- factor(df[["Infl"]], levels = c("Low", "Medium", "High")) # stored level order
df[["Type"]] <- factor(df[["Type"]], levels = c("Tower", "Apartment", "Atrium", "Terrace")) # stored level order
df[["Cont"]] <- factor(df[["Cont"]], levels = c("Low", "High")) # stored level order
df <- df[stats::complete.cases(df[c("Sat", "Infl", "Type", "Cont")]), , drop = FALSE] # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("Sat", "Infl", "Type", "Cont")) # infinite values stop the run (registry/errors.yaml)
# %% Outcome and model
outcome <- "Sat"
predictors <- c("Infl", "Type", "Cont")
link <- "logit" # logit | probit
interactions <- "none"
conf <- 0.95
levels_y <- levels(df[[outcome]]) # stored order = outcome order (lowest first)
J <- length(levels_y)
if (J < 3) cs_error("CS_E_TOO_FEW_GROUPS", column = outcome, min = 3, k = J) # two levels: logistic regression
y <- as.integer(df[[outcome]]) # 1..J
terms_all <- cs_design_labels(df, predictors, interactions)
# Degenerate input stops with a catalog error; Python runs the same checks in the same order.
# More rows than coefficients: the slopes plus J - 1 thresholds.
cs_check_rows(nrow(df), (length(terms_all) - 1) + (J - 1) + 1, "Ordinal regression")
for (col in predictors) cs_check_not_constant(df[[col]], col) # one value (or one level with data) is no variation
fml <- cs_model_formula(outcome, predictors, interactions)
Xf <- model.matrix(fml, data = df) # treatment dummies, intercept first
if (qr(Xf)$rank < ncol(Xf)) cs_error("CS_E_COLLINEAR")
stopifnot(length(terms_all) == ncol(Xf))
colnames(Xf) <- terms_all
X <- Xf[, -1, drop = FALSE] # thresholds replace the intercept
terms <- colnames(X)
n <- nrow(X)
p <- ncol(X)
# %% Fit: MASS::polr (BFGS) for starting values, then the shared Newton polish
pf0 <- MASS::polr(fml, data = df, method = if (link == "logit") "logistic" else "probit", Hess = FALSE, control = list(reltol = 1e-12, maxit = 2000))
fitc <- cs_clm_fit(X, y, J, c(unname(pf0$coefficients), unname(pf0$zeta)), link)
theta <- fitc$theta
V <- fitc$cov
log_lik <- fitc$ll
b <- theta[seq_len(p)]
cuts <- theta[p + seq_len(J - 1)]
se <- sqrt(diag(V))
zval <- theta / se
pval <- 2 * pnorm(abs(zval), lower.tail = FALSE)
zc <- qnorm(1 - (1 - conf) / 2)
counts <- tabulate(y, nbins = J)
null_log_lik <- sum(counts * log(counts / n))
lr_chi2 <- 2 * (log_lik - null_log_lik)
lr_p <- pchisq(lr_chi2, p, lower.tail = FALSE)
mcfadden <- 1 - log_lik / null_log_lik
aic <- -2 * log_lik + 2 * (p + J - 1)
bic <- -2 * log_lik + log(n) * (p + J - 1)
br <- cs_brant(Xf, y, J) # proportional-odds check from the J - 1 binary logits
# %% Assumptions
assumptions <- list(list(key = "proportional_odds", label = "Proportional odds", status = if (br$p < 0.05) "warn" else "pass",
statistic = br$chi2, p = br$p,
detail = paste0(sprintf("Brant χ²(%d) = %.2f, %s", br$df, br$chi2, cs_fmt_p(br$p)),
if (br$p < 0.05) "; effects differ across cut-points — consider a multinomial model." else ".")))
min_n <- min(counts)
assumptions[[2]] <- list(key = "sample_size", label = "Observations per category", status = if (min_n < 10) "warn" else "pass", statistic = min_n,
detail = sprintf("Smallest outcome category: %s with %d rows.", levels_y[which.min(counts)], min_n))
main_cols <- terms[!grepl(" × ", terms, fixed = TRUE)]
vifs <- cs_gvif(X, main_cols, df, predictors) # one generalized VIF per factor
if (length(vifs)) {
mv <- max(vifs)
assumptions[[3]] <- list(key = "multicollinearity", label = "Multicollinearity", status = if (mv < 5) "pass" else if (mv < 10) "warn" else "fail",
statistic = mv, detail = sprintf("Largest VIF %.2f (%s).", mv, names(vifs)[which.max(vifs)]))
}
# %% Result
alpha <- 1 - conf
values <- list()
coefs <- list()
for (j in seq_len(p)) {
t <- terms[j]
row <- list(term = t, estimate = b[j], se = se[j], z = zval[j], p = pval[j], ci_low = b[j] - zc * se[j], ci_high = b[j] + zc * se[j])
if (link == "logit") row <- c(row, list(or = exp(row$estimate), or_ci_low = exp(row$ci_low), or_ci_high = exp(row$ci_high)))
row$brant_p <- br$terms[[j]]$p
coefs[[j]] <- row
for (key in c("estimate", "se", "z", "p", "ci_low", "ci_high", "or", "or_ci_low", "or_ci_high", "brant_p")) {
if (!is.null(row[[key]])) values[[sprintf("%s[%s]", if (key == "estimate") "coef" else key, t)]] <- row[[key]]
}
}
cut_rows <- list()
for (j in seq_len(J - 1)) {
label <- paste0(levels_y[j], "|", levels_y[j + 1])
cut_rows[[j]] <- list(cut = label, estimate = cuts[j], se = se[p + j])
values[[sprintf("cut[%s]", label)]] <- cuts[j]
values[[sprintf("cut_se[%s]", label)]] <- se[p + j]
}
values <- c(values, list(n = n, k = p, n_levels = J, link = link, log_lik = log_lik, null_log_lik = null_log_lik, lr_chi2 = lr_chi2,
lr_df = p, lr_p = lr_p, mcfadden_r2 = mcfadden, aic = aic, bic = bic, brant_chi2 = br$chi2, brant_df = br$df,
brant_p = br$p, min_category_n = min_n,
epv = min_n / p, converged = max(abs(cs_clm_loglik_grad(theta, X, y, J, link)$grad)) < 1e-6,
n_params = p + J - 1, max_interaction_order = if (interactions != "none" && length(predictors) >= 2) 2 else 1, missing_share = if (n_input > 0) n_dropped / n_input else 0))
pct <- sprintf("%.0f%%", conf * 100)
coef_cols <- list(list(key = "term", label = "Term", type = "string"), list(key = "estimate", label = "B", type = "number"),
list(key = "se", label = "SE", type = "number"), list(key = "z", label = "z", type = "number"), list(key = "p", label = "p", type = "pvalue"))
coef_cols <- c(coef_cols, if (link == "logit") {
list(list(key = "or", label = "Odds ratio", type = "number"), list(key = "or_ci_low", label = paste(pct, "CI low"), type = "number"),
list(key = "or_ci_high", label = paste(pct, "CI high"), type = "number"))
} else {
list(list(key = "ci_low", label = paste(pct, "CI low"), type = "number"), list(key = "ci_high", label = paste(pct, "CI high"), type = "number"))
}, list(list(key = "brant_p", label = "Brant p", type = "pvalue")))
summary <- sprintf("%s model of %s (%d levels, n = %d): χ²(%d) = %.2f, %s; Brant test of proportional odds %s.",
if (link == "logit") "Proportional-odds" else "Ordinal probit", outcome, J, n, p, lr_chi2, cs_fmt_p(lr_p), cs_fmt_p(br$p))
charts <- list()
if (link == "logit") {
charts[[1]] <- cs_chart("odds", "forest", "Cumulative odds ratios", list(
label = cs_col("Term", vapply(coefs, `[[`, "", "term"), kind = "categorical"), estimate = cs_col("Odds ratio", vapply(coefs, `[[`, 0, "or")),
low = cs_col("low", vapply(coefs, `[[`, 0, "or_ci_low")), high = cs_col("high", vapply(coefs, `[[`, 0, "or_ci_high"))),
controls = list(reference = 1, log = TRUE))
}
cs_publish(list(
method = "regression.ordinal",
methodVersion = "2.0.1",
title = if (link == "logit") "Ordinal logistic regression" else "Ordinal probit regression",
engine = cs_engine_info("stats", "MASS", "nanoparquet"),
n = n,
summary = summary,
apa = sprintf("χ²(%d, N = %d) = %s, %s, McFadden R² = %s", p, n, cs_fmt_num(lr_chi2), cs_fmt_p(lr_p), cs_fmt_num(mcfadden, leading_zero = FALSE)),
statistics = list(list(key = "lr_chi2", label = "LR χ²", value = lr_chi2), list(key = "lr_p", label = "p", value = lr_p, format = "p"),
list(key = "mcfadden_r2", label = "McFadden R²", value = mcfadden), list(key = "brant_p", label = "Brant p", value = br$p, format = "p"),
list(key = "aic", label = "AIC", value = aic)),
tables = list(
list(key = "coefficients", title = "Coefficients", columns = coef_cols, rows = coefs,
note = "Positive B: higher outcome categories more likely. P(Y ≤ j) = F(ζ_j − x'B); Wald z tests; Brant p per term."),
list(key = "cutpoints", title = "Cut-points (thresholds ζ)", columns = list(
list(key = "cut", label = "Split", type = "string"), list(key = "estimate", label = "ζ", type = "number"), list(key = "se", label = "SE", type = "number")),
rows = cut_rows)
),
effectSizes = list(list(key = "mcfadden_r2", label = "McFadden R²", value = mcfadden)),
assumptions = assumptions,
warnings = warnings,
notes = list(sprintf("Cumulative %s model (MASS::polr parameterization); outcome order: %s; categorical predictors against their first level.",
link, paste(levels_y, collapse = " < "))),
charts = charts,
values = values
))
χ²(6, N = 1681) = 169.73, p < .001, McFadden R² = .05
- LR χ²
- 169.73
- p
- < .001
- McFadden R²
- 0.0465
- Brant p
- .201
- AIC
- 3495.15
Effect size
- McFadden R² 0.0465
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Proportional odds — Brant χ²(6) = 8.53, p = .201.
- Observations per category — Smallest outcome category: Medium with 446 rows.
- Multicollinearity — Largest VIF 1.03 (Cont).
Coefficients
| Term | B | SE | z | p | Odds ratio | 95% CI low | 95% CI high | Brant p |
|---|---|---|---|---|---|---|---|---|
| Infl: Medium | 0.5664 | 0.1047 | 5.412 | < .001 | 1.762 | 1.435 | 2.163 | .573 |
| Infl: High | 1.289 | 0.1272 | 10.136 | < .001 | 3.628 | 2.828 | 4.655 | .658 |
| Type: Apartment | −0.5724 | 0.1192 | −4.800 | < .001 | 0.5642 | 0.4466 | 0.7127 | .494 |
| Type: Atrium | −0.3662 | 0.1552 | −2.360 | .018 | 0.6934 | 0.5115 | 0.9398 | .094 |
| Type: Terrace | −1.091 | 0.1515 | −7.202 | < .001 | 0.3359 | 0.2496 | 0.4520 | .860 |
| Cont: High | 0.3603 | 0.0955 | 3.771 | < .001 | 1.434 | 1.189 | 1.729 | .257 |
Positive B: higher outcome categories more likely. P(Y ≤ j) = F(ζ_j − x'B); Wald z tests; Brant p per term.
Cut-points (thresholds ζ)
| Split | ζ | SE |
|---|---|---|
| Low|Medium | −0.4961 | 0.1248 |
| Medium|High | 0.6907 | 0.1255 |
- Cumulative logit model (MASS::polr parameterization); outcome order: Low < Medium < High; categorical predictors against their first level.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Ordinal logistic regression (proportional odds)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method regression.ordinal 2.0.1 · spec 91aa7e0a91455ca8
# Dataset: housing (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd
from scipy import stats
from statsmodels.miscmodels.ordinal_model import OrderedModel
import codesplash as cs
from codesplash.errors import check_not_constant
from codesplash.stats import glm as csglm
from codesplash.stats import regression as csreg
# %% Data
df = pd.read_parquet("tests/parity/fixtures/housing.parquet", columns=["Sat", "Infl", "Type", "Cont"])
n_input = len(df)
df["Sat"] = pd.Categorical(df["Sat"], categories=["Low", "Medium", "High"]) # stored level order
df["Infl"] = pd.Categorical(df["Infl"], categories=["Low", "Medium", "High"]) # stored level order
df["Type"] = pd.Categorical(df["Type"], categories=["Tower", "Apartment", "Atrium", "Terrace"]) # stored level order
df["Cont"] = pd.Categorical(df["Cont"], categories=["Low", "High"]) # stored level order
df = df.dropna(subset=["Sat", "Infl", "Type", "Cont"]) # listwise deletion over the analysis columns
df["Sat"] = df["Sat"].cat.remove_unused_categories()
df["Infl"] = df["Infl"].cat.remove_unused_categories()
df["Type"] = df["Type"].cat.remove_unused_categories()
df["Cont"] = df["Cont"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["Sat", "Infl", "Type", "Cont"]) # infinite values stop the run (registry/errors.yaml)
# %% Outcome and design matrix
outcome = "Sat"
predictors = ["Infl", "Type", "Cont"]
link = "logit" # logit | probit
interactions = "none"
conf = 0.95
levels_y = [str(x) for x in df[outcome].cat.categories] # stored order = outcome order (lowest first)
J = len(levels_y)
if J < 3: # two levels: logistic regression
cs.cs_error("CS_E_TOO_FEW_GROUPS", column=outcome, min=3, k=J)
y = df[outcome].cat.codes.to_numpy() # 0..J−1
Xf = csreg.design_matrix(df, predictors, interactions) # treatment dummies, intercept first
# Degenerate input stops with a catalog error; R runs the same checks in the same order.
# More rows than coefficients: the slopes plus J − 1 thresholds.
cs.check_rows(len(df), (Xf.shape[1] - 1) + (J - 1) + 1, "Ordinal regression")
for col in predictors:
check_not_constant(df[col], col) # one value (or one level with data) is no variation
if np.linalg.matrix_rank(Xf.to_numpy()) < Xf.shape[1]:
cs.cs_error("CS_E_COLLINEAR")
X = Xf.drop(columns="(Intercept)") # thresholds replace the intercept
terms = list(X.columns)
n, p = X.shape
# %% Fit: OrderedModel (BFGS) for starting values, then the shared Newton polish
om = OrderedModel(y, X, distr=link).fit(method="bfgs", maxiter=2000, gtol=1e-8, disp=False)
start_cuts = om.model.transform_threshold_params(om.params)[1:-1] # actual cut-points ζ
theta, V, log_lik = csglm.clm_fit(X.to_numpy(), y, J, np.concatenate([np.asarray(om.params)[:p], start_cuts]), link)
b, cuts = theta[:p], theta[p:]
se = np.sqrt(np.diag(V))
zval = theta / se
pval = 2 * stats.norm.sf(np.abs(zval))
zc = stats.norm.ppf(1 - (1 - conf) / 2)
counts = np.bincount(y, minlength=J)
null_log_lik = float(np.sum(counts * np.log(counts / n)))
lr_chi2 = 2 * (log_lik - null_log_lik)
lr_p = float(stats.chi2.sf(lr_chi2, p))
mcfadden = 1 - log_lik / null_log_lik
aic = -2 * log_lik + 2 * (p + J - 1)
bic = -2 * log_lik + np.log(n) * (p + J - 1)
br = csglm.brant(Xf.to_numpy(), y, J) # proportional-odds check from the J − 1 binary logits
# %% Assumptions
assumptions = [{"key": "proportional_odds", "label": "Proportional odds", "status": "warn" if br["p"] < 0.05 else "pass",
"statistic": br["chi2"], "p": br["p"],
"detail": f"Brant χ²({br['df']}) = {br['chi2']:.2f}, {cs.fmt_p(br['p'])}" + ("; effects differ across cut-points — consider a multinomial model." if br["p"] < 0.05 else ".")}]
min_n = int(counts.min())
assumptions.append({"key": "sample_size", "label": "Observations per category", "status": "warn" if min_n < 10 else "pass", "statistic": min_n,
"detail": f"Smallest outcome category: {levels_y[int(counts.argmin())]} with {min_n} rows."})
main_cols = [c for c in terms if csreg.TIMES not in c]
vifs = csreg.gvif(X, main_cols, df, predictors) # one generalized VIF per factor
if vifs:
worst = max(vifs, key=vifs.get)
assumptions.append({"key": "multicollinearity", "label": "Multicollinearity", "status": "pass" if vifs[worst] < 5 else ("warn" if vifs[worst] < 10 else "fail"),
"statistic": vifs[worst], "detail": f"Largest VIF {vifs[worst]:.2f} ({worst})."})
# %% Result
alpha = 1 - conf
values = {}
coefs = []
for j, t in enumerate(terms):
row = {"term": t, "estimate": float(b[j]), "se": float(se[j]), "z": float(zval[j]), "p": float(pval[j]),
"ci_low": float(b[j] - zc * se[j]), "ci_high": float(b[j] + zc * se[j])}
if link == "logit":
row.update({"or": float(np.exp(row["estimate"])), "or_ci_low": float(np.exp(row["ci_low"])), "or_ci_high": float(np.exp(row["ci_high"]))})
row["brant_p"] = br["terms"][j]["p"]
coefs.append(row)
for key in ("estimate", "se", "z", "p", "ci_low", "ci_high", "or", "or_ci_low", "or_ci_high", "brant_p"):
if key in row:
values[f"{'coef' if key == 'estimate' else key}[{t}]"] = row[key]
cut_rows = []
for j in range(J - 1):
label = f"{levels_y[j]}|{levels_y[j + 1]}"
cut_rows.append({"cut": label, "estimate": float(cuts[j]), "se": float(se[p + j])})
values[f"cut[{label}]"] = float(cuts[j])
values[f"cut_se[{label}]"] = float(se[p + j])
values.update({"n": n, "k": p, "n_levels": J, "link": link, "log_lik": float(log_lik), "null_log_lik": null_log_lik, "lr_chi2": float(lr_chi2),
"lr_df": float(p), "lr_p": lr_p, "mcfadden_r2": float(mcfadden), "aic": float(aic), "bic": float(bic),
"brant_chi2": br["chi2"], "brant_df": float(br["df"]), "brant_p": br["p"], "min_category_n": min_n,
"epv": min_n / p, "converged": bool(np.max(np.abs(csglm.clm_loglik_grad(theta, X.to_numpy(), y, J, link)[1])) < 1e-6),
"n_params": p + J - 1, "max_interaction_order": 2 if interactions != "none" and len(predictors) >= 2 else 1, "missing_share": n_dropped / n_input if n_input else 0.0})
pct = f"{conf:.0%}"
coef_cols = [{"key": "term", "label": "Term", "type": "string"}, {"key": "estimate", "label": "B", "type": "number"},
{"key": "se", "label": "SE", "type": "number"}, {"key": "z", "label": "z", "type": "number"}, {"key": "p", "label": "p", "type": "pvalue"}]
coef_cols += ([{"key": "or", "label": "Odds ratio", "type": "number"}, {"key": "or_ci_low", "label": f"{pct} CI low", "type": "number"},
{"key": "or_ci_high", "label": f"{pct} CI high", "type": "number"}] if link == "logit" else
[{"key": "ci_low", "label": f"{pct} CI low", "type": "number"}, {"key": "ci_high", "label": f"{pct} CI high", "type": "number"}])
coef_cols.append({"key": "brant_p", "label": "Brant p", "type": "pvalue"})
summary = (f"{'Proportional-odds' if link == 'logit' else 'Ordinal probit'} model of {outcome} ({J} levels, n = {n}): "
f"χ²({p}) = {lr_chi2:.2f}, {cs.fmt_p(lr_p)}; Brant test of proportional odds {cs.fmt_p(br['p'])}.")
charts = []
if link == "logit":
charts.append(cs.chart("odds", "forest", "Cumulative odds ratios", {
"label": cs.col("Term", [c["term"] for c in coefs], kind="categorical"), "estimate": cs.col("Odds ratio", [c["or"] for c in coefs]),
"low": cs.col("low", [c["or_ci_low"] for c in coefs]), "high": cs.col("high", [c["or_ci_high"] for c in coefs])}, controls={"reference": 1, "log": True}))
cs.publish({
"method": "regression.ordinal",
"methodVersion": "2.0.1",
"title": "Ordinal logistic regression" if link == "logit" else "Ordinal probit regression",
"engine": cs.engine_info("pandas", "numpy", "statsmodels", "scipy"),
"n": n,
"summary": summary,
"apa": f"χ²({p}, N = {n}) = {cs.fmt_num(lr_chi2)}, {cs.fmt_p(lr_p)}, McFadden R² = {cs.fmt_num(mcfadden, leading_zero=False)}",
"statistics": [{"key": "lr_chi2", "label": "LR χ²", "value": float(lr_chi2)}, {"key": "lr_p", "label": "p", "value": lr_p, "format": "p"},
{"key": "mcfadden_r2", "label": "McFadden R²", "value": float(mcfadden)}, {"key": "brant_p", "label": "Brant p", "value": br["p"], "format": "p"},
{"key": "aic", "label": "AIC", "value": float(aic)}],
"tables": [
{"key": "coefficients", "title": "Coefficients", "columns": coef_cols, "rows": coefs,
"note": "Positive B: higher outcome categories more likely. P(Y ≤ j) = F(ζ_j − x'B); Wald z tests; Brant p per term."},
{"key": "cutpoints", "title": "Cut-points (thresholds ζ)", "columns": [
{"key": "cut", "label": "Split", "type": "string"}, {"key": "estimate", "label": "ζ", "type": "number"}, {"key": "se", "label": "SE", "type": "number"}],
"rows": cut_rows},
],
"effectSizes": [{"key": "mcfadden_r2", "label": "McFadden R²", "value": float(mcfadden)}],
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"Cumulative {link} model (MASS::polr parameterization); outcome order: {' < '.join(levels_y)}; categorical predictors against their first level."],
"charts": charts,
"values": values,
})
Satisfaction among 1,681 Copenhagen households: (6) = 169.7, p < .001.
An odds ratio here applies at every cut-point. A value of 2 means twice the odds of being above Low rather than at it, and twice the odds of being above Medium rather than at or below it. That single number is the model's main appeal, and it only holds if the assumption does.
Check the assumption
ReadThe Brant testBrant testCompares separate binary logits at each cut-point to test the proportional-odds assumption. compares separate binary logits at each cut-point: if slopes really are shared, they should be close.
Here (6) = 8.5, p = .201: no sign of trouble.
On the survey model of exercise, the test gives p = .038, a warning that some predictor works differently across cut-points. In that case, consider a multinomial model or a partial proportional-odds model.
Like other assumption tests, it's sensitive with large , so compare the separate slopes on a practical scale too.
Why not a line on the codes?
ReflectCoding Low, Medium, High as 1, 2, 3 and running a linear regression assumes the gaps are equal and that means tell the whole story. Both can be wrong, and that can produce false positives and even reversed effects, especially when categories are unevenly used.
With many ordered levels and symmetric responses, a linear model is often a reasonable approximation. Is that true of your scale? How would you check?
Logit or probit?
ReadThe Link option changes the shape assumed for the hidden feeling. Logit gives odds ratios. Probit assumes a normal latent trait, and its coefficients are in standard-deviation units of that trait. The two rarely disagree on conclusions: on similar housing data with fewer predictors, probit reports = 113.4, p < .001.
Check your understanding
CheckpointCheck yourself
An outcome has 5 ordered levels. How many thresholds does the model have?
Show the answer
Answer: 4
Levels minus one: 5 − 1 = 4.
Check yourself
What does proportional odds assume?
Show the answer
Answer: a
It's one slope for all cut-points. It doesn't assume equal gaps: the thresholds are free.
Check yourself
The Brant test gives p < .001 with n = 40,000, and the separate slopes differ only slightly. What do you do?
Show the answer
Answer: b
With a very large n, trivial differences become significant. Judge by whether they'd change any conclusion, and report what you did.
Fit yours
In the appPick an Ordered outcome, set the order of its levels if they aren't already ordered, and add your Predictors.
import pandas as pd
from statsmodels.miscmodels.ordinal_model import OrderedModel
df = pd.read_csv("housing.csv")
y = pd.Series(pd.Categorical(df["Sat"], categories=["Low", "Medium", "High"], ordered=True))
X = pd.get_dummies(df[["Infl", "Type", "Cont"]], drop_first=True, dtype=float)
fit = OrderedModel(y, X, distr="logit").fit(method="bfgs", disp=0)
print(fit.summary())library(MASS)
df <- read.csv("housing.csv")
df$Sat <- factor(df$Sat, levels = c("Low", "Medium", "High"), ordered = TRUE)
fit <- polr(Sat ~ Infl + Type + Cont, data = df, Hess = TRUE)
summary(fit)
exp(coef(fit))Recap
Recap- Ordinal models use thresholds plus one shared set of slopes.
- Proportional odds means one odds ratio applies at every cut-point. Check it with Brant.
- Treating levels as numbers assumes equal gaps, which can mislead.
- Probit reads in latent standard deviations, logit in odds ratios.
Concepts in this lesson