Goodness of fit and the power-divergence family
Do these counts match a theory? Pearson's chi-square, the G test and Cressie–Read are one family with one dial.
What runs in CodeSplash
- STAT115Pearson chi square goodness of fit test Runs in CodeSplash
- STAT124Cressie–Read power divergence tests Runs in CodeSplash
- Goodness of fit (χ² / G test) Verified in Python and R
You will be able to
- Test observed counts against stated proportions
- Place Pearson, G and Cressie–Read on the λ dial
- Interpret a large goodness-of-fit p-value without overclaiming
Does the theory fit?
ReadMendel crossed peas and predicted four phenotypes in the ratio . Across 556 peas, how well do the counts match?
The degrees of freedom drop further for every parameter you estimate from the same data.
Predict the result
PredictPredict first
Observed counts were 315, 101, 108 and 32. Expected under are about 313, 104, 104 and 35. What p-value do you expect? Drag to your guess.
Make your guess between 0 and 1 p-value, then reveal.
Reveal
= 0.47 on 3 degrees of freedom, p = .925. The counts are very close to the prediction.
What a large p-value means
Read"The data fit" means something weaker than "the theory is right". Mendel's result is compatible with , and with neighboring ratios too. With a weak test or a small sample, a poor theory can also pass.
Fisher later noticed that Mendel's results, taken together, fit too well. A p-value near 1 is worth a second look too.
Compare equal proportions for eye color: = 133.5, p < .001, Cohen's = 0.47.
One family
ReadCressie and Read showed these statistics are one power-divergencePower-divergence statisticsOne family of goodness-of-fit statistics indexed by λ — Pearson's χ² (λ = 1), G² (λ = 0), Freeman–Tukey (−½), Neyman (−2). family, with a single dial :
| λ | Statistic |
|---|---|
| 1 | Pearson |
| 2/3 | Cressie–Read |
| 0 (limit) | Likelihood-ratio |
| −½ | Freeman–Tukey |
| −1 (limit) | Modified |
| −2 | Neyman |
Turn the dial
ReflectOn Mendel's peas: Pearson 0.470, = 0.475 and Freeman–Tukey 0.478. With expected counts this large, the choice hardly matters.
With a small sample it matters more, so simulate: mtcars cylinders with gives p = .302 from the table and p = .330 from Monte Carlo.
Would a colleague reach another conclusion from a different λ? If so, decide before you look.
Parameters you estimated
ReadThe degrees of freedom are k − 1 only when the expected proportions come from outside the data. If you estimated something from these same counts first (a Poisson mean, a binomial p), each estimate uses up one degree of freedom. Set Parameters estimated from the data and the test refers χ² to k − 1 − (that number) degrees of freedom, as scipy's ddof does.
χ²(2, N = 556) = 0.47, p = .791, w = 0.03
- Pearson χ²
- 0.4700
- G
- 0.4754
- df
- 2
- p (χ² goodness-of-fit test)
- .791
Effect size
- Cohen's w 0.0291 · negligible
Plots
Observed shares with 95% Wilson intervals next to the expected shares.
View data
| Share | series | high | phenotype | low |
|---|---|---|---|---|
| 0.5665 | observed | 0.6071 | round yellow | 0.5250 |
| 0.1942 | observed | 0.2292 | round green | 0.1635 |
| 0.1817 | observed | 0.2159 | wrinkled yellow | 0.1518 |
| 0.0576 | observed | 0.0801 | wrinkled green | 0.0411 |
| 0.5625 | expected | 0.5625 | round yellow | 0.5625 |
| 0.1875 | expected | 0.1875 | round green | 0.1875 |
| 0.1875 | expected | 0.1875 | wrinkled yellow | 0.1875 |
| 0.0625 | expected | 0.0625 | wrinkled green | 0.0625 |
Assumptions
- Expected counts ≥ 5 — Every expected count is at least 5 (smallest 34.75).
Observed and expected frequencies
| phenotype | Observed | Expected | Observed share | Expected share | Pearson residual | Adjusted residual |
|---|---|---|---|---|---|---|
| round yellow | 315 | 312.75 | 0.5665 | 0.5625 | 0.1272 | 0.1924 |
| round green | 108 | 104.25 | 0.1942 | 0.1875 | 0.3673 | 0.4075 |
| wrinkled yellow | 101 | 104.25 | 0.1817 | 0.1875 | −0.3183 | −0.3531 |
| wrinkled green | 32 | 34.750 | 0.0576 | 0.0625 | −0.4665 | −0.4818 |
- Expected proportions: round yellow 0.5625, round green 0.1875, wrinkled yellow 0.1875, wrinkled green 0.0625.
The exact R script · R R version 4.5.1 (2025-06-13)
# Goodness of fit (χ² / G test)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method proportion.gof 1.2.0 · spec d9e210c527fdab80
# Dataset: mendel_peas (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr) # cs_gof_mc, cs_prop_ci, cs_power_divergence (twins of codesplash.stats)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/mendel_peas.parquet", col_select = c("phenotype")))
n_input <- nrow(df)
df[["phenotype"]] <- factor(df[["phenotype"]], levels = c("round yellow", "round green", "wrinkled yellow", "wrinkled green")) # stored level order
df <- df[stats::complete.cases(df[c("phenotype")]), , 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("phenotype")) # infinite values stop the run (registry/errors.yaml)
# %% Helpers
magnitude <- function(x, cuts, labels = c("negligible", "small", "medium", "large")) {
# Benchmark label for an effect size (rule set named in the result)
if (is.null(x) || !is.finite(x)) return("undetermined")
labels[findInterval(abs(x), cuts) + 1]
}
# %% Test
v <- "phenotype"
levels_v <- c("round yellow", "round green", "wrinkled yellow", "wrinkled green") # every stored level, including empty ones
observed <- vapply(levels_v, function(lv) sum(as.character(df[[v]]) == lv), numeric(1))
n <- sum(observed)
k <- length(levels_v)
probs <- c(9, 3, 3, 1)
if (length(probs) != k) stop(sprintf("Give one proportion per level of %s (%d: %s); got %d.", v, k, paste(levels_v, collapse = ", "), length(probs)))
if (sum(probs) <= 0) stop("The expected proportions must not all be zero.")
probs <- probs / sum(probs) # rescaled to sum to 1 (chisq.test(rescale.p = TRUE))
expected <- n * probs
statistic <- "pearson"
use_mc <- FALSE
ddof <- as.integer(1) # Stage 12.7 option: parameters estimated from the data (scipy's ddof)
dof <- k - 1 - ddof
if (ddof > 0 && (dof < 1 || FALSE)) {
cs_error("CS_E_INVALID_OPTION", option = "Estimated parameters", allowed = sprintf("at most %d with %d categories, without the Monte Carlo p-value", k - 2, k), value = as.character(ddof))
}
chi2 <- sum((observed - expected)^2 / expected) # Pearson χ² = chisq.test(observed, p = probs)$statistic
pos <- observed > 0
g <- 2 * sum(observed[pos] * log(observed[pos] / expected[pos])) # likelihood-ratio G
p_pearson <- pchisq(chi2, dof, lower.tail = FALSE)
p_g <- pchisq(g, dof, lower.tail = FALSE)
# Power-divergence statistic (Cressie & Read 1984): Pearson lambda = 1, G lambda = 0, others below
pd_label <- c(pearson = "Pearson χ²", g = "likelihood-ratio G²", cressie_read = "Cressie–Read", freeman_tukey = "Freeman–Tukey",
mod_g = "modified G²", neyman = "Neyman χ²")
lam <- cs_pd_lambda(statistic, 0.6666666666666666)
pd_stat <- if (statistic == "pearson") chi2 else if (statistic == "g") g else cs_power_divergence(observed, expected, lam)
pd_p <- if (is.finite(pd_stat)) pchisq(pd_stat, dof, lower.tail = FALSE) else NULL
if (is.null(pd_p)) {
warnings <- c(warnings, sprintf("The %s statistic is undefined when a level has no values; Pearson's χ² is used instead.", pd_label[[statistic]]))
statistic <- "pearson"; lam <- 1; pd_stat <- chi2; pd_p <- p_pearson
}
mc_p <- if (!use_mc) {
NULL
} else if (statistic %in% c("pearson", "g")) {
cs_gof_mc(observed, probs, 10000, seed = 42, statistic = statistic)
} else {
cs_pd_gof_mc(observed, probs, 10000, 42, lam)
}
p <- if (use_mc) mc_p else pd_p
label <- paste0(if (statistic == "g") "G test" else if (statistic == "pearson") "χ² goodness-of-fit test" else paste(pd_label[[statistic]], "goodness-of-fit test"),
if (use_mc) " (Monte Carlo)" else "")
w <- sqrt(chi2 / n) # Cohen's w
resid <- (observed - expected) / sqrt(expected) # Pearson residuals
stdres <- (observed - expected) / sqrt(expected * (1 - probs)) # adjusted residuals (chisq.test()$stdres)
min_expected <- min(expected)
# %% Assumptions
below <- sum(expected < 5)
if (use_mc) {
status <- "info"
detail <- sprintf("Monte Carlo p-value (%s simulations, seed 42); smallest expected count %.2f.",
format(10000, big.mark = ","), min_expected)
} else if (min_expected < 1) {
status <- "fail"
detail <- sprintf("Smallest expected count %.2f (< 1): the χ² approximation fails; use the Monte Carlo p-value.", min_expected)
} else if (below > 0) {
status <- "warn"
detail <- sprintf("%d of %d expected counts are below 5 (smallest %.2f); consider the Monte Carlo p-value.", below, k, min_expected)
} else {
status <- "pass"
detail <- sprintf("Every expected count is at least 5 (smallest %.2f).", min_expected)
}
assumptions <- list(list(key = "expected_counts", label = "Expected counts ≥ 5", status = status, detail = detail))
# %% Result
size <- magnitude(w, c(0.1, 0.3, 0.5))
summary <- sprintf("%s on %d values of %s over %d levels: %s; Cohen's w = %.2f (%s).", label, as.integer(n), v, k, cs_fmt_p(p), w, size)
result_values <- list(n = n, k = k, chi2 = chi2, g = g, df = dof, p_pearson = p_pearson, p_g = p_g, mc_p = mc_p, p = p,
cohens_w = w, min_expected = min_expected, statistic_label = label, pd_stat = pd_stat, pd_lambda = lam, pd_p = pd_p)
if (ddof > 0) result_values$ddof <- ddof
props <- observed / n
cis <- lapply(seq_len(k), function(i) cs_prop_ci(observed[[i]], n, 0.95, "wilson"))
rows <- data.frame(level = levels_v, observed = as.integer(observed), expected = expected, proportion = props, expected_prop = probs,
resid = resid, stdres = stdres, ci_low = vapply(cis, `[`, numeric(1), 1), ci_high = vapply(cis, `[`, numeric(1), 2),
row.names = NULL)
for (i in seq_len(k)) {
result_values[[sprintf("observed[%s]", levels_v[i])]] <- observed[[i]]
result_values[[sprintf("expected[%s]", levels_v[i])]] <- expected[[i]]
result_values[[sprintf("resid[%s]", levels_v[i])]] <- resid[[i]]
}
cs_publish(list(
method = "proportion.gof",
methodVersion = "1.2.0",
title = "Goodness of fit",
engine = cs_engine_info("stats", "nanoparquet"),
n = n,
summary = summary,
apa = if (statistic %in% c("pearson", "g")) {
sprintf("%s(%d, N = %d) = %s, %s, w = %s", if (statistic == "g") "G" else "χ²", dof, as.integer(n),
cs_fmt_num(if (statistic == "g") g else chi2), cs_fmt_p(p), cs_fmt_num(w))
} else {
sprintf("%s (λ = %s)(%d, N = %d) = %s, %s, w = %s", pd_label[[statistic]], cs_fmt_num(lam), as.integer(dof), as.integer(n),
cs_fmt_num(pd_stat), cs_fmt_p(p), cs_fmt_num(w))
},
statistics = c(list(
list(key = "chi2", label = "Pearson χ²", value = chi2), list(key = "g", label = "G", value = g),
list(key = "df", label = "df", value = dof), list(key = "p", label = sprintf("p (%s)", label), value = p, format = "p")),
if (!statistic %in% c("pearson", "g")) list(
list(key = "pd_stat", label = sprintf("%s (λ = %s)", pd_label[[statistic]], format(signif(lam, 3))), value = pd_stat),
list(key = "pd_p", label = sprintf("p (%s)", pd_label[[statistic]]), value = pd_p, format = "p"))
),
tables = list(list(
key = "frequencies", title = "Observed and expected frequencies",
columns = list(
list(key = "level", label = v, type = "string"), list(key = "observed", label = "Observed", type = "integer"),
list(key = "expected", label = "Expected", type = "number"), list(key = "proportion", label = "Observed share", type = "number"),
list(key = "expected_prop", label = "Expected share", type = "number"),
list(key = "resid", label = "Pearson residual", type = "number"), list(key = "stdres", label = "Adjusted residual", type = "number")
),
rows = rows[, c("level", "observed", "expected", "proportion", "expected_prop", "resid", "stdres")]
)),
effectSizes = list(list(key = "cohens_w", label = "Cohen's w", value = w, method = "√(χ² / n)", magnitude = size, ruleSet = "Cohen (1988)")),
assumptions = assumptions,
warnings = warnings,
notes = list(paste0("Expected proportions: ", paste(sprintf("%s %s", levels_v, format(signif(probs, 4))), collapse = ", "), ".")),
charts = list(cs_chart(
"shares", "forest", sprintf("Observed vs expected shares of %s", v),
list(label = cs_col(v, rep(levels_v, 2)), estimate = cs_col("Share", c(rows$proportion, rows$expected_prop)),
low = cs_col("low", c(rows$ci_low, rows$expected_prop)), high = cs_col("high", c(rows$ci_high, rows$expected_prop)),
group = cs_col("series", rep(c("observed", "expected"), each = k))),
note = "Observed shares with 95% Wilson intervals next to the expected shares."
)),
values = result_values
))
χ²(2, N = 556) = 0.47, p = .791, w = 0.03
- Pearson χ²
- 0.4700
- G
- 0.4754
- df
- 2
- p (χ² goodness-of-fit test)
- .791
Effect size
- Cohen's w 0.0291 · negligible
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Expected counts ≥ 5 — Every expected count is at least 5 (smallest 34.75).
Observed and expected frequencies
| phenotype | Observed | Expected | Observed share | Expected share | Pearson residual | Adjusted residual |
|---|---|---|---|---|---|---|
| round yellow | 315 | 312.75 | 0.5665 | 0.5625 | 0.1272 | 0.1924 |
| round green | 108 | 104.25 | 0.1942 | 0.1875 | 0.3673 | 0.4075 |
| wrinkled yellow | 101 | 104.25 | 0.1817 | 0.1875 | −0.3183 | −0.3531 |
| wrinkled green | 32 | 34.750 | 0.0576 | 0.0625 | −0.4665 | −0.4818 |
- Expected proportions: round yellow 0.5625, round green 0.1875, wrinkled yellow 0.1875, wrinkled green 0.0625.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Goodness of fit (χ² / G test)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method proportion.gof 1.2.0 · spec d9e210c527fdab80
# Dataset: mendel_peas (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import math
import numpy as np
import pandas as pd
from scipy import stats
import codesplash as cs
from codesplash.stats import proportions as csp # Monte Carlo p and Wilson intervals (twins of codesplashr)
from codesplash.stats import proportions_ext as csx # power-divergence family (twins of cs_power_divergence …)
# %% Data
df = pd.read_parquet("tests/parity/fixtures/mendel_peas.parquet", columns=["phenotype"])
n_input = len(df)
df["phenotype"] = pd.Categorical(df["phenotype"], categories=["round yellow", "round green", "wrinkled yellow", "wrinkled green"]) # stored level order
df = df.dropna(subset=["phenotype"]) # listwise deletion over the analysis columns
df["phenotype"] = df["phenotype"].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, ["phenotype"]) # infinite values stop the run (registry/errors.yaml)
# %% Helpers
def magnitude(x, cuts, labels=("negligible", "small", "medium", "large")):
"""Benchmark label for an effect size (rule set named in the result)."""
if x is None or not np.isfinite(x):
return "undetermined"
for cut, label in zip(cuts, labels):
if abs(x) < cut:
return label
return labels[-1]
# %% Test
v = "phenotype"
levels = ["round yellow", "round green", "wrinkled yellow", "wrinkled green"] # every stored level, including empty ones
values = df[v].astype(str)
observed = np.array([float((values == lv).sum()) for lv in levels])
n, k = float(observed.sum()), len(levels)
probs = np.array([9,3,3,1], dtype=float)
if len(probs) != k:
raise ValueError(f"Give one proportion per level of {v} ({k}: {', '.join(levels)}); got {len(probs)}.")
if probs.sum() <= 0:
raise ValueError("The expected proportions must not all be zero.")
probs = probs / probs.sum() # rescaled to sum to 1 (chisq.test(rescale.p = TRUE))
expected = n * probs
statistic = "pearson"
use_mc = False
ddof = int(1) # Stage 12.7 option: parameters estimated from the data (scipy's ddof)
dof = k - 1 - ddof
if ddof and (dof < 1 or False):
cs.cs_error("CS_E_INVALID_OPTION", option="Estimated parameters", allowed=f"at most {k - 2} with {k} categories, without the Monte Carlo p-value", value=str(ddof))
chi2 = float(np.sum((observed - expected) ** 2 / expected)) # Pearson χ² = scipy.stats.chisquare(observed, expected)
pos = observed > 0
g = float(2 * np.sum(observed[pos] * np.log(observed[pos] / expected[pos]))) # likelihood-ratio G
p_pearson = float(stats.chi2.sf(chi2, dof))
p_g = float(stats.chi2.sf(g, dof))
# Power-divergence statistic (Cressie & Read 1984): Pearson λ = 1, G λ = 0, others below
lam = csx.pd_lambda(statistic, 0.6666666666666666)
pd_stat = chi2 if statistic == "pearson" else (g if statistic == "g" else csx.power_divergence(observed, expected, lam))
pd_p = float(stats.chi2.sf(pd_stat, dof)) if math.isfinite(pd_stat) else None
if pd_p is None:
warnings.append(f"The {csx.PD_LABEL[statistic]} statistic is undefined when a level has no values; Pearson's χ² is used instead.")
statistic, lam, pd_stat, pd_p = "pearson", 1.0, chi2, p_pearson
if not use_mc:
mc_p = None
elif statistic in ("pearson", "g"):
mc_p = csp.gof_mc(observed, probs, int(10000), seed=42, statistic=statistic)
else:
mc_p = csx.pd_gof_mc(observed, probs, int(10000), 42, lam)
p = mc_p if use_mc else pd_p
label = ("G test" if statistic == "g" else "χ² goodness-of-fit test" if statistic == "pearson" else f"{csx.PD_LABEL[statistic]} goodness-of-fit test") + (" (Monte Carlo)" if use_mc else "")
w = math.sqrt(chi2 / n) # Cohen's w
resid = (observed - expected) / np.sqrt(expected) # Pearson residuals
stdres = (observed - expected) / np.sqrt(expected * (1 - probs)) # adjusted residuals (chisq.test()$stdres)
min_expected = float(expected.min())
# %% Assumptions
below = int((expected < 5).sum())
if use_mc:
status, detail = "info", f"Monte Carlo p-value ({int(10000):,} simulations, seed 42); smallest expected count {min_expected:.2f}."
elif min_expected < 1:
status, detail = "fail", f"Smallest expected count {min_expected:.2f} (< 1): the χ² approximation fails; use the Monte Carlo p-value."
elif below:
status, detail = "warn", f"{below} of {k} expected counts are below 5 (smallest {min_expected:.2f}); consider the Monte Carlo p-value."
else:
status, detail = "pass", f"Every expected count is at least 5 (smallest {min_expected:.2f})."
assumptions = [{"key": "expected_counts", "label": "Expected counts ≥ 5", "status": status, "detail": detail}]
# %% Result
size = magnitude(w, (0.1, 0.3, 0.5))
summary = f"{label} on {int(n)} values of {v} over {k} levels: {cs.fmt_p(p)}; Cohen's w = {w:.2f} ({size})."
result_values = {"n": int(n), "k": k, "chi2": chi2, "g": g, "df": float(dof), "p_pearson": p_pearson, "p_g": p_g, "mc_p": mc_p, "p": p,
"cohens_w": w, "min_expected": min_expected, "statistic_label": label, "pd_stat": pd_stat, "pd_lambda": lam, "pd_p": pd_p, **({"ddof": ddof} if ddof else {})}
rows = []
props = observed / n
for i, lv in enumerate(levels):
lo, hi = csp.prop_ci(observed[i], n, 0.95, "wilson")
rows.append({"level": lv, "observed": int(observed[i]), "expected": float(expected[i]), "proportion": float(props[i]),
"expected_prop": float(probs[i]), "resid": float(resid[i]), "stdres": float(stdres[i]), "ci_low": lo, "ci_high": hi})
result_values[f"observed[{lv}]"] = float(observed[i])
result_values[f"expected[{lv}]"] = float(expected[i])
result_values[f"resid[{lv}]"] = float(resid[i])
cs.publish({
"method": "proportion.gof",
"methodVersion": "1.2.0",
"title": "Goodness of fit",
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": int(n),
"summary": summary,
"apa": (f"{'G' if statistic == 'g' else 'χ²'}({dof}, N = {int(n)}) = {cs.fmt_num(g if statistic == 'g' else chi2)}, {cs.fmt_p(p)}, w = {cs.fmt_num(w)}"
if statistic in ("pearson", "g") else
f"{csx.PD_LABEL[statistic]} (λ = {cs.fmt_num(lam)})({dof}, N = {int(n)}) = {cs.fmt_num(pd_stat)}, {cs.fmt_p(p)}, w = {cs.fmt_num(w)}"),
"statistics": [
{"key": "chi2", "label": "Pearson χ²", "value": chi2}, {"key": "g", "label": "G", "value": g},
{"key": "df", "label": "df", "value": dof}, {"key": "p", "label": f"p ({label})", "value": p, "format": "p"},
] + ([{"key": "pd_stat", "label": f"{csx.PD_LABEL[statistic]} (λ = {lam:.3g})", "value": pd_stat},
{"key": "pd_p", "label": f"p ({csx.PD_LABEL[statistic]})", "value": pd_p, "format": "p"}] if statistic not in ("pearson", "g") else []),
"tables": [{
"key": "frequencies", "title": "Observed and expected frequencies",
"columns": [{"key": "level", "label": v, "type": "string"}, {"key": "observed", "label": "Observed", "type": "integer"},
{"key": "expected", "label": "Expected", "type": "number"}, {"key": "proportion", "label": "Observed share", "type": "number"},
{"key": "expected_prop", "label": "Expected share", "type": "number"},
{"key": "resid", "label": "Pearson residual", "type": "number"}, {"key": "stdres", "label": "Adjusted residual", "type": "number"}],
"rows": rows,
}],
"effectSizes": [{"key": "cohens_w", "label": "Cohen's w", "value": w, "method": "√(χ² / n)", "magnitude": size, "ruleSet": "Cohen (1988)"}],
"assumptions": assumptions,
"warnings": warnings,
"notes": ["Expected proportions: " + ", ".join(f"{lv} {pr:.4g}" for lv, pr in zip(levels, probs)) + "."],
"charts": [cs.chart(
"shares", "forest", f"Observed vs expected shares of {v}",
{"label": cs.col(v, [r["level"] for r in rows] * 2),
"estimate": cs.col("Share", [r["proportion"] for r in rows] + [r["expected_prop"] for r in rows]),
"low": cs.col("low", [r["ci_low"] for r in rows] + [r["expected_prop"] for r in rows]),
"high": cs.col("high", [r["ci_high"] for r in rows] + [r["expected_prop"] for r in rows]),
"group": cs.col("series", ["observed"] * k + ["expected"] * k)},
note="Observed shares with 95% Wilson intervals next to the expected shares.",
)],
"values": result_values,
})
Check your understanding
CheckpointCheck yourself
You test whether 6 faces of a die are equally likely. How many degrees of freedom does the test have?
Show the answer
Answer: 5
k − 1 = 5, because the six counts must sum to the total.
Check yourself
Testing a ratio across 100 observations: what is the expected count for the first category?
Show the answer
Answer: 25
1/4 of 100 = 25.
Check yourself
A goodness-of-fit test gives p = 0.60. What may you say?
Show the answer
Answer: b
Failing to reject doesn't confirm a theory. It says the data aren't surprising under it.
Check yourself
Counts of goals per match fall into 6 categories (0, 1, 2, 3, 4, 5+). You fitted a Poisson mean to the same counts to get the expected proportions. How many degrees of freedom does the goodness-of-fit test have?
Show the answer
Answer: 4
k − 1 − 1 = 6 − 2 = 4: one for the fixed total and one for the estimated mean.
Do it in CodeSplash
In the appPick the Variable, and set Expected proportions to Equal for every level or to Custom proportions, entered in level order. Statistic is the λ dial, with Monte Carlo p-value for small samples.
import numpy as np
from scipy import stats
obs = np.array([315, 101, 108, 32])
exp = obs.sum() * np.array([9, 3, 3, 1]) / 16
print(stats.chisquare(obs, exp))
print(stats.power_divergence(obs, exp, lambda_="cressie-read"))obs <- c(315, 101, 108, 32)
chisq.test(obs, p = c(9, 3, 3, 1) / 16)Recap
Recap- Goodness of fit compares counts with a stated distribution.
- Pearson, and Cressie–Read are one family, and they agree when expected counts are large.
- A large p-value means compatible, not confirmed.
Concepts in this lesson