DRegression models · regression.multinomial
Multinomial logistic regression
How do predictors change the chances of each category of an unordered outcome?
Baseline-category logit model for an outcome with three or more unordered categories: one set of coefficients per non-reference category, reported as relative-risk ratios (multinomial odds ratios) with Wald intervals, the likelihood-ratio test against the intercept-only model and McFadden's R².
A real result
Example “Smoking”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
χ²(9, N = 208) = 7.46, p = .590, McFadden R² = .03
- LR χ²
- 7.456
- p
- .590
- McFadden R²
- 0.0257
- AIC
- 306.64
Effect size
- McFadden R² 0.0257
Plots
View data
| RRR | Smoke | high | Term | low |
|---|---|---|---|---|
| 0.8330 | Occas | 3.398 | Sex: Male | 0.2042 |
| 0.9556 | Occas | 1.101 | Age | 0.8296 |
| 1.018 | Occas | 1.093 | Height | 0.9484 |
| 2.560 | Regul | 13.228 | Sex: Male | 0.4956 |
| 1.023 | Regul | 1.091 | Age | 0.9600 |
| 1.031 | Regul | 1.109 | Height | 0.9591 |
| 0.6490 | Heavy | 3.905 | Sex: Male | 0.1079 |
| 1.018 | Heavy | 1.097 | Age | 0.9450 |
| 1.037 | Heavy | 1.135 | Height | 0.9466 |
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: Heavy with 10 rows for 3 slope(s) per equation (10 per slope recommended).
- Multicollinearity — Largest VIF 1.81 (Height).
Coefficients and relative-risk ratios (vs Never)
| Smoke | Term | B | SE | z | p | RRR | 95% CI low | 95% CI high |
|---|---|---|---|---|---|---|---|---|
| Occas | (Intercept) | −4.478 | 6.292 | −0.7117 | .477 | 0.0114 | 5.003e-8 | 2576.20 |
| Occas | Sex: Male | −0.1827 | 0.7172 | −0.2547 | .799 | 0.8330 | 0.2042 | 3.398 |
| Occas | Age | −0.0454 | 0.0721 | −0.6301 | .529 | 0.9556 | 0.8296 | 1.101 |
| Occas | Height | 0.0181 | 0.0363 | 0.4986 | .618 | 1.018 | 0.9484 | 1.093 |
| Regul | (Intercept) | −8.994 | 6.327 | −1.421 | .155 | 0.0001 | 5.111e-10 | 30.183 |
| Regul | Sex: Male | 0.9402 | 0.8379 | 1.122 | .262 | 2.560 | 0.4956 | 13.228 |
| Regul | Age | 0.0232 | 0.0327 | 0.7109 | .477 | 1.023 | 0.9600 | 1.091 |
| Regul | Height | 0.0310 | 0.0371 | 0.8343 | .404 | 1.031 | 0.9591 | 1.109 |
| Heavy | (Intercept) | −9.219 | 7.858 | −1.173 | .241 | 9.916e-5 | 2.030e-11 | 484.26 |
| Heavy | Sex: Male | −0.4323 | 0.9156 | −0.4722 | .637 | 0.6490 | 0.1079 | 3.905 |
| Heavy | Age | 0.0182 | 0.0382 | 0.4768 | .634 | 1.018 | 0.9450 | 1.097 |
| Heavy | Height | 0.0361 | 0.0464 | 0.7769 | .437 | 1.037 | 0.9466 | 1.135 |
Each category against Never: RRR = exp(B), the multiplicative change in P(category) / P(Never).
- 29 of 237 rows were left out because a value was missing.
- Baseline-category logit; reference Smoke = Never; categorical predictors against their first level; Wald z tests.
χ²(9, N = 208) = 7.46, p = .590, McFadden R² = .03
- LR χ²
- 7.456
- p
- .590
- McFadden R²
- 0.0257
- AIC
- 306.64
Effect size
- McFadden R² 0.0257
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: Heavy with 10 rows for 3 slope(s) per equation (10 per slope recommended).
- Multicollinearity — Largest VIF 1.81 (Height).
Coefficients and relative-risk ratios (vs Never)
| Smoke | Term | B | SE | z | p | RRR | 95% CI low | 95% CI high |
|---|---|---|---|---|---|---|---|---|
| Occas | (Intercept) | −4.478 | 6.292 | −0.7117 | .477 | 0.0114 | 5.003e-8 | 2576.20 |
| Occas | Sex: Male | −0.1827 | 0.7172 | −0.2547 | .799 | 0.8330 | 0.2042 | 3.398 |
| Occas | Age | −0.0454 | 0.0721 | −0.6301 | .529 | 0.9556 | 0.8296 | 1.101 |
| Occas | Height | 0.0181 | 0.0363 | 0.4986 | .618 | 1.018 | 0.9484 | 1.093 |
| Regul | (Intercept) | −8.994 | 6.327 | −1.421 | .155 | 0.0001 | 5.111e-10 | 30.183 |
| Regul | Sex: Male | 0.9402 | 0.8379 | 1.122 | .262 | 2.560 | 0.4956 | 13.228 |
| Regul | Age | 0.0232 | 0.0327 | 0.7109 | .477 | 1.023 | 0.9600 | 1.091 |
| Regul | Height | 0.0310 | 0.0371 | 0.8343 | .404 | 1.031 | 0.9591 | 1.109 |
| Heavy | (Intercept) | −9.219 | 7.858 | −1.173 | .241 | 9.916e-5 | 2.030e-11 | 484.26 |
| Heavy | Sex: Male | −0.4323 | 0.9156 | −0.4722 | .637 | 0.6490 | 0.1079 | 3.905 |
| Heavy | Age | 0.0182 | 0.0382 | 0.4768 | .634 | 1.018 | 0.9450 | 1.097 |
| Heavy | Height | 0.0361 | 0.0464 | 0.7769 | .437 | 1.037 | 0.9466 | 1.135 |
Each category against Never: RRR = exp(B), the multiplicative change in P(category) / P(Never).
- 29 of 237 rows were left out because a value was missing.
- Baseline-category logit; reference Smoke = Never; categorical predictors against their first level; Wald z tests.
Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.
Worked examples in the app
- Smokingsurvey · outcome: Smoke · predictors: Sex, Age, Height
- Survey reference missingsurvey · outcome: Exer · predictors: Sex, Age
- Categorical predictorshousing · outcome: Type · predictors: Infl, Cont
- Degenerate constantsurvey · outcome: Smoke · predictors: Sex, Age, Height
- Degenerate single levelsurvey · outcome: Smoke · predictors: Sex, Age, Height
In the guides
Where it sits in the decision guides
- Association with covariates: linear / logistic regression · Statistics Guide · C — Test association
- Nominal outcome: multinomial logistic · Statistics Guide · D — Predict an outcome
- Regression (linear, logistic, Poisson) · DS & ML Decision Guide · Predict — forecast or classify outcomes
What you need
- Outcomecategorical · 1 column · 3–20 levels
- A categorical outcome with three or more unordered levels.
- Predictorsnumeric / categorical / boolean · 1–20 columns · 2–30 levels
- Columns used to explain or predict the outcome.
Choices you make
hypothesis
- Reference categorydefault —
Every other category is compared with this one; default: the first stored level.
- Confidence leveldefault 0.95
How sure the intervals should be: 0.95 gives 95% confidence intervals. Higher confidence means wider intervals.
statistics
- Interactionsdefault none
Add interaction terms so the effect of one predictor can depend on the value of another.
- None (main effects only)(default) — Fits main effects only; the usual starting point and the easiest to read.
- First two predictors (A × B) — Adds the A × B term for the first two predictors; pick it when you expect one effect to depend on the other.
- All pairs of predictors — Adds every two-way term; uses many coefficients, so pick it with plenty of rows and a reason to look.
Checks and remedies
CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.
Independence of irrelevant alternatives
Odds between two categories do not depend on which other categories exist.
Observations per category
Multicollinearity (VIF)
What it reports
- Tests: Model vs intercept only (likelihood-ratio test)
- n
- How many independent units the analysis used; it sets precision and power.
- k
- How many groups, studies or clusters the analysis used. Many methods are less reliable when k is small.
- n_levels
- How many independent units the analysis used; it sets precision and power.
- reference_level
- Which group counts as first (or treated, or positive) decides the sign of differences and ratios on the card.
- log_lik
- The logarithm of the likelihood; higher (less negative) means the model fits the data better.
- null_log_lik
- How well a model with no predictors fits. The likelihood-ratio test compares the fitted model with it.
- lr_chi2
- A sum of squared, scaled differences between observed and expected counts or estimates.
- lr_df
- Compares nested models by how much the log-likelihood improves when parameters are added.
- lr_p
- Compares nested models by how much the log-likelihood improves when parameters are added.
- mcfadden_r2
- An R²-like summary for models without a usual R². Versions differ, and none reads as variance explained.
- aic
- A model score balancing fit against complexity; lower is better, and only differences matter.
- bic
- Like AIC but with a stronger penalty for parameters as n grows; favors simpler models.
- min_category_n
- Number of observations in the rarest outcome category. Few cases there make the related coefficients unstable.
- epv
- Events (the rarer outcome) per estimated coefficient in logistic or Cox models.
- separation
- A predictor perfectly splits the outcome in logistic regression, so its coefficient runs to infinity.
- converged
- Whether an iterative fit found a stable solution; warnings mean estimates may be unreliable.
- n_params
- How many values a model learns from the data: a regression's coefficients (intercept included) or a network's weights and biases.
- max_interaction_order
- The most factors combined in one term of the model: 1 means main effects only, 2 two-way interactions.
- missing_share
- Values that were not recorded; how they went missing decides which fixes are safe.
Per group, level or term: coef[<level>|<term>], se[…], z[…], p[…], ci_low[…], ci_high[…], rrr[…], rrr_ci_low[…], rrr_ci_high[…]
Python and R
Python and R agree to 6 decimals (relative tolerance 1e-7). Python uses pandas, numpy, statsmodels, scipy, codesplash; R uses stats, nnet, nanoparquet, codesplashr.
Default traps between the two languages
- statsmodels MNLogit / nnet::multinom give starting values; both engines then run the same Newton–Raphson twin with the analytic Hessian, which also gives the standard errors (nnet's BFGS stops at reltol 1e-8 otherwise).
The exact script CodeSplash ran for example “Smoking” · 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 41a4b09926be4154
# Dataset: survey (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/survey.parquet", columns=["Smoke", "Sex", "Age", "Height"])
n_input = len(df)
df["Smoke"] = pd.Categorical(df["Smoke"], categories=["Never", "Occas", "Regul", "Heavy"]) # stored level order
df["Sex"] = pd.Categorical(df["Sex"], categories=["Female", "Male"]) # stored level order
df = df.dropna(subset=["Smoke", "Sex", "Age", "Height"]) # listwise deletion over the analysis columns
df["Smoke"] = df["Smoke"].cat.remove_unused_categories()
df["Sex"] = df["Sex"].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, ["Smoke", "Sex", "Age", "Height"]) # infinite values stop the run (registry/errors.yaml)
# %% Outcome and design matrix
outcome = "Smoke"
predictors = ["Sex", "Age", "Height"]
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,
})
The exact script CodeSplash ran for example “Smoking” · 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 41a4b09926be4154
# Dataset: survey (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/survey.parquet", col_select = c("Smoke", "Sex", "Age", "Height")))
n_input <- nrow(df)
df[["Smoke"]] <- factor(df[["Smoke"]], levels = c("Never", "Occas", "Regul", "Heavy")) # stored level order
df[["Sex"]] <- factor(df[["Sex"]], levels = c("Female", "Male")) # stored level order
df <- df[stats::complete.cases(df[c("Smoke", "Sex", "Age", "Height")]), , 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("Smoke", "Sex", "Age", "Height")) # infinite values stop the run (registry/errors.yaml)
# %% Outcome and model
outcome <- "Smoke"
predictors <- c("Sex", "Age", "Height")
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
))
Sources
- Agresti, A. (2013). Categorical Data Analysis (3rd ed.), ch. 8. Wiley.
- Venables, W. N., & Ripley, B. D. (2002). Modern Applied Statistics with S (4th ed.), §7.3. Springer.
From the CodeSplash method registry · regression.multinomial v2.0.1.