Skip to content

Log-linear models for tables with many variables

Write a table's cell counts as a model with one term for each association. Comparing models answers questions a single chi-square can't.

Advanced ~12 min9 steps

What runs in CodeSplash

You will be able to

  • Connect the independence model to the chi-square and G tests
  • Read model notation for a three-way table
  • Treat backward elimination as a search, and a saturated fit as no finding

Read first

01

Model the counts

Read

A chi-square test asks one question about two variables. A log-linear modelLog-linear modelModels the log of each cell's expected count as a sum of terms, one for each variable and association allowed. writes the logarithm of each cell's expected count as a sum of terms:

log⁡μij=λ+λiH+λjE\log \mu_{ij} = \lambda + \lambda^{H}_{i} + \lambda^{E}_{j}

That's hair and eye color with no association. Add a term λijHE\lambda^{HE}_{ij} and it can fit any pattern at all.

No variable is the outcome here: all are treated alike. If one is plainly the outcome, logistic regression asks the same questions in terms that are easier to read.

02

Count the parameters

Predict

Predict first

Hair and eye color have 4 levels each, so the table has 16 cells. The independence model has one overall term, 3 free hair terms and 3 free eye terms. How many degrees of freedom are left over?

Make your guess between 0 and 16 residual degrees of freedom, then reveal.

Reveal

16−(1+3+3)=916 - (1 + 3 + 3) = 9, the same as a chi-square test on this table. Its G2G^2 is 146.44, which is the GG of the chi-square card: 146.44. The independence model is that test.

03

Three-way notation

Read

Each model names the associations it allows:

ModelWrittenWhat it claims
Mutual independence[A] [B] [C]No associations at all
Joint independence[A × B] [C]C is unrelated to A and B
Conditional independenceConditional independenceTwo variables are unrelated within each level of a third, though they may look related when pooled over it.[A × C] [B × C]A and B are unrelated within each level of C
Homogeneous association[A × B] [A × C] [B × C]Each pair's odds ratio is the same at every level of the third
Saturated[A × B × C]Anything goes

Models are hierarchical: a term like [A × B] brings A and B with it.

04

Berkeley again

Predict

Predict first

Homogeneous association says that admission and gender have the same odds ratio in every department. Given the previous lesson, how will that model fit?

It fits wellIt fits poorly
Reveal

Poorly: G2G^2 = 20.20 on 5 df, p = .001. Its Pearson statistic, 18.82, is close to Breslow–Day's 18.83. Both are asking the same question.

05

Search for a model

Read
Log-linear modelRecorded · Python and R agreeRecorded 2026-11-17 · 51 values compared
R

G²(12, N = 592) = 11.76, p = .465

G² (likelihood ratio)
11.764
Pearson X²
11.771
df
12
p (G²)
.465
AIC
190.64

Plots

Likelihood-ratio χ² of each interactionHow do categories compare on one value — and across up to three groups?
View data
termΔG²
hair × eye146.44
hair × sex8.093

Assumptions

  • Enough expected counts — 16% of fitted cell counts are below 5 (smallest 2.41).
  • Independent observations — Each subject is counted in one cell.

Backward elimination

StepRemovedΔG²dfp
1hair × eye × sex6.76190.6620
2eye × sex5.00230.1716

Likelihood-ratio tests of the interactions in the final model

TermΔG²dfp
hair × eye146.4494.806e-27
hair × sex8.09330.0441

Observed and fitted counts

hair · eye · sexObservedFittedAdjusted residual
Black · Brown · Male3235.259−1.300
Brown · Brown · Male5359.500−1.560
Red · Brown · Male1012.451−1.208
Blond · Brown · Male32.5350.3758
Black · Blue · Male1110.3700.3122
Brown · Blue · Male50422.077
Red · Blue · Male108.1411.035
Blond · Blue · Male3034.047−1.704
Black · Hazel · Male107.7781.237
Brown · Hazel · Male2527−0.6044
Red · Hazel · Male76.7040.1766
Blond · Hazel · Male53.6220.9446
Black · Green · Male32.5930.3734
Brown · Green · Male1514.5000.1959
Red · Green · Male76.7040.1766
Blond · Green · Male85.7951.227
Black · Brown · Female3632.7411.300
Brown · Brown · Female6659.5001.560
Red · Brown · Female1613.5491.208
Blond · Brown · Female44.465−0.3758
Black · Blue · Female99.630−0.3122
Brown · Blue · Female3442−2.077
Red · Blue · Female78.859−1.035
Blond · Blue · Female6459.9531.704
Black · Hazel · Female57.222−1.237
Brown · Hazel · Female29270.6044
Red · Hazel · Female77.296−0.1766
Blond · Hazel · Female56.378−0.9446
Black · Green · Female22.407−0.3734
Brown · Green · Female1414.500−0.1959
Red · Green · Female77.296−0.1766
Blond · Green · Female810.205−1.227
  • Model (generating class): [hair × eye] [hair × sex]. Every cell of the 4 × 4 × 2 table is fitted, empty cells included.
