Skip to content

Multinomial logistic regression: more than two categories

When the outcome has several unordered categories, you fit one set of coefficients per non-reference category. See how to read them and how quickly they use up your data.

Applied ~9 min9 steps

What runs in CodeSplash

You will be able to

  • Describe the model as logits against one reference category
  • Read relative risk ratios for each category
  • Count parameters and judge if you have enough events
  • State the independence of irrelevant alternatives assumption

Read first

01

One binary model per category

Read

Which housing type does a household live in? With JJ unordered categories, the model picks one as the reference and fits J−1J-1 sets of log-odds, each against that reference:

ln⁡P(Y=j)P(Y=ref)=β0j+β1jx1+…\ln\frac{P(Y=j)}{P(Y=\text{ref})} = \beta_{0j} + \beta_{1j} x_1 + \dots

Every predictor gets its own coefficient for each non-reference category. A predictor might raise the chance of one category and lower another's.

02

Make a prediction

Predict

Predict first

An outcome has 4 categories. There's one numeric predictor plus two factors with 3 levels each, so the predictors make 5 columns. Including intercepts, how many coefficients does the model estimate?

Make your guess between 1 and 30 parameters, then reveal.

Reveal

Three non-reference categories, each with an intercept and 5 slopes: 3×6=183 \times 6 = 18. Parameters multiply quickly in this model.

03

Read the card

In the app
Multinomial logistic regressionRecorded · Python and R agreeRecorded 2026-11-17 · 127 values compared
R

χ²(9, N = 1681) = 55.11, p < .001, McFadden R² = .01

LR χ²
55.112
p
< .001
McFadden R²
0.0129
AIC
4253.31

Effect size

  • McFadden R² 0.0129

Plots

Relative-risk ratios vs TowerHow large are several estimates, how precise, and which exclude the null?
View data
RRRTypehighTermlow
0.9241Apartment1.222Infl: Medium0.6988
1.278Apartment1.773Infl: High0.9215
1.745Apartment2.231Cont: High1.365
0.7461Atrium1.082Infl: Medium0.5144
1.123Atrium1.717Infl: High0.7345
2.344Atrium3.273Cont: High1.678
0.7202Terrace1.017Infl: Medium0.5100
0.6707Terrace1.035Infl: High0.4348
2.254Terrace3.100Cont: High1.640

Assumptions

  • Independence of irrelevant alternatives — Assumed by the model: the odds between two categories should not change if another category were removed or merged.
  • Observations per category — Smallest category: Atrium with 239 rows for 3 slope(s) per equation.
  • Multicollinearity — Largest VIF 1.01 (Cont).

Coefficients and relative-risk ratios (vs Tower)

TypeTermBSEzpRRR95% CI low95% CI high
Apartment(Intercept)0.33240.12552.649.0081.3941.0901.783
ApartmentInfl: Medium−0.07890.1426−0.5536.5800.92410.69881.222
ApartmentInfl: High0.24540.16691.470.1411.2780.92151.773
ApartmentCont: High0.55700.12534.447< .0011.7451.3652.231
Atrium(Intercept)−0.90190.1721−5.240< .0010.40580.28960.5686
AtriumInfl: Medium−0.29290.1897−1.544.1220.74610.51441.082
AtriumInfl: High0.11600.21660.5356.5921.1230.73451.717
AtriumCont: High0.85180.17044.999< .0012.3441.6783.273
Terrace(Intercept)−0.60840.1599−3.804< .0010.54420.39780.7446
TerraceInfl: Medium−0.32820.1761−1.864.0620.72020.51001.017
TerraceInfl: High−0.39940.2212−1.806.0710.67070.43481.035
TerraceCont: High0.81280.16255.003< .0012.2541.6403.100

Each category against Tower: RRR = exp(B), the multiplicative change in P(category) / P(Tower).

  • Baseline-category logit; reference Type = Tower; categorical predictors against their first level; Wald z tests.
