Does this distribution fit?
The one-sample Kolmogorov–Smirnov, Cramér–von Mises and Anderson–Darling tests, why estimated parameters break their textbook p-values, and what a large p-value can't say.
What runs in CodeSplash
- STAT116One sample Kolmogorov–Smirnov test Runs in CodeSplash
- STAT118Anderson–Darling general goodness of fit test Runs in CodeSplash
- STAT120Cramér–von Mises one sample test Runs in CodeSplash
- Fit a distribution (goodness of fit) Verified in Python and R
You will be able to
- Say what each of the KS, CvM and AD statistics measures
- Explain why estimating parameters from the same data needs a bootstrap
- Read a fit test without treating a large p-value as proof of a family
Read first
Fit against what?
ReadA goodness-of-fit test compares your data's ECDFEmpirical CDFFor each value, the share of observations at or below it; a step plot with no bins to choose. with a stated distribution. All three tests here measure the gap between the two curves. They differ in how they add it up.
| Test | What it uses |
|---|---|
| Kolmogorov–SmirnovKolmogorov–Smirnov testCompares distributions by the largest vertical gap (D) between their cumulative curves. | The single largest gap |
| Cramér–von MisesCramér–von Mises testGoodness-of-fit test summing the squared gaps between the data's ECDF and the fitted distribution over all values. | The squared gap, averaged over the range |
| Anderson–DarlingAnderson–Darling testGoodness-of-fit test that weighs the tails more than Kolmogorov–Smirnov, so it notices heavy or light tails sooner. | The same, with more weight in the tails |
See the gap
ExploreChange the data's shift and sample size below, and watch where the largest gap falls. Then ask what the test can't see when the gap is spread out across the range.
BExplorable · One-sample Kolmogorov–Smirnov test
Could the sample come from a fully specified distribution, here N(0, 1)?
Your data
Drag a point or use ↑/↓ to change itIf H₀ were true
- The reference: how D varies across samples when H₀ is true.
- Your statistic, from the data above.
- The p-value: the area at least as extreme as yours (p = .027).
- The hatched rejection region at α = .050: statistics landing here reject H₀.
The formula
With your numbers
- the sample's empirical CDF
- the hypothesized CDF, with parameters fixed in advance
- the largest vertical gap between them
The verdict
D = 0.227, p = .027
p ≤ α = .050: reject H₀
Effect size: largest ECDF gap D = 0.227
Parameters must be specified, not estimated from the same data — estimating them makes this p-value far too large (use Lilliefors for normality). R uses D's exact distribution below n = 100 without ties.
- Statistic
- 0.227
- p-value
- 0.0267
One-sample Kolmogorov–Smirnov test on Sample: n = 40: D = 0.227, p = .027. The p-value is below α = .050, so the data are hard to reconcile with H₀.
Fit it, then test it?
PredictPredict first
You estimate a normal's mean and SD from your data, then run the usual KS test against that fitted normal, with the usual p-value.
Suppose the data really are normal. What are those p-values like?
Reveal
Too large. Fitting pulls the curve toward the data, so the gap is smaller than the textbook null expects. The test almost never rejects, even when it should. Lilliefors noticed this for the normal.
The parametric bootstrap
ReadThe fix is to repeat the whole procedure under the fitted model:
- Fit the family to your data and compute the statistic.
- Simulate a sample from the fitted model.
- Refit on that sample, and compute its statistic.
- Repeat, and see where yours falls.
The card's p-values from option does this automatically when parameters are estimated. With parameters stated in advance, the exact formulas are correct.
Stated in advance
ReadNormal(mean = 50, SD = 8); KS D = 0.12, p = .166; A² = 2.08, p = .083
- AIC
- 552.40
- KS D
- 0.1226
- Anderson–Darling p
- 0.0834
Plots
View data
| density | curve | normalish |
|---|---|---|
| 0.0036 | Data (kernel density) | 29.983 |
| 0.0039 | Data (kernel density) | 30.182 |
| 0.0041 | Data (kernel density) | 30.381 |
| 0.0044 | Data (kernel density) | 30.579 |
| 0.0047 | Data (kernel density) | 30.778 |
| 0.0050 | Data (kernel density) | 30.977 |
| 0.0052 | Data (kernel density) | 31.176 |
| 0.0055 | Data (kernel density) | 31.375 |
| 0.0058 | Data (kernel density) | 31.573 |
| 0.0061 | Data (kernel density) | 31.772 |
| 0.0063 | Data (kernel density) | 31.971 |
| 0.0066 | Data (kernel density) | 32.170 |
| 0.0069 | Data (kernel density) | 32.368 |
| 0.0071 | Data (kernel density) | 32.567 |
| 0.0074 | Data (kernel density) | 32.766 |
| 0.0077 | Data (kernel density) | 32.965 |
| 0.0079 | Data (kernel density) | 33.164 |
| 0.0082 | Data (kernel density) | 33.362 |
| 0.0085 | Data (kernel density) | 33.561 |
| 0.0088 | Data (kernel density) | 33.760 |
| 0.0091 | Data (kernel density) | 33.959 |
| 0.0095 | Data (kernel density) | 34.157 |
| 0.0098 | Data (kernel density) | 34.356 |
| 0.0102 | Data (kernel density) | 34.555 |
| 0.0106 | Data (kernel density) | 34.754 |
| 0.0110 | Data (kernel density) | 34.953 |
| 0.0115 | Data (kernel density) | 35.151 |
| 0.0120 | Data (kernel density) | 35.350 |
| 0.0125 | Data (kernel density) | 35.549 |
| 0.0131 | Data (kernel density) | 35.748 |
| 0.0137 | Data (kernel density) | 35.946 |
| 0.0144 | Data (kernel density) | 36.145 |
| 0.0151 | Data (kernel density) | 36.344 |
| 0.0159 | Data (kernel density) | 36.543 |
| 0.0167 | Data (kernel density) | 36.742 |
| 0.0175 | Data (kernel density) | 36.940 |
| 0.0184 | Data (kernel density) | 37.139 |
| 0.0193 | Data (kernel density) | 37.338 |
| 0.0203 | Data (kernel density) | 37.537 |
| 0.0213 | Data (kernel density) | 37.735 |
| 0.0223 | Data (kernel density) | 37.934 |
| 0.0234 | Data (kernel density) | 38.133 |
| 0.0245 | Data (kernel density) | 38.332 |
| 0.0256 | Data (kernel density) | 38.531 |
| 0.0267 | Data (kernel density) | 38.729 |
| 0.0278 | Data (kernel density) | 38.928 |
| 0.0290 | Data (kernel density) | 39.127 |
| 0.0301 | Data (kernel density) | 39.326 |
| 0.0312 | Data (kernel density) | 39.524 |
| 0.0323 | Data (kernel density) | 39.723 |
| 0.0333 | Data (kernel density) | 39.922 |
| 0.0343 | Data (kernel density) | 40.121 |
| 0.0353 | Data (kernel density) | 40.320 |
| 0.0363 | Data (kernel density) | 40.518 |
| 0.0372 | Data (kernel density) | 40.717 |
| 0.0380 | Data (kernel density) | 40.916 |
| 0.0388 | Data (kernel density) | 41.115 |
| 0.0395 | Data (kernel density) | 41.314 |
| 0.0402 | Data (kernel density) | 41.512 |
| 0.0408 | Data (kernel density) | 41.711 |
First 60 of 400 rows.
View data
| normalish (sorted) | Fitted Normal quantile |
|---|---|
| 31.781 | 30.018 |
| 32.819 | 33.358 |
| 33.564 | 35.098 |
| 36.185 | 36.330 |
| 36.827 | 37.304 |
| 38.977 | 38.119 |
| 39.035 | 38.826 |
| 39.262 | 39.456 |
| 39.750 | 40.026 |
| 39.967 | 40.550 |
| 39.987 | 41.036 |
| 40.833 | 41.491 |
| 40.927 | 41.920 |
| 41.040 | 42.327 |
| 41.397 | 42.715 |
| 41.493 | 43.087 |
| 41.562 | 43.444 |
| 42.300 | 43.789 |
| 42.470 | 44.122 |
| 42.508 | 44.446 |
| 42.828 | 44.760 |
| 43.201 | 45.067 |
| 43.291 | 45.367 |
| 43.422 | 45.660 |
| 43.789 | 45.948 |
| 44.029 | 46.230 |
| 44.121 | 46.508 |
| 44.288 | 46.782 |
| 44.415 | 47.052 |
| 45.146 | 47.319 |
| 45.576 | 47.582 |
| 45.850 | 47.844 |
| 46.205 | 48.102 |
| 46.256 | 48.359 |
| 46.609 | 48.614 |
| 47.278 | 48.868 |
| 47.291 | 49.121 |
| 48.008 | 49.373 |
| 49.182 | 49.624 |
| 49.206 | 49.875 |
| 49.281 | 50.125 |
| 49.318 | 50.376 |
| 49.419 | 50.627 |
| 50.058 | 50.879 |
| 50.284 | 51.132 |
| 50.585 | 51.386 |
| 50.665 | 51.641 |
| 50.868 | 51.898 |
| 50.907 | 52.156 |
| 50.933 | 52.418 |
| 51.447 | 52.681 |
| 51.485 | 52.948 |
| 51.602 | 53.218 |
| 51.698 | 53.492 |
| 52.141 | 53.770 |
| 52.293 | 54.052 |
| 52.313 | 54.340 |
| 52.358 | 54.633 |
| 52.822 | 54.933 |
| 53.088 | 55.240 |
First 60 of 80 rows.
Assumptions
- Independent, identically distributed values — The tests assume one distribution generated every value independently; trends, clusters or mixtures break this.
Fitted distribution
| Distribution | Parameters (ML) | Log-likelihood | AIC | ΔAIC | Akaike weight | KS D |
|---|---|---|---|---|---|---|
| Normal | mean = 48.4; SD = 7.454 | −274.21 | 552.42 | 0 | 1 | 0.0669 |
Goodness of fit — Normal
| Test | Statistic | Value | p |
|---|---|---|---|
| Kolmogorov–Smirnov | D | 0.1226 | .166 |
| Cramér–von Mises | W² | 0.3941 | .075 |
| Anderson–Darling | A² | 2.078 | .083 |
- The tests ask whether the data could come from the fitted distribution; not rejecting is not proof of fit. Read the Q–Q plot.
The exact R script · R R version 4.5.1 (2025-06-13)
# Fit a distribution (goodness of fit)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method distribution.fit 1.0.1 · spec a505972121867f85
# Dataset: h_fit (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/h_fit.parquet", col_select = c("normalish")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("normalish")]), , 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("normalish")) # infinite values stop the run (registry/errors.yaml)
# %% Fit
y <- "normalish"
x <- as.numeric(df[[y]])
x <- x[is.finite(x)]
n <- length(x)
family <- "normal"
specified <- "specified" == "specified"
calibration <- "auto"
seed <- 42 # bootstrap samples come from the shared Wichmann-Hill stream
reps <- as.integer(999)
alpha <- 0.05
fams <- cs_dist_families()
if (n < 5) cs_error("CS_E_TOO_FEW_ROWS", what = "Fitting a distribution", min = 5, n = n)
if (length(unique(x)) < 2) cs_error("CS_E_CONSTANT", column = y) # every family's scale estimate would be zero
if (family == "compare") {
candidates <- Filter(function(f) cs_dist_supports(f, x), names(fams))
} else {
if (!cs_dist_supports(family, x)) {
need <- switch(fams[[family]]$support, positive = "positive values", nonnegative = "values ≥ 0", unit = "values strictly between 0 and 1")
stop(sprintf("The %s distribution needs %s; %s has values outside that range.", fams[[family]]$label, need, y))
}
candidates <- family
}
fits <- lapply(candidates, function(f) cs_dist_fit_one(f, x))
usable <- Filter(function(f) isTRUE(f$ok) && is.finite(f$aic), fits)
if (!length(usable)) stop(sprintf("No candidate distribution could be fitted to %s.", y))
best <- usable[[which.min(vapply(usable, function(f) f$aic, numeric(1)))]]
chosen <- best$family
spec <- NULL
if (specified) {
given <- list(loc = 50, scale = 8, shape = NULL, shape2 = NULL)
missing <- Filter(function(k) is.null(given[[k]]), fams[[chosen]]$params)
if (length(missing)) stop(sprintf("Specified parameters for the %s distribution need: %s.", fams[[chosen]]$label, paste(missing, collapse = ", ")))
spec <- lapply(given, function(v) if (is.null(v)) NaN else as.numeric(v))
spec$converged <- TRUE
}
gof <- cs_dist_gof_test(chosen, x, spec, calibration, reps = reps, seed = seed)
p_used <- gof$params
k_used <- if (specified) 0 else fams[[chosen]]$k
ll <- sum(cs_dist_logpdf(chosen, x, p_used))
tests <- list(list("Kolmogorov–Smirnov", "D", gof$ks_d, gof$ks_p), list("Cramér–von Mises", "W²", gof$cvm_w2, gof$cvm_p),
list("Anderson–Darling", "A²", gof$ad_a2, gof$ad_p))
n_reject <- sum(vapply(tests, function(t) is.finite(t[[4]]) && t[[4]] < alpha, logical(1)))
m <- mean(x)
m2 <- mean((x - m)^2)
g1 <- if (m2 > 0) sqrt(n * (n - 1)) / (n - 2) * mean((x - m)^3) / m2^1.5 else NaN
g2 <- if (m2 > 0) ((n + 1) * (mean((x - m)^4) / m2^2 - 3) + 6) * (n - 1) / ((n - 2) * (n - 3)) else NaN
# %% Result
values <- list(n = n, family = chosen, n_params = k_used, loglik = ll, aic = 2 * k_used - 2 * ll, bic = k_used * log(n) - 2 * ll,
loc = p_used$loc, scale = p_used$scale, shape = p_used$shape, shape2 = p_used$shape2,
ks_d = gof$ks_d, ks_p = gof$ks_p, cvm_w2 = gof$cvm_w2, cvm_p = gof$cvm_p, ad_a2 = gof$ad_a2, ad_p = gof$ad_p,
n_reject = n_reject, calibration = gof$calibration, reps_used = gof$reps, skewness = g1, kurtosis = g2,
n_candidates = length(usable))
w_den <- sum(vapply(usable, function(f) exp(-(f$aic - best$aic) / 2), numeric(1)))
fam_rows <- list()
for (f in fits) {
d_aic <- if (isTRUE(f$ok)) f$aic - best$aic else NaN
w <- if (isTRUE(f$ok)) exp(-d_aic / 2) / w_den else NaN
if (family == "compare") {
values[[sprintf("aic[%s]", f$family)]] <- f$aic
values[[sprintf("delta_aic[%s]", f$family)]] <- d_aic
values[[sprintf("weight[%s]", f$family)]] <- w
values[[sprintf("ks_d[%s]", f$family)]] <- f$ks_d
}
info <- fams[[f$family]]
fam_rows[[length(fam_rows) + 1]] <- list(
family = info$label,
parameters = if (isTRUE(f$ok)) paste(sprintf("%s = %s", info$names, vapply(info$params, function(k) formatC(f$params[[k]], digits = 4, format = "g"), "")), collapse = "; ") else "did not converge",
loglik = f$loglik, aic = f$aic, delta_aic = d_aic, weight = w, ks_d = f$ks_d)
}
fam_rows <- fam_rows[order(!vapply(fam_rows, function(r) is.finite(r$aic), logical(1)), vapply(fam_rows, function(r) if (is.finite(r$aic)) r$aic else 0, numeric(1)))]
info <- fams[[chosen]]
par_text <- paste(sprintf("%s = %s", info$names, vapply(info$params, function(k) formatC(p_used[[k]], digits = 4, format = "g"), "")), collapse = ", ")
how <- paste0(gof$calibration, if (gof$reps > 0) sprintf(", %d replicates, seed %d", as.integer(gof$reps), as.integer(seed)) else "")
lead <- if (family == "compare") {
sprintf("Of %d candidate distributions, the %s distribution fits %s best by AIC (weight %.2f). ", length(usable), info$label, y, 1 / w_den)
} else {
sprintf("%s distribution %s. ", info$label, if (specified) "with the specified parameters" else "fitted by maximum likelihood")
}
summary <- paste0(lead, sprintf("Parameters: %s. Goodness of fit (%s): KS D = %.3f, %s; Cramér–von Mises W² = %.3f, %s; Anderson–Darling A² = %.3f, %s — ",
par_text, how, gof$ks_d, cs_fmt_p(gof$ks_p), gof$cvm_w2, cs_fmt_p(gof$cvm_p), gof$ad_a2, cs_fmt_p(gof$ad_p)),
if (n_reject == 0) "no test rejects the fit." else sprintf("%d of 3 tests reject the fit at α = .05.", n_reject))
notes <- list("The tests ask whether the data could come from the fitted distribution; not rejecting is not proof of fit. Read the Q–Q plot.")
if (!specified && endsWith(gof$calibration, "formulas")) {
warnings <- c(warnings, "The parameters were estimated from the same data, so the textbook p-values are too large (anti-conservative); use the parametric bootstrap.")
}
if (!specified) notes[[length(notes) + 1]] <- "With estimated parameters the p-values come from a parametric bootstrap that refits every simulated sample (Stute et al. 1993)."
if (family == "compare") notes[[length(notes) + 1]] <- "AIC compares the candidates on the same data; Akaike weights are the relative support for each, given this set."
lo <- min(x)
hi <- max(x)
pad <- 0.05 * (if (hi > lo) hi - lo else 1)
gl <- lo - pad
gh <- hi + pad
if (info$support %in% c("positive", "nonnegative")) gl <- max(gl, if (lo > 0) lo / 2 else 0)
if (info$support == "unit") {
gl <- max(gl, 1e-4)
gh <- min(gh, 1 - 1e-4)
}
grid <- seq(gl, gh, length.out = 200)
ranked <- usable[order(vapply(usable, function(f) f$aic, numeric(1)))]
show <- c(chosen, if (family == "compare") head(Filter(function(f) f != chosen, vapply(ranked, function(f) f$family, "")), 2) else character(0))
dens_x <- grid
dens_y <- cs_dist_kde(x, grid)
dens_src <- rep("Data (kernel density)", length(grid))
for (fam in show) {
pf <- if (fam == chosen) p_used else Filter(function(f) f$family == fam, usable)[[1]]$params
s <- fams[[fam]]$support
ok <- if (s == "positive") grid > 0 else if (s == "nonnegative") grid >= 0 else if (s == "unit") grid > 0 & grid < 1 else rep(TRUE, length(grid))
dv <- numeric(length(grid))
dv[ok] <- exp(cs_dist_logpdf(fam, grid[ok], pf))
dv[!is.finite(dv)] <- 0
dens_x <- c(dens_x, grid)
dens_y <- c(dens_y, dv)
dens_src <- c(dens_src, rep(paste("Fitted", fams[[fam]]$label), length(grid)))
}
xs <- sort(x)
theo <- cs_dist_quantile(chosen, (seq_len(n) - 0.5) / n, p_used)
cs_publish(list(
method = "distribution.fit",
methodVersion = "1.0.1",
title = paste("Distribution fit —", info$label),
engine = cs_engine_info("stats", "nanoparquet"),
n = n,
summary = summary,
apa = sprintf("%s(%s); KS D = %.2f, %s; A² = %.2f, %s", info$label, par_text, gof$ks_d, cs_fmt_p(gof$ks_p), gof$ad_a2, cs_fmt_p(gof$ad_p)),
statistics = list(list(key = "aic", label = "AIC", value = values$aic), list(key = "ks_d", label = "KS D", value = gof$ks_d),
list(key = "ad_p", label = "Anderson–Darling p", value = gof$ad_p)),
tables = list(
list(key = "fit", title = if (family == "compare") "Candidate distributions" else "Fitted distribution", columns = list(
list(key = "family", label = "Distribution", type = "string"), list(key = "parameters", label = "Parameters (ML)", type = "string"),
list(key = "loglik", label = "Log-likelihood", type = "number"), list(key = "aic", label = "AIC", type = "number"),
list(key = "delta_aic", label = "ΔAIC", type = "number"), list(key = "weight", label = "Akaike weight", type = "number"),
list(key = "ks_d", label = "KS D", type = "number")), rows = fam_rows),
list(key = "gof", title = paste("Goodness of fit —", info$label), columns = list(
list(key = "test", label = "Test", type = "string"), list(key = "symbol", label = "Statistic", type = "string"),
list(key = "statistic", label = "Value", type = "number"), list(key = "p", label = "p", type = "pvalue")),
rows = lapply(tests, function(t) list(test = t[[1]], symbol = t[[2]], statistic = t[[3]], p = t[[4]])))
),
effectSizes = list(),
assumptions = list(list(key = "independence", label = "Independent, identically distributed values", status = "info",
detail = "The tests assume one distribution generated every value independently; trends, clusters or mixtures break this.")),
warnings = warnings,
notes = notes,
charts = list(
cs_chart("density", "density-compare", sprintf("%s: data and fitted density", y),
list(x = cs_col(y, dens_x), density = cs_col("density", dens_y), source = cs_col("curve", dens_src))),
cs_chart("qq", "pred-actual", sprintf("Q–Q plot against the fitted %s", info$label),
list(actual = cs_col(paste0(y, " (sorted)"), xs), predicted = cs_col(paste("Fitted", info$label, "quantile"), theo)))
),
values = values
))
Normal(mean = 50, SD = 8); KS D = 0.12, p = .166; A² = 2.08, p = .083
- AIC
- 552.40
- KS D
- 0.1226
- Anderson–Darling p
- 0.0834
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Independent, identically distributed values — The tests assume one distribution generated every value independently; trends, clusters or mixtures break this.
Fitted distribution
| Distribution | Parameters (ML) | Log-likelihood | AIC | ΔAIC | Akaike weight | KS D |
|---|---|---|---|---|---|---|
| Normal | mean = 48.4; SD = 7.454 | −274.21 | 552.42 | 0 | 1 | 0.0669 |
Goodness of fit — Normal
| Test | Statistic | Value | p |
|---|---|---|---|
| Kolmogorov–Smirnov | D | 0.1226 | .166 |
| Cramér–von Mises | W² | 0.3941 | .075 |
| Anderson–Darling | A² | 2.078 | .083 |
- The tests ask whether the data could come from the fitted distribution; not rejecting is not proof of fit. Read the Q–Q plot.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Fit a distribution (goodness of fit)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method distribution.fit 1.0.1 · spec a505972121867f85
# Dataset: h_fit (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
import codesplash as cs
from codesplash.stats import distribution as csd
# %% Data
df = pd.read_parquet("tests/parity/fixtures/h_fit.parquet", columns=["normalish"])
n_input = len(df)
df = df.dropna(subset=["normalish"]) # listwise deletion over the analysis columns
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, ["normalish"]) # infinite values stop the run (registry/errors.yaml)
# %% Fit
y = "normalish"
x = df[y].to_numpy(dtype=float)
x = x[np.isfinite(x)]
n = x.size
family = "normal"
specified = "specified" == "specified"
calibration = "auto"
seed, reps = 42, int(999) # bootstrap samples come from the shared Wichmann–Hill stream
alpha = 0.05
nan = math.nan
if n < 5:
cs.cs_error("CS_E_TOO_FEW_ROWS", what="Fitting a distribution", min=5, n=n)
if len(np.unique(x)) < 2: # every family's scale estimate would be zero
cs.cs_error("CS_E_CONSTANT", column=y)
if family == "compare":
candidates = [f for f in csd.FAMILY_ORDER if csd.supports(f, x)]
else:
if not csd.supports(family, x):
need = {"positive": "positive values", "nonnegative": "values ≥ 0", "unit": "values strictly between 0 and 1"}[csd.FAMILIES[family]["support"]]
raise ValueError(f"The {csd.FAMILIES[family]['label']} distribution needs {need}; {y} has values outside that range.")
candidates = [family]
fits = [csd.fit_one(f, x) for f in candidates]
usable = [f for f in fits if f["ok"] and np.isfinite(f["aic"])]
if not usable:
raise ValueError(f"No candidate distribution could be fitted to {y}.")
best = min(usable, key=lambda f: f["aic"])
chosen = best["family"]
spec = None
if specified:
given = {"loc": 50, "scale": 8, "shape": None, "shape2": None}
missing = [k for k in csd.FAMILIES[chosen]["params"] if given[k] is None]
if missing:
raise ValueError(f"Specified parameters for the {csd.FAMILIES[chosen]['label']} distribution need: {', '.join(missing)}.")
spec = {k: (nan if v is None else float(v)) for k, v in given.items()} | {"converged": True}
gof = csd.gof_test(chosen, x, spec, calibration, reps=reps, seed=seed)
p_used = gof["params"]
k_used = 0 if specified else csd.FAMILIES[chosen]["k"]
ll = float(np.sum(csd.logpdf(chosen, x, p_used)))
tests = [("Kolmogorov–Smirnov", "D", gof["ks_d"], gof["ks_p"]), ("Cramér–von Mises", "W²", gof["cvm_w2"], gof["cvm_p"]),
("Anderson–Darling", "A²", gof["ad_a2"], gof["ad_p"])]
n_reject = sum(1 for t in tests if np.isfinite(t[3]) and t[3] < alpha)
m = float(np.mean(x))
m2 = float(np.mean((x - m) ** 2))
g1 = math.sqrt(n * (n - 1)) / (n - 2) * float(np.mean((x - m) ** 3)) / m2**1.5 if m2 > 0 else nan
g2 = ((n + 1) * (float(np.mean((x - m) ** 4)) / m2**2 - 3) + 6) * (n - 1) / ((n - 2) * (n - 3)) if m2 > 0 else nan
# %% Result
values = {"n": n, "family": chosen, "n_params": k_used, "loglik": ll, "aic": 2 * k_used - 2 * ll, "bic": k_used * math.log(n) - 2 * ll,
"loc": p_used["loc"], "scale": p_used["scale"], "shape": p_used["shape"], "shape2": p_used["shape2"],
"ks_d": gof["ks_d"], "ks_p": gof["ks_p"], "cvm_w2": gof["cvm_w2"], "cvm_p": gof["cvm_p"], "ad_a2": gof["ad_a2"], "ad_p": gof["ad_p"],
"n_reject": n_reject, "calibration": gof["calibration"], "reps_used": gof["reps"], "skewness": g1, "kurtosis": g2,
"n_candidates": len(usable)}
fam_rows = []
w_den = sum(math.exp(-(f["aic"] - best["aic"]) / 2) for f in usable)
for f in fits:
d_aic = f["aic"] - best["aic"] if f["ok"] else nan
w = math.exp(-d_aic / 2) / w_den if f["ok"] else nan
if family == "compare":
values.update({f"aic[{f['family']}]": f["aic"], f"delta_aic[{f['family']}]": d_aic, f"weight[{f['family']}]": w, f"ks_d[{f['family']}]": f["ks_d"]})
info = csd.FAMILIES[f["family"]]
fam_rows.append({"family": info["label"],
"parameters": "; ".join(f"{nm} = {f['params'][k]:.4g}" for nm, k in zip(info["names"], info["params"])) if f["ok"] else "did not converge",
"loglik": f["loglik"], "aic": f["aic"], "delta_aic": d_aic, "weight": w, "ks_d": f["ks_d"]})
info = csd.FAMILIES[chosen]
par_text = ", ".join(f"{nm} = {p_used[k]:.4g}" for nm, k in zip(info["names"], info["params"]))
how = gof["calibration"] + (f", {gof['reps']} replicates, seed {seed}" if gof["reps"] else "")
lead = (f"Of {len(usable)} candidate distributions, the {info['label']} distribution fits {y} best by AIC (weight {1 / w_den:.2f}). "
if family == "compare" else f"{info['label']} distribution {'with the specified parameters' if specified else 'fitted by maximum likelihood'}. ")
summary = (lead + f"Parameters: {par_text}. Goodness of fit ({how}): KS D = {gof['ks_d']:.3f}, {cs.fmt_p(gof['ks_p'])}; "
f"Cramér–von Mises W² = {gof['cvm_w2']:.3f}, {cs.fmt_p(gof['cvm_p'])}; Anderson–Darling A² = {gof['ad_a2']:.3f}, {cs.fmt_p(gof['ad_p'])} — "
+ ("no test rejects the fit." if n_reject == 0 else f"{n_reject} of 3 tests reject the fit at α = .05."))
notes = ["The tests ask whether the data could come from the fitted distribution; not rejecting is not proof of fit. Read the Q–Q plot."]
if not specified and gof["calibration"].endswith("formulas"):
warnings.append("The parameters were estimated from the same data, so the textbook p-values are too large (anti-conservative); use the parametric bootstrap.")
if not specified:
notes.append("With estimated parameters the p-values come from a parametric bootstrap that refits every simulated sample (Stute et al. 1993).")
if family == "compare":
notes.append("AIC compares the candidates on the same data; Akaike weights are the relative support for each, given this set.")
# charts: fitted density over a kernel density of the data; Q–Q against the fitted quantiles
lo, hi = float(np.min(x)), float(np.max(x))
pad = 0.05 * (hi - lo if hi > lo else 1.0)
gl, gh = lo - pad, hi + pad
if info["support"] in ("positive", "nonnegative"):
gl = max(gl, lo / 2 if lo > 0 else 0.0)
if info["support"] == "unit":
gl, gh = max(gl, 1e-4), min(gh, 1 - 1e-4)
grid = np.linspace(gl, gh, 200)
show = [chosen] + ([f["family"] for f in sorted(usable, key=lambda f: f["aic"]) if f["family"] != chosen][:2] if family == "compare" else [])
dens_x, dens_y, dens_src = list(grid), list(csd.kde(x, grid)), ["Data (kernel density)"] * grid.size
for fam in show:
pf = p_used if fam == chosen else next(f["params"] for f in usable if f["family"] == fam)
ok = (grid > 0) if csd.FAMILIES[fam]["support"] in ("positive",) else ((grid >= 0) if csd.FAMILIES[fam]["support"] == "nonnegative" else ((grid > 0) & (grid < 1) if csd.FAMILIES[fam]["support"] == "unit" else np.ones(grid.size, bool)))
dv = np.zeros(grid.size)
dv[ok] = np.exp(csd.logpdf(fam, grid[ok], pf))
dens_x += list(grid)
dens_y += list(np.where(np.isfinite(dv), dv, 0.0))
dens_src += [f"Fitted {csd.FAMILIES[fam]['label']}"] * grid.size
xs = np.sort(x)
theo = csd.quantile(chosen, (np.arange(1, n + 1) - 0.5) / n, p_used)
cs.publish({
"method": "distribution.fit",
"methodVersion": "1.0.1",
"title": f"Distribution fit — {info['label']}",
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": n,
"summary": summary,
"apa": f"{info['label']}({par_text}); KS D = {gof['ks_d']:.2f}, {cs.fmt_p(gof['ks_p'])}; A² = {gof['ad_a2']:.2f}, {cs.fmt_p(gof['ad_p'])}",
"statistics": [{"key": "aic", "label": "AIC", "value": values["aic"]}, {"key": "ks_d", "label": "KS D", "value": gof["ks_d"]},
{"key": "ad_p", "label": "Anderson–Darling p", "value": gof["ad_p"]}],
"tables": [
{"key": "fit", "title": "Candidate distributions" if family == "compare" else "Fitted distribution", "columns": [
{"key": "family", "label": "Distribution", "type": "string"}, {"key": "parameters", "label": "Parameters (ML)", "type": "string"},
{"key": "loglik", "label": "Log-likelihood", "type": "number"}, {"key": "aic", "label": "AIC", "type": "number"},
{"key": "delta_aic", "label": "ΔAIC", "type": "number"}, {"key": "weight", "label": "Akaike weight", "type": "number"},
{"key": "ks_d", "label": "KS D", "type": "number"}], "rows": sorted(fam_rows, key=lambda r: (not np.isfinite(r["aic"]), r["aic"] if np.isfinite(r["aic"]) else 0))},
{"key": "gof", "title": f"Goodness of fit — {info['label']}", "columns": [
{"key": "test", "label": "Test", "type": "string"}, {"key": "symbol", "label": "Statistic", "type": "string"},
{"key": "statistic", "label": "Value", "type": "number"}, {"key": "p", "label": "p", "type": "pvalue"}],
"rows": [{"test": t[0], "symbol": t[1], "statistic": t[2], "p": t[3]} for t in tests]},
],
"effectSizes": [],
"assumptions": [{"key": "independence", "label": "Independent, identically distributed values", "status": "info",
"detail": "The tests assume one distribution generated every value independently; trends, clusters or mixtures break this."}],
"warnings": warnings,
"notes": notes,
"charts": [
cs.chart("density", "density-compare", f"{y}: data and fitted density",
{"x": cs.col(y, dens_x), "density": cs.col("density", dens_y), "source": cs.col("curve", dens_src)}),
cs.chart("qq", "pred-actual", f"Q–Q plot against the fitted {info['label']}",
{"actual": cs.col(f"{y} (sorted)", xs), "predicted": cs.col(f"Fitted {info['label']} quantile", theo)}),
],
"values": values,
})
Here the question fixes a normal with mean 50 and SD 8 before seeing the data:
- KS: D = 0.123, p = .166.
- CvM: p = .075.
- AD: p = .083.
Calibration: exact formulas.
Tests can disagree
PredictPredict first
A Weibull is fitted to 80 lifetimes, using 199 bootstrap samples. The largest gap happens at one spot in the middle.
Which test gives the lowest p-value?
Reveal
KS: p = .050, against CvM p = .220 and AD p = .320. They answer related but different questions, so don't shop among them.
A large p isn't a verdict
ReadA gamma fitted to the same lifetimes gives KS p = .165, CvM p = .285 and AD p = .410. The Weibull wasn't rejected either.
So these data can't separate those families, and a large p-value isn't evidence for the one you tried.
A bad fit does stand out: a Gumbel on the bimodal Old Faithful waiting times gives p = .010 from AD. To choose between candidates, compare them: here AIC ranks 12 families and puts gamma first.
What will you do with the fit?
ReflectYou want a model for how long support tickets stay open. With a thousand tickets, every family gets rejected, because tiny departures become detectable. With twenty tickets, none does.
Which matters more for your decision: a p-value or how well the model predicts the part of the range you care about? How would you check that?
Check your understanding
CheckpointCheck yourself
You care most about whether a model captures extreme values. Which statistic gives the most weight to the tails?
Show the answer
Answer: c
Anderson–Darling divides the squared gap by , which is small in the tails, so tail gaps count for more.
Check yourself
In a parametric bootstrap for a goodness-of-fit test, what must happen on each simulated sample?
Show the answer
Answer: b
The null has to include the fitting step, because fitting is what shrinks the gap. That is the point of refitting every time.
Check yourself
Run the first script below on h_fit.csv. What is the KS statistic for normalish against a normal with mean 50 and SD 8? Give three decimals.
Show the answer
Answer: 0.122635765915539
The largest gap between the ECDF and that normal's CDF. It matches the card because these parameters were stated in advance.
Do it in CodeSplash
In the appChoose a Distribution, or Compare all that fit (AIC). Under Parameters, choose whether they're estimated or specified. Leave p-values from on Automatic, so that estimated parameters get the bootstrap.
The first script reproduces the stated-parameter KS test. The second simulates what happens if you use the textbook p-value after fitting: at the 0.05 level it rejects far less than 5% of the time. Simulated counts differ between languages.
import numpy as np
import pandas as pd
from scipy import stats
x = pd.read_csv("h_fit.csv")["normalish"]
print(stats.kstest(x, stats.norm(50, 8).cdf))
rng = np.random.default_rng(1)
reject = 0
for _ in range(2000):
s = rng.normal(size=50)
p = stats.kstest(s, stats.norm(s.mean(), s.std(ddof=1)).cdf).pvalue
reject += p < 0.05
print(reject / 2000)x <- read.csv("h_fit.csv")$normalish
print(ks.test(x, "pnorm", 50, 8))
set.seed(1)
reject <- 0
for (i in 1:2000) {
s <- rnorm(50)
p <- ks.test(s, "pnorm", mean(s), sd(s))$p.value
reject <- reject + (p < 0.05)
}
reject / 2000Recap
Recap- KS uses the largest gap, CvM the average squared gap, AD adds weight in the tails.
- If you estimate parameters from the same data, use the parametric bootstrap, refitting each time.
- A large p-value is only compatible with the family. Compare candidates with AIC.
Concepts in this lesson