The exact R script · R R version 4.5.1 (2025-06-13)
# Log-linear models for multiway tables
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method contingency.loglinear 1.0.1 · spec f2b921fb1c5375ef
# Dataset: hair_eye (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr) # cs_cat_reduce_generator, cs_cat_gen_formula (generator bookkeeping, twins of codesplash.stats)

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/hair_eye.parquet", col_select = c("hair", "eye", "sex")))
n_input <- nrow(df)
df[["hair"]] <- factor(df[["hair"]], levels = c("Black", "Brown", "Red", "Blond"))  # stored level order
df[["eye"]] <- factor(df[["eye"]], levels = c("Brown", "Blue", "Hazel", "Green"))  # stored level order
df[["sex"]] <- factor(df[["sex"]], levels = c("Male", "Female"))  # stored level order
df <- df[stats::complete.cases(df[c("hair", "eye", "sex")]), , 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("hair", "eye", "sex"))  # infinite values stop the run (registry/errors.yaml)

# %% Cells of the cross-table (empty cells included)
factors <- c("hair", "eye", "sex")
k <- length(factors)
df$.w <- 1
tab <- stats::xtabs(stats::as.formula(paste(".w ~", paste(sprintf("`%s`", factors), collapse = " + "))), data = df)
cells <- as.data.frame(tab, responseName = ".n", stringsAsFactors = TRUE)  # every cell, empty ones included
names(cells) <- c(factors, ".n")  # keep names with spaces as they are
nlev <- vapply(factors, function(f) nlevels(cells[[f]]), 0L)
for (i in seq_len(k)) {  # a variable with one category has no association to model
  if (nlev[[i]] < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = factors[i], min = 2, k = nlev[[i]])
}
n <- sum(cells$.n)
ncell <- nrow(cells)

fit_gens <- function(gens) {
  f <- stats::as.formula(paste(".n ~", cs_cat_gen_formula(gens, factors)))
  m <- suppressWarnings(stats::glm(f, family = stats::poisson(), data = cells, control = stats::glm.control(epsilon = 1e-14, maxit = 200)))
  list(fit = m, mu = stats::fitted(m), dev = max(stats::deviance(m), 0), df = stats::df.residual(m), rank = m$rank,
       aic = stats::AIC(m), x2 = sum(stats::residuals(m, type = "pearson")^2))
}
lab_of <- function(g) paste(factors[g], collapse = " × ")
chi2_p <- function(stat, dfree) if (dfree > 0) stats::pchisq(stat, dfree, lower.tail = FALSE) else NaN

# %% Model
model <- "backward"
alpha_drop <- 0.05
saturated <- list(seq_len(k))
gens <- switch(model,
  saturated = saturated,
  independence = as.list(seq_len(k)),
  homogeneous = if (k > 2) utils::combn(k, 2, simplify = FALSE) else saturated,
  backward = saturated
)
gens <- cs_cat_sort_generators(gens)
cur <- fit_gens(gens)
path <- list()
if (model == "backward") {
  repeat {
    cands <- Filter(function(g) length(g) >= 2, gens)
    if (!length(cands)) break
    tests <- lapply(cands, function(g) {
      red <- fit_gens(cs_cat_reduce_generator(gens, g))
      list(g = g, g2 = red$dev - cur$dev, df = red$df - cur$df, p = chi2_p(red$dev - cur$dev, red$df - cur$df), red = red)
    })
    best <- which.max(vapply(tests, function(t) t$p, 0))  # first of tied maxima
    tt <- tests[[best]]
    if (!(tt$p > alpha_drop)) break
    gens <- cs_cat_reduce_generator(gens, tt$g)
    cur <- tt$red
    path[[length(path) + 1]] <- list(step = length(path) + 1L, term = lab_of(tt$g), g2 = tt$g2, df = tt$df, p = tt$p)
  }
}