The exact R script · R R version 4.5.1 (2025-06-13)
# Multinomial logistic regression
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method regression.multinomial 2.0.1 · spec 44808b2efdf5fa80
# 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("Type", "Infl", "Cont")))
n_input <- nrow(df)
df[["Type"]] <- factor(df[["Type"]], levels = c("Tower", "Apartment", "Atrium", "Terrace"))  # stored level order
df[["Infl"]] <- factor(df[["Infl"]], levels = c("Low", "Medium", "High"))  # stored level order
df[["Cont"]] <- factor(df[["Cont"]], levels = c("Low", "High"))  # stored level order
df <- df[stats::complete.cases(df[c("Type", "Infl", "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("Type", "Infl", "Cont"))  # infinite values stop the run (registry/errors.yaml)

# %% Outcome and model
outcome <- "Type"
predictors <- c("Infl", "Cont")
interactions <- "none"
conf <- 0.95
stored <- levels(df[[outcome]])
J <- length(stored)
if (J < 3) cs_error("CS_E_TOO_FEW_GROUPS", column = outcome, min = 3, k = J)  # two categories: logistic regression
reference <- stored[1]  # default: the first stored level
if (!(reference %in% stored)) cs_error("CS_E_NOT_A_LEVEL", level = reference, column = outcome)
levels_y <- c(reference, setdiff(stored, reference))  # reference first
data <- df
data[[outcome]] <- factor(as.character(df[[outcome]]), levels = levels_y)
y <- as.integer(data[[outcome]])  # 1..J, reference = 1
terms <- cs_design_labels(df, predictors, interactions)
# Degenerate input stops with a catalog error; Python runs the same checks in the same order.
cs_check_rows(nrow(df), (J - 1) * length(terms) + 1, "Multinomial regression")  # more rows than coefficients
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)
X <- model.matrix(fml, data = data)
if (qr(X)$rank < ncol(X)) cs_error("CS_E_COLLINEAR")
stopifnot(length(terms) == ncol(X))
colnames(X) <- terms
n <- nrow(X)
p <- ncol(X)

# %% Fit: nnet::multinom for starting values, then the shared Newton polish (analytic Hessian)
mn <- nnet::multinom(fml, data = data, trace = FALSE, maxit = 1000, reltol = 1e-12)
fitm <- cs_mnl_fit(X, y, J, as.vector(t(coef(mn))))
theta <- fitm$theta
V <- fitm$cov
log_lik <- fitm$ll
if (max(abs(theta)) > 25) {
  warnings <- c(warnings, "Some coefficients are very large: the predictors nearly separate the categories, so estimates and standard errors are unreliable.")
}
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_df <- (p - 1) * (J - 1)
lr_p <- pchisq(lr_chi2, lr_df, 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)

# %% Assumptions
min_n <- min(counts)
assumptions <- list(
  list(key = "iia", label = "Independence of irrelevant alternatives", status = "info",
       detail = "Assumed by the model: the odds between two categories should not change if another category were removed or merged."),
  list(key = "sample_size", label = "Observations per category", status = if (min_n < 10 * (p - 1)) "warn" else "pass", statistic = min_n,
       detail = paste0(sprintf("Smallest category: %s with %d rows for %d slope(s) per equation", levels_y[which.min(counts)], min_n, p - 1),
                       if (min_n < 10 * (p - 1)) " (10 per slope recommended)." else "."))
)
main_cols <- terms[-1][!grepl(" × ", terms[-1], 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
values <- list()
rows <- list()
for (jj in seq_len(J - 1)) {
  lv <- levels_y[jj + 1]
  for (ti in seq_len(p)) {
    i <- (jj - 1) * p + ti
    row <- list(level = lv, term = terms[ti], estimate = theta[i], se = se[i], z = zval[i], p = pval[i],
                ci_low = theta[i] - zc * se[i], ci_high = theta[i] + zc * se[i])
    row <- c(row, list(rrr = exp(row$estimate), rrr_ci_low = exp(row$ci_low), rrr_ci_high = exp(row$ci_high)))
    rows[[length(rows) + 1]] <- row
    for (key in c("estimate", "se", "z", "p", "ci_low", "ci_high", "rrr", "rrr_ci_low", "rrr_ci_high")) {
      values[[sprintf("%s[%s|%s]", if (key == "estimate") "coef" else key, lv, terms[ti])]] <- row[[key]]
    }
  }
}
values <- c(values, list(n = n, k = p, n_levels = J, reference_level = reference, log_lik = log_lik, null_log_lik = null_log_lik,
                         lr_chi2 = lr_chi2, lr_df = lr_df, lr_p = lr_p, mcfadden_r2 = mcfadden, aic = aic, bic = bic, min_category_n = min_n,
                         epv = min_n / max(p - 1, 1), separation = max(abs(theta)) > 25,
                         converged = max(abs(cs_mnl_loglik_grad_hess(theta, X, y, J)$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)
summary <- sprintf("Multinomial logit of %s (%d categories, reference %s, n = %d): χ²(%d) = %.2f, %s; McFadden R² = %.3f.",
                   outcome, J, reference, n, lr_df, lr_chi2, cs_fmt_p(lr_p), mcfadden)
slopes <- Filter(function(r) r$term != "(Intercept)", rows)
cs_publish(list(
  method = "regression.multinomial",
  methodVersion = "2.0.1",
  title = "Multinomial logistic regression",
  engine = cs_engine_info("stats", "nnet", "nanoparquet"),
  n = n,
  summary = summary,
  apa = sprintf("χ²(%d, N = %d) = %s, %s, McFadden R² = %s", lr_df, 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 = "aic", label = "AIC", value = aic)),
  tables = list(list(key = "coefficients", title = sprintf("Coefficients and relative-risk ratios (vs %s)", reference), columns = list(
    list(key = "level", label = outcome, type = "string"), 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"),
    list(key = "rrr", label = "RRR", type = "number"), list(key = "rrr_ci_low", label = paste(pct, "CI low"), type = "number"),
    list(key = "rrr_ci_high", label = paste(pct, "CI high"), type = "number")), rows = rows,
    note = sprintf("Each category against %s: RRR = exp(B), the multiplicative change in P(category) / P(%s).", reference, reference))),
  effectSizes = list(list(key = "mcfadden_r2", label = "McFadden R²", value = mcfadden)),
  assumptions = assumptions,
  warnings = warnings,
  notes = list(sprintf("Baseline-category logit; reference %s = %s; categorical predictors against their first level; Wald z tests.", outcome, reference)),
  charts = list(cs_chart("rrr", "forest", sprintf("Relative-risk ratios vs %s", reference), list(
    label = cs_col("Term", vapply(slopes, `[[`, "", "term"), kind = "categorical"), estimate = cs_col("RRR", vapply(slopes, `[[`, 0, "rrr")),
    low = cs_col("low", vapply(slopes, `[[`, 0, "rrr_ci_low")), high = cs_col("high", vapply(slopes, `[[`, 0, "rrr_ci_high")),
    group = cs_col(outcome, vapply(slopes, `[[`, "", "level"), levels = levels_y[-1])), controls = list(reference = 1, log = TRUE))),
  values = values
))
Python

χ²(9, N = 1681) = 55.11, p < .001, McFadden R² = .01

LR χ²
55.112
p
< .001
McFadden R²
0.0129
AIC
4253.31

Effect size

  • McFadden R² 0.0129

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Independence of irrelevant alternatives — Assumed by the model: the odds between two categories should not change if another category were removed or merged.
  • Observations per category — Smallest category: Atrium with 239 rows for 3 slope(s) per equation.
  • Multicollinearity — Largest VIF 1.01 (Cont).

Coefficients and relative-risk ratios (vs Tower)

TypeTermBSEzpRRR95% CI low95% CI high
Apartment(Intercept)0.33240.12552.649.0081.3941.0901.783
ApartmentInfl: Medium−0.07890.1426−0.5536.5800.92410.69881.222
ApartmentInfl: High0.24540.16691.470.1411.2780.92151.773
ApartmentCont: High0.55700.12534.447< .0011.7451.3652.231
Atrium(Intercept)−0.90190.1721−5.240< .0010.40580.28960.5686
AtriumInfl: Medium−0.29290.1897−1.544.1220.74610.51441.082
AtriumInfl: High0.11600.21660.5356.5921.1230.73451.717
AtriumCont: High0.85180.17044.999< .0012.3441.6783.273
Terrace(Intercept)−0.60840.1599−3.804< .0010.54420.39780.7446
TerraceInfl: Medium−0.32820.1761−1.864.0620.72020.51001.017
TerraceInfl: High−0.39940.2212−1.806.0710.67070.43481.035
TerraceCont: High0.81280.16255.003< .0012.2541.6403.100

Each category against Tower: RRR = exp(B), the multiplicative change in P(category) / P(Tower).

  • Baseline-category logit; reference Type = Tower; categorical predictors against their first level; Wald z tests.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Multinomial logistic regression
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method regression.multinomial 2.0.1 · spec 44808b2efdf5fa80
# 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
import statsmodels.api as sm
from scipy import stats

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=["Type", "Infl", "Cont"])
n_input = len(df)
df["Type"] = pd.Categorical(df["Type"], categories=["Tower", "Apartment", "Atrium", "Terrace"])  # stored level order
df["Infl"] = pd.Categorical(df["Infl"], categories=["Low", "Medium", "High"])  # stored level order
df["Cont"] = pd.Categorical(df["Cont"], categories=["Low", "High"])  # stored level order
df = df.dropna(subset=["Type", "Infl", "Cont"])  # listwise deletion over the analysis columns
df["Type"] = df["Type"].cat.remove_unused_categories()
df["Infl"] = df["Infl"].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, ["Type", "Infl", "Cont"])  # infinite values stop the run (registry/errors.yaml)

# %% Outcome and design matrix
outcome = "Type"
predictors = ["Infl", "Cont"]
interactions = "none"
conf = 0.95
stored = [str(x) for x in df[outcome].cat.categories]
J = len(stored)
if J < 3:  # two categories: logistic regression
    cs.cs_error("CS_E_TOO_FEW_GROUPS", column=outcome, min=3, k=J)
reference = stored[0]  # default: the first stored level
if reference not in stored:
    cs.cs_error("CS_E_NOT_A_LEVEL", level=reference, column=outcome)
levels_y = [reference] + [lv for lv in stored if lv != reference]  # reference first (code 0)
y = df[outcome].astype(str).map({lv: i for i, lv in enumerate(levels_y)}).to_numpy()
X = csreg.design_matrix(df, predictors, interactions)
# Degenerate input stops with a catalog error; R runs the same checks in the same order.
cs.check_rows(len(df), (J - 1) * X.shape[1] + 1, "Multinomial regression")  # more rows than coefficients
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(X.to_numpy()) < X.shape[1]:
    cs.cs_error("CS_E_COLLINEAR")
terms = list(X.columns)
n, p = X.shape

# %% Fit: statsmodels MNLogit for starting values, then the shared Newton polish (analytic Hessian)
mn = sm.MNLogit(y, X).fit(method="newton", maxiter=200, disp=False)
start = np.asarray(mn.params).T.ravel()  # outcome blocks
theta, V, log_lik = csglm.mnl_fit(X.to_numpy(), y, J, start)
if np.max(np.abs(theta)) > 25:
    warnings.append("Some coefficients are very large: the predictors nearly separate the categories, so estimates and standard errors are unreliable.")
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_df = (p - 1) * (J - 1)
lr_p = float(stats.chi2.sf(lr_chi2, lr_df))
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)

# %% Assumptions
min_n = int(counts.min())
assumptions = [
    {"key": "iia", "label": "Independence of irrelevant alternatives", "status": "info",
     "detail": "Assumed by the model: the odds between two categories should not change if another category were removed or merged."},
    {"key": "sample_size", "label": "Observations per category", "status": "warn" if min_n < 10 * (p - 1) else "pass", "statistic": min_n,
     "detail": f"Smallest category: {levels_y[int(counts.argmin())]} with {min_n} rows for {p - 1} slope(s) per equation" + (" (10 per slope recommended)." if min_n < 10 * (p - 1) else ".")},
]
main_cols = [c for c in terms[1:] 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
values = {}
rows = []
for jj, lv in enumerate(levels_y[1:]):
    for t_i, t in enumerate(terms):
        i = jj * p + t_i
        row = {"level": lv, "term": t, "estimate": float(theta[i]), "se": float(se[i]), "z": float(zval[i]), "p": float(pval[i]),
               "ci_low": float(theta[i] - zc * se[i]), "ci_high": float(theta[i] + zc * se[i])}
        row.update({"rrr": float(np.exp(row["estimate"])), "rrr_ci_low": float(np.exp(row["ci_low"])), "rrr_ci_high": float(np.exp(row["ci_high"]))})
        rows.append(row)
        for key in ("estimate", "se", "z", "p", "ci_low", "ci_high", "rrr", "rrr_ci_low", "rrr_ci_high"):
            values[f"{'coef' if key == 'estimate' else key}[{lv}|{t}]"] = row[key]
values.update({"n": n, "k": p, "n_levels": J, "reference_level": reference, "log_lik": float(log_lik), "null_log_lik": null_log_lik,
               "lr_chi2": float(lr_chi2), "lr_df": float(lr_df), "lr_p": lr_p, "mcfadden_r2": float(mcfadden), "aic": float(aic),
               "bic": float(bic), "min_category_n": min_n,
               "epv": min_n / max(p - 1, 1), "separation": bool(np.max(np.abs(theta)) > 25),
               "converged": bool(np.max(np.abs(csglm.mnl_loglik_grad_hess(theta, X.to_numpy(), y, J)[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%}"
summary = (f"Multinomial logit of {outcome} ({J} categories, reference {reference}, n = {n}): χ²({lr_df}) = {lr_chi2:.2f}, {cs.fmt_p(lr_p)}; "
           f"McFadden R² = {mcfadden:.3f}.")
slopes = [r for r in rows if r["term"] != "(Intercept)"]
cs.publish({
    "method": "regression.multinomial",
    "methodVersion": "2.0.1",
    "title": "Multinomial logistic regression",
    "engine": cs.engine_info("pandas", "numpy", "statsmodels", "scipy"),
    "n": n,
    "summary": summary,
    "apa": f"χ²({lr_df}, 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": "aic", "label": "AIC", "value": float(aic)}],
    "tables": [{"key": "coefficients", "title": f"Coefficients and relative-risk ratios (vs {reference})", "columns": [
        {"key": "level", "label": outcome, "type": "string"}, {"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"},
        {"key": "rrr", "label": "RRR", "type": "number"}, {"key": "rrr_ci_low", "label": f"{pct} CI low", "type": "number"},
        {"key": "rrr_ci_high", "label": f"{pct} CI high", "type": "number"}], "rows": rows,
        "note": f"Each category against {reference}: RRR = exp(B), the multiplicative change in P(category) / P({reference})."}],
    "effectSizes": [{"key": "mcfadden_r2", "label": "McFadden R²", "value": float(mcfadden)}],
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": [f"Baseline-category logit; reference {outcome} = {reference}; categorical predictors against their first level; Wald z tests."],
    "charts": [cs.chart("rrr", "forest", f"Relative-risk ratios vs {reference}", {
        "label": cs.col("Term", [r["term"] for r in slopes], kind="categorical"), "estimate": cs.col("RRR", [r["rrr"] for r in slopes]),
        "low": cs.col("low", [r["rrr_ci_low"] for r in slopes]), "high": cs.col("high", [r["rrr_ci_high"] for r in slopes]),
        "group": cs.col(outcome, [r["level"] for r in slopes], levels=levels_y[1:])}, controls={"reference": 1, "log": True})],
    "values": values,
})

This model has 4 housing types, with Tower as the reference, and 12 parameters. The overall test gives χ2\chi^2(9) = 55.1, p < .001.

Exponentiated coefficients are relative risk ratios: how a unit of the predictor changes the odds of this category compared with the reference only. They say nothing direct about other pairs.

04

Pick the reference on purpose

Read

Each coefficient compares a category with the reference. Pick a large, meaningful category; a rare one makes every comparison noisy.

Changing Reference category relabels the comparisons but doesn't change the model's predictions or its overall test.

Because coefficients compare only against the reference, predicted probabilities are usually the easiest thing to explain to other people.

05

How much data do you have?

Read

Each model's information is limited by its smallest category. In the survey model of smoking habits, the rarest category has only 10 rows, with 3.3 events per parameter, far below the usual rule of thumb of 10.

Its overall test gives p = .590. With this little data, the honest reading is that the data can't say much, not that these predictors have no effect.

06

The IIA assumption

Reflect

The model assumes independence of irrelevant alternatives: the odds between two options don't depend on which other options exist.

The classic counterexample: people choose between a car and a red bus. Add a blue bus, and it takes riders mostly from the red bus, not the car, so the car-to-red-bus odds change. Are any of your categories near-substitutes like that? If so, consider whether the categories should be combined.

07

Check your understanding

Checkpoint

Check yourself

A 4-category outcome with 3 numeric predictors: how many coefficients does the model have, including intercepts?

Show the answer

Answer: 12

(4 − 1) × (3 + 1) = 3 × 4 = 12.

Check yourself

With "Never" as the reference, the relative risk ratio for age in the "Heavy" smokers equation is 1.1. What does it say?

Show the answer

Answer: a

Coefficients compare one category with the reference, on the odds scale.

Check yourself

The outcome is low, medium, high. Which model is usually better?

Show the answer

Answer: b

Multinomial ignores the order. An ordinal model uses it and costs far fewer parameters, as long as its assumption holds.

08

Fit yours

In the app

Pick a categorical Outcome with three or more levels, your Predictors, and a Reference category.

Python
import pandas as pd
import statsmodels.formula.api as smf

df = pd.read_csv("housing.csv")
df["y"] = df["Type"].astype("category").cat.codes
fit = smf.mnlogit("y ~ C(Infl) + C(Cont)", data=df).fit()
print(fit.summary())
R
# nnet ships with R
library(nnet)
df <- read.csv("housing.csv")
df$Type <- relevel(factor(df$Type), ref = "Tower")
fit <- multinom(Type ~ Infl + Cont, data = df)
summary(fit)
09

Recap

Recap
  • The model fits J−1J - 1 log-odds, each against a reference category.
  • Coefficients and parameters multiply across categories.
  • Your smallest category limits what the data can tell you.
  • Read predicted probabilities, and think about IIA.

Concepts in this lesson