# %% Likelihood-ratio tests of each interaction in the final model
drops <- list()
for (g in gens) {
  if (length(g) >= 2) {
    red <- fit_gens(cs_cat_reduce_generator(gens, g))
    drops[[length(drops) + 1]] <- list(term = lab_of(g), g2 = red$dev - cur$dev, df = red$df - cur$df, p = chi2_p(red$dev - cur$dev, red$df - cur$df))
  }
}
mu <- as.numeric(cur$mu)
h <- stats::hatvalues(cur$fit)
y <- cells$.n
adj <- ifelse(mu > 0 & 1 - h > 1e-8, (y - mu) / sqrt(mu * pmax(1 - h, 1e-300)), 0)  # saturated cells (leverage 1) fit exactly
model_label <- paste(vapply(gens, function(g) sprintf("[%s]", lab_of(g)), ""), collapse = " ")
p <- chi2_p(cur$dev, cur$df)

# %% Assumptions
small <- mean(mu < 5)
assumptions <- list(
  list(key = "expected", label = "Enough expected counts", status = if (small <= 0.2 && min(mu) >= 1) "pass" else "warn",
       detail = sprintf("%.0f%% of fitted cell counts are below 5 (smallest %.2f).", 100 * small, min(mu))),
  list(key = "independence", label = "Independent observations", status = "info", detail = "Each subject is counted in one cell.")
)

# %% Result
values <- list(n = n, cells = ncell, k = k, model_label = model_label, g2 = cur$dev, x2 = cur$x2, df = cur$df,
               p = p, p_x2 = chi2_p(cur$x2, cur$df), aic = cur$aic, n_params = cur$rank, steps = length(path), min_expected = min(mu))
for (d in drops) {
  values[[sprintf("drop_g2[%s]", d$term)]] <- d$g2
  values[[sprintf("drop_df[%s]", d$term)]] <- d$df
  values[[sprintf("drop_p[%s]", d$term)]] <- d$p
}
cell_labels <- apply(cells[factors], 1, function(r) paste(trimws(r), collapse = " · "))
if (ncell <= 300) for (i in seq_len(ncell)) values[[sprintf("adj_resid[%s]", cell_labels[i])]] <- adj[i]
tables <- list(
  list(key = "terms", title = "Likelihood-ratio tests of the interactions in the final model",
       columns = list(list(key = "term", label = "Term", type = "string"), list(key = "g2", label = "ΔG²", type = "number"),
                      list(key = "df", label = "df", type = "integer"), list(key = "p", label = "p", type = "number", format = "p")),
       rows = drops),
  list(key = "cells", title = "Observed and fitted counts",
       columns = list(list(key = "cell", label = paste(factors, collapse = " · "), type = "string"), list(key = "observed", label = "Observed", type = "number"),
                      list(key = "fitted", label = "Fitted", type = "number"), list(key = "adj", label = "Adjusted residual", type = "number")),
       rows = lapply(seq_len(ncell), function(i) list(cell = cell_labels[i], observed = y[i], fitted = mu[i], adj = adj[i])))
)
if (length(path)) {
  tables <- c(list(list(key = "path", title = "Backward elimination",
                        columns = list(list(key = "step", label = "Step", type = "integer"), list(key = "term", label = "Removed", type = "string"),
                                       list(key = "g2", label = "ΔG²", type = "number"), list(key = "df", label = "df", type = "integer"),
                                       list(key = "p", label = "p", type = "number", format = "p")),
                        rows = path)), tables)
}
charts <- list()
if (length(drops)) {
  charts[[length(charts) + 1]] <- cs_chart("terms", "cleveland-dot", "Likelihood-ratio χ² of each interaction",
                                           list(category = cs_col("term", vapply(drops, function(d) d$term, "")), value = cs_col("ΔG²", vapply(drops, function(d) d$g2, 0))))
}
if (k == 2) {
  charts[[length(charts) + 1]] <- cs_chart("residuals", "matrix-heatmap", "Adjusted residuals",
                                           list(row = cs_col(factors[1], as.character(cells[[factors[1]]])), col = cs_col(factors[2], as.character(cells[[factors[2]]])),
                                                value = cs_col("adjusted residual", adj)), controls = list(scale = "diverging"))
}
cs_publish(list(
  method = "contingency.loglinear",
  methodVersion = "1.0.1",
  title = "Log-linear model",
  engine = cs_engine_info("stats", "nanoparquet"),
  n = as.integer(n),
  summary = sprintf("Log-linear model %s: G²(%d) = %.2f, %s (X² = %.2f, AIC = %.1f).", model_label, as.integer(cur$df), cur$dev, cs_fmt_p(p), cur$x2, cur$aic),
  apa = sprintf("G²(%d, N = %d) = %.2f, %s", as.integer(cur$df), as.integer(n), cur$dev, cs_fmt_p(p)),
  statistics = list(
    list(key = "g2", label = "G² (likelihood ratio)", value = cur$dev),
    list(key = "x2", label = "Pearson X²", value = cur$x2),
    list(key = "df", label = "df", value = cur$df),
    list(key = "p", label = "p (G²)", value = p, format = "p"),
    list(key = "aic", label = "AIC", value = cur$aic)
  ),
  tables = tables,
  assumptions = assumptions,
  warnings = warnings,
  notes = list(sprintf("Model (generating class): %s. Every cell of the %s table is fitted, empty cells included.", model_label, paste(nlev, collapse = " × "))),
  charts = charts,
  values = values
))
Python

G²(12, N = 592) = 11.76, p = .465

G² (likelihood ratio)
11.764
Pearson X²
11.771
df
12
p (G²)
.465
AIC
190.64

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

Assumptions

  • Enough expected counts — 16% of fitted cell counts are below 5 (smallest 2.41).
  • Independent observations — Each subject is counted in one cell.

Backward elimination

StepRemovedΔG²dfp
1hair × eye × sex6.76190.6620
2eye × sex5.00230.1716

Likelihood-ratio tests of the interactions in the final model

TermΔG²dfp
hair × eye146.4494.806e-27
hair × sex8.09330.0441

Observed and fitted counts

hair · eye · sexObservedFittedAdjusted residual
Black · Brown · Male3235.259−1.300
Black · Brown · Female3632.7411.300
Black · Blue · Male1110.3700.3122
Black · Blue · Female99.630−0.3122
Black · Hazel · Male107.7781.237
Black · Hazel · Female57.222−1.237
Black · Green · Male32.5930.3734
Black · Green · Female22.407−0.3734
Brown · Brown · Male5359.500−1.560
Brown · Brown · Female6659.5001.560
Brown · Blue · Male5042.0002.077
Brown · Blue · Female3442.000−2.077
Brown · Hazel · Male2527.000−0.6044
Brown · Hazel · Female2927.0000.6044
Brown · Green · Male1514.5000.1959
Brown · Green · Female1414.500−0.1959
Red · Brown · Male1012.451−1.208
Red · Brown · Female1613.5491.208
Red · Blue · Male108.1411.035
Red · Blue · Female78.859−1.035
Red · Hazel · Male76.7040.1766
Red · Hazel · Female77.296−0.1766
Red · Green · Male76.7040.1766
Red · Green · Female77.296−0.1766
Blond · Brown · Male32.5350.3758
Blond · Brown · Female44.465−0.3758
Blond · Blue · Male3034.047−1.704
Blond · Blue · Female6459.9531.704
Blond · Hazel · Male53.6220.9446
Blond · Hazel · Female56.378−0.9446
Blond · Green · Male85.7951.227
Blond · Green · Female810.205−1.227
  • Model (generating class): [hair × eye] [hair × sex]. Every cell of the 4 × 4 × 2 table is fitted, empty cells included.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Log-linear models for multiway tables
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method contingency.loglinear 1.0.1 · spec f2b921fb1c5375ef
# Dataset: hair_eye (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import itertools
import math
import warnings as pywarnings

import numpy as np
import pandas as pd
import statsmodels.api as sm
from scipy import stats
from scipy.special import gammaln

import codesplash as cs
from codesplash.stats import categorical_adv as cat  # hierarchical designs, generator bookkeeping (twins of codesplashr)

# %% Data
df = pd.read_parquet("tests/parity/fixtures/hair_eye.parquet", columns=["hair", "eye", "sex"])
n_input = len(df)
df["hair"] = pd.Categorical(df["hair"], categories=["Black", "Brown", "Red", "Blond"])  # stored level order
df["eye"] = pd.Categorical(df["eye"], categories=["Brown", "Blue", "Hazel", "Green"])  # stored level order
df["sex"] = pd.Categorical(df["sex"], categories=["Male", "Female"])  # stored level order
df = df.dropna(subset=["hair", "eye", "sex"])  # listwise deletion over the analysis columns
df["hair"] = df["hair"].cat.remove_unused_categories()
df["eye"] = df["eye"].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, ["hair", "eye", "sex"])  # infinite values stop the run (registry/errors.yaml)

# %% Cells of the cross-table (empty cells included)
factors = ["hair", "eye", "sex"]
k = len(factors)
levels = [[str(v) for v in df[f].cat.categories] for f in factors]
nlev = [len(lv) for lv in levels]
weight = np.ones(len(df))
for f, m in zip(factors, nlev):  # a variable with one category has no association to model
    if m < 2:
        cs.cs_error("CS_E_TOO_FEW_GROUPS", column=f, min=2, k=m)
codes = [df[f].cat.codes.to_numpy(dtype=np.int64) for f in factors]
grid = list(itertools.product(*[range(m) for m in nlev]))
cell_index = {g: i for i, g in enumerate(grid)}
y = np.zeros(len(grid))
for i, g in enumerate(zip(*codes)):
    y[cell_index[g]] += weight[i]
cell_codes = [np.array([g[f] for g in grid]) for f in range(k)]
n = float(y.sum())
ncell = len(grid)


def fit(gens):
    """Poisson GLM of the cell counts on the hierarchical model with generators ``gens``."""
    x = cat.loglinear_design(cell_codes, nlev, gens)
    with pywarnings.catch_warnings():
        pywarnings.simplefilter("ignore")
        res = sm.GLM(y, x, family=sm.families.Poisson()).fit(tol=1e-14, maxiter=200)
    mu = np.asarray(res.mu)
    with np.errstate(divide="ignore", invalid="ignore"):
        dev = float(2 * np.sum(np.where(y > 0, y * np.log(y / mu), 0.0) - (y - mu)))
    rank = int(np.linalg.matrix_rank(x))
    ll = float(np.sum(y * np.log(np.maximum(mu, 1e-300)) - mu - gammaln(y + 1)))
    return {"x": x, "mu": mu, "dev": max(dev, 0.0), "df": ncell - rank, "rank": rank, "aic": -2 * ll + 2 * rank,
            "x2": float(np.sum((y - mu) ** 2 / mu))}


def label(g):
    return " × ".join(factors[f] for f in g)


def chi2_p(stat, dfree):
    return float(stats.chi2.sf(stat, dfree)) if dfree > 0 else math.nan


# %% Model
model = "backward"
alpha_drop = 0.05
saturated = [tuple(range(k))]
gens = {"saturated": saturated, "independence": [(f,) for f in range(k)],
        "homogeneous": [g for g in itertools.combinations(range(k), 2)] if k > 2 else saturated, "backward": saturated}[model]
gens = sorted(gens, key=lambda t: (-len(t), t))
cur = fit(gens)
path = []
if model == "backward":
    while True:
        cands = [g for g in gens if len(g) >= 2]
        if not cands:
            break
        tests = []
        for g in cands:
            red = fit(cat.reduce_generator(gens, g))
            tests.append((g, red["dev"] - cur["dev"], red["df"] - cur["df"], chi2_p(red["dev"] - cur["dev"], red["df"] - cur["df"]), red))
        best = max(range(len(tests)), key=lambda i: (tests[i][3], -i))
        g, g2d, dfd, pd_, red = tests[best]
        if not pd_ > alpha_drop:
            break
        gens = cat.reduce_generator(gens, g)
        cur = red
        path.append({"step": len(path) + 1, "term": label(g), "g2": g2d, "df": dfd, "p": pd_})

# %% Likelihood-ratio tests of each interaction in the final model
drops = []
for g in gens:
    if len(g) >= 2:
        red = fit(cat.reduce_generator(gens, g))
        drops.append({"term": label(g), "g2": red["dev"] - cur["dev"], "df": red["df"] - cur["df"],
                      "p": chi2_p(red["dev"] - cur["dev"], red["df"] - cur["df"])})

mu = cur["mu"]
h = cat.hat_poisson(cur["x"], mu)
with np.errstate(divide="ignore", invalid="ignore"):
    # Saturated cells (leverage 1) fit exactly: their adjusted residual is 0.
    adj = np.where((mu > 0) & (1 - h > 1e-8), (y - mu) / np.sqrt(mu * np.maximum(1 - h, 1e-300)), 0.0)
model_label = " ".join(f"[{label(g)}]" for g in gens)
p = chi2_p(cur["dev"], cur["df"])

# %% Assumptions
small = float(np.mean(mu < 5))
assumptions = [
    {"key": "expected", "label": "Enough expected counts", "status": "pass" if small <= 0.2 and mu.min() >= 1 else "warn",
     "detail": f"{small:.0%} of fitted cell counts are below 5 (smallest {mu.min():.2f})."},
    {"key": "independence", "label": "Independent observations", "status": "info", "detail": "Each subject is counted in one cell."},
]

# %% Result
values = {"n": n, "cells": ncell, "k": k, "model_label": model_label, "g2": cur["dev"], "x2": cur["x2"], "df": cur["df"],
          "p": p, "p_x2": chi2_p(cur["x2"], cur["df"]), "aic": cur["aic"], "n_params": cur["rank"], "steps": len(path),
          "min_expected": float(mu.min())}
for d in drops:
    values[f"drop_g2[{d['term']}]"] = d["g2"]
    values[f"drop_df[{d['term']}]"] = d["df"]
    values[f"drop_p[{d['term']}]"] = d["p"]
cell_labels = [" · ".join(levels[f][g[f]] for f in range(k)) for g in grid]
if ncell <= 300:
    for lab, a in zip(cell_labels, adj):
        values[f"adj_resid[{lab}]"] = float(a)
tables = [
    {"key": "terms", "title": "Likelihood-ratio tests of the interactions in the final model",
     "columns": [{"key": "term", "label": "Term", "type": "string"}, {"key": "g2", "label": "ΔG²", "type": "number"},
                 {"key": "df", "label": "df", "type": "integer"}, {"key": "p", "label": "p", "type": "number", "format": "p"}],
     "rows": drops},
    {"key": "cells", "title": "Observed and fitted counts",
     "columns": [{"key": "cell", "label": " · ".join(factors), "type": "string"}, {"key": "observed", "label": "Observed", "type": "number"},
                 {"key": "fitted", "label": "Fitted", "type": "number"}, {"key": "adj", "label": "Adjusted residual", "type": "number"}],
     "rows": [{"cell": lab, "observed": float(o), "fitted": float(f), "adj": float(a)} for lab, o, f, a in zip(cell_labels, y, mu, adj)]},
]
if path:
    tables.insert(0, {"key": "path", "title": "Backward elimination",
                      "columns": [{"key": "step", "label": "Step", "type": "integer"}, {"key": "term", "label": "Removed", "type": "string"},
                                  {"key": "g2", "label": "ΔG²", "type": "number"}, {"key": "df", "label": "df", "type": "integer"},
                                  {"key": "p", "label": "p", "type": "number", "format": "p"}],
                      "rows": path})
charts = []
if drops:
    charts.append(cs.chart("terms", "cleveland-dot", "Likelihood-ratio χ² of each interaction",
                           {"category": cs.col("term", [d["term"] for d in drops]), "value": cs.col("ΔG²", [d["g2"] for d in drops])}))
if k == 2:
    charts.append(cs.chart("residuals", "matrix-heatmap", "Adjusted residuals",
                           {"row": cs.col(factors[0], [levels[0][g[0]] for g in grid]), "col": cs.col(factors[1], [levels[1][g[1]] for g in grid]),
                            "value": cs.col("adjusted residual", [float(a) for a in adj])}, controls={"scale": "diverging"}))
cs.publish({
    "method": "contingency.loglinear",
    "methodVersion": "1.0.1",
    "title": "Log-linear model",
    "engine": cs.engine_info("pandas", "numpy", "scipy", "statsmodels"),
    "n": int(n),
    "summary": f"Log-linear model {model_label}: G²({cur['df']}) = {cur['dev']:.2f}, {cs.fmt_p(p)} (X² = {cur['x2']:.2f}, AIC = {cur['aic']:.1f}).",
    "apa": f"G²({cur['df']}, N = {int(n)}) = {cur['dev']:.2f}, {cs.fmt_p(p)}",
    "statistics": [
        {"key": "g2", "label": "G² (likelihood ratio)", "value": cur["dev"]},
        {"key": "x2", "label": "Pearson X²", "value": cur["x2"]},
        {"key": "df", "label": "df", "value": cur["df"]},
        {"key": "p", "label": "p (G²)", "value": p, "format": "p"},
        {"key": "aic", "label": "AIC", "value": cur["aic"]},
    ],
    "tables": tables,
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": [f"Model (generating class): {model_label}. Every cell of the {' × '.join(str(m) for m in nlev)} table is fitted, empty cells included."],
    "charts": charts,
    "values": values,
})

Backward elimination starts at the saturated model and drops terms while the fit doesn't get meaningfully worse. For hair, eye and sex it takes 2 steps and stops at [hair × eye] [hair × sex], with G2G^2 = 11.76 on 12 df, p = .465.

Read it as: within each hair color, these data are compatible with eye color and sex being unrelated.

The search used these data to choose the model. Treat the result as a hypothesis, and don't quote its p-value as if the model had been fixed in advance.

06

A perfect fit

Reflect

The saturated model has G2G^2 = 0.0 on 0 df. It reproduces every cell, since it has 32 parameters for 32 cells.

AIC charges for those parameters: 202.9 for the saturated model, against 190.6 for the simpler one, and lower is better.

Why does a perfect fit tell you nothing about the world? How would you explain that to a colleague who is pleased to see G2G^2 = 0?

07

Check your understanding

Checkpoint

Check yourself

A 2 × 3 × 4 table is fitted with mutual independence. How many residual degrees of freedom are there?

Show the answer

Answer: 17

24 cells minus (1 + 1 + 2 + 3) = 7 parameters leaves 17.

Check yourself

The model [A × C] [B × C] fits well. What does that suggest?

Show the answer

Answer: b

This is conditional independence. Pooled over C, A and B can still look associated, which is Simpson's paradox seen from a modeling angle.

Check yourself

A smaller model has G2G^2 = 30 on 8 df. A larger model containing it has G2G^2 = 12 on 5 df. What is the likelihood-ratio statistic comparing them?

Show the answer

Answer: 18

30 − 12 = 18, on 8 − 5 = 3 degrees of freedom. Differences of G2G^2 between nested models are themselves tests.

Check yourself

A log-linear model gives p = 0.46 for its fit. What does that mean?

Show the answer

Answer: b

The null hypothesis here is the model itself, so a large p means only that the data don't contradict it.

08

Do it in CodeSplash

In the app

Choose the Variables. If your data are already counted, put the counts in Count (frequency weight). Model offers backward elimination, homogeneous association, mutual independence and saturated, and Keep a term when p ≤ controls the search. The card's adjusted residuals show which cells the model misses.

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

df = pd.read_csv("haireye_counts.csv")  # hair, eye, sex, students
fit = smf.glm(
    "students ~ C(hair) * C(eye) + C(hair) * C(sex)",
    data=df,
    family=sm.families.Poisson(),
).fit()
print(fit.deviance, fit.df_resid, fit.aic)
R
counts <- as.data.frame(HairEyeColor)
fit <- glm(Freq ~ Hair * Eye + Hair * Sex, family = poisson, data = counts)
c(deviance(fit), df.residual(fit), AIC(fit))

MASS::loglm(~ Hair * Eye + Hair * Sex, data = HairEyeColor)
09

Recap

Recap
  • A log-linear model turns a table's associations into terms you can add or drop.
  • The independence model is the G test; homogeneous association asks what Breslow–Day asks.
  • A fitted model is compatible with the data, not confirmed by them, and a search needs a fresh look.

Concepts in this lesson