Skip to content

ADescribe · distribution.ksd

Kernel Stein discrepancy goodness-of-fit test

Do the data fit a normal, lognormal or gamma model — in one variable or several at once?

Measures how far the data are from a fitted model with the kernel Stein discrepancy, which needs only the model's score function, so it works for several variables at once (multivariate normal) as well as one positive variable (lognormal, gamma). The data are first put on the fitted model's own scale, so the result doesn't depend on units; the p-value refits the model on bootstrap samples drawn from it, so estimating the parameters is accounted for. Experimental.

Experimental Python and R agree to 6 decimals Seeded Also called KSD, kernel Stein discrepancy, Stein discrepancy test…

A real result

Example “Normal one variable”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

Kernel Stein discrepancy testRecorded · Python and R agreeRecorded 2026-11-21 · 11 values compared
R

n·KSD² = 1.59, p = .200

n·KSD²
1.595
p
.200
KSD² (unbiased)
−0.0031

Plots

n·KSD² under the fitted modelHow unusual is the observed statistic if the null hypothesis were true?
View data
DensityObservedn·KSD²
0.27531.5950.1587
0.41291.5950.2320
0.27531.5950.3054
0.41291.5950.3788
0.68821.5950.4522
0.13761.5950.5256
0.55061.5950.5990
0.68821.5950.6724
1.3761.5950.7457
0.68821.5950.8191
0.68821.5950.8925
0.82581.5950.9659
1.3761.5951.039
0.82581.5951.113
0.27531.5951.186
0.27531.5951.259
0.27531.5951.333
0.13761.5951.406
0.41291.5951.480
0.41291.5951.553
0.27531.5951.626
0.13761.5951.700
0.13761.5951.773
01.5951.847
0.13761.5951.920
0.27531.5951.993
0.55061.5952.067
0.13761.5952.140
0.13761.5952.213
0.27531.5952.287
01.5952.360
0.13761.5952.434
01.5952.507
01.5952.580
01.5952.654
0.13761.5952.727
01.5952.801
01.5952.874
0.13761.5952.947
0.13761.5953.021

Assumptions

  • Independent rows — The test treats the rows as independent draws from one distribution.
  • Calibration accounts for fitting — Each bootstrap sample is refitted, so the p-value accounts for estimating the parameters.

Fitted normal model (maximum likelihood)

ParameterEstimate
mean of Wind9.958
SD of Wind3.511
  • Inverse multiquadric kernel (1 + ‖x − y‖²/h²)^(−1/2) with h = 0.9683, the median distance between rows on the fitted model's own scale (whitened for the normal; divided by the fitted scale otherwise); bootstrap on the shared seeded stream (seed 42), p = (1 + count) / (B + 1).
Python

n·KSD² = 1.59, p = .200

n·KSD²
1.595
p
.200
KSD² (unbiased)
−0.0031

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

Assumptions

  • Independent rows — The test treats the rows as independent draws from one distribution.
  • Calibration accounts for fitting — Each bootstrap sample is refitted, so the p-value accounts for estimating the parameters.

Fitted normal model (maximum likelihood)

ParameterEstimate
mean of Wind9.958
SD of Wind3.511
  • Inverse multiquadric kernel (1 + ‖x − y‖²/h²)^(−1/2) with h = 0.9683, the median distance between rows on the fitted model's own scale (whitened for the normal; divided by the fitted scale otherwise); bootstrap on the shared seeded stream (seed 42), p = (1 + count) / (B + 1).

Do it in CodeSplash Run it on your own data. It's in the Experimental lane in the app.

Worked examples in the app

  • Normal one variableairquality · variables: Wind
  • Normal three variablesmv_guide · variables: y1, y2, y3
  • Gamma ozoneairquality · variables: Ozone
  • Lognormal ozone wildairquality · variables: Ozone
  • Lognormal two variablesairquality · variables: Ozone, Wind
  • Degenerate constantairquality · variables: Wind
  • Degenerate n1airquality · variables: Wind
  • Degenerate n2airquality · variables: Wind

In the guides

Where it sits in the decision guides

  • Goodness of fit · Statistics Guide · E — Compare proportions / frequencies

What you need

Variablesnumeric · 1–10 columns
The numeric variables to test; the lognormal and gamma models take one positive variable.

Choices you make

hypothesis

Modeldefault normal

The model whose fit you test; its parameters are estimated from the data.

  • Normal (multivariate for several variables)(default) — Mean and covariance by maximum likelihood; several variables are tested jointly.
  • Lognormal — One positive variable whose logarithm is normal.
  • Gamma — One positive variable; shape and scale by maximum likelihood.
p-value fromdefault parametric

How the null distribution of the statistic is simulated.

  • Parametric bootstrap (refit)(default) — Draws samples from the fitted model and refits each, so estimating the parameters is accounted for.
  • Wild bootstrap (fast) — Random sign weights with the fitted parameters held fixed; quicker but approximate when parameters are estimated.
Bootstrap samplesdefault 199

More samples give a steadier p-value; the smallest possible p is 1/(B + 1).

Significance leveldefault 0.05

Level used in the narrative.

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.

  • Independent rowsNot checked from data: state why it holds

    The rows are independent draws from one distribution.

  • Calibration accounts for fitting

    The parametric bootstrap refits each sample; the wild bootstrap ignores that the parameters were estimated.

What it reports

  • Tests: The data follow the fitted model
family
normal (multivariate for several variables), lognormal or gamma, fitted by maximum likelihood.
calibration
parametric: bootstrap samples drawn from the fitted model and refitted; wild: random sign weights with the fit held fixed.
n
Rows with a value for every variable.
d
How many variables were tested jointly.
statistic
The test statistic: n times the V-statistic estimate of the squared kernel Stein discrepancy; larger means a worse fit.
ksd2
The unbiased estimate of the squared discrepancy; near 0 when the model fits, and it can dip slightly below 0.
p
Share of bootstrap statistics at least as large as the observed one, (1 + count) / (B + 1).
n_boot
How many bootstrap statistics make up the null distribution.
bandwidth
The median distance between rows on the fitted model's scale (whitened, or divided by the fitted scale), used by the IMQ kernel.

Per group, level or term: mean, sd (normal, one variable), meanlog, sdlog (lognormal), shape, scale (gamma)

Python and R

Python and R agree to 6 decimals (relative tolerance 1e-8). Python uses pandas, numpy, scipy, codesplash; R uses stats, nanoparquet, codesplashr.

Default traps between the two languages

  • Both engines fit the same model, build the same Stein kernel matrix and draw the same bootstrap samples from the shared Wichmann–Hill stream; the gamma shape's Newton steps (digamma, trigamma) and the gamma quantiles of the parametric bootstrap (scipy's Boost vs R's qgamma) differ in the last digits.
Python

The exact script CodeSplash ran for example “Normal one variable” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0

# Kernel Stein discrepancy goodness-of-fit test
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method distribution.ksd 1.0.0 · spec cac092c3894a83d4
# Dataset: airquality (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 codesplash as cs
from codesplash.errors import check_not_constant, check_rows
from codesplash.stats import ksd  # twin: codesplashr cs_ksd_*
from codesplash.stats import signflip  # null_curve for the chart

# %% Data
df = pd.read_parquet("tests/parity/fixtures/airquality.parquet", columns=["Wind"])
n_input = len(df)
df = df.dropna(subset=["Wind"])  # 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, ["Wind"])  # infinite values stop the run (registry/errors.yaml)

# %% Test
# Kernel Stein discrepancy (Liu, Lee & Jordan 2016; Chwialkowski et al. 2016): how far the data are from the
# fitted model, using only its score function ∇ log p; IMQ kernel with the median-distance bandwidth.
variables = ["Wind"]
family = "normal"  # normal | lognormal | gamma
calibration = "parametric"  # parametric | wild
n_boot = int(99)
alpha = 0.05
seed = 42  # portable Wichmann–Hill stream: R simulates the same bootstrap data
X = df[variables].to_numpy(dtype=float)
n, d = X.shape
check_rows(n, 5, "The kernel Stein discrepancy test")
for v in variables:
    check_not_constant(df[v].to_numpy(dtype=float), v)
if family != "normal" and d != 1:
    cs.cs_error("CS_E_INVALID_OPTION", option="Model", allowed="the normal model when you test more than one variable", value=family)
if family != "normal" and np.any(X <= 0):
    cs.cs_error("CS_E_INVALID_VALUES", column=variables[0], requirement="positive (the lognormal and gamma models need values above 0)", count=int(np.sum(X <= 0)))
if n > 2000:
    raise ValueError(f"The test builds an n × n kernel matrix for every bootstrap sample; {n} rows is too many (at most 2000).")
res = ksd.ksd_test(X, family, calibration, n_boot, seed)
stat, p, par = res["statistic"], res["p"], res["params"]

# %% Assumptions
assumptions = [
    {"key": "independence", "label": "Independent rows", "status": "info",
     "detail": "The test treats the rows as independent draws from one distribution."},
    {"key": "calibration", "label": "Calibration accounts for fitting", "status": "pass" if calibration == "parametric" else "warn",
     "detail": ("Each bootstrap sample is refitted, so the p-value accounts for estimating the parameters." if calibration == "parametric"
                else "The wild bootstrap holds the fitted parameters fixed; with estimated parameters its p-value is only approximate (usually too large).")},
]

# %% Result
fam_label = {"normal": "multivariate normal" if d > 1 else "normal", "lognormal": "lognormal", "gamma": "gamma"}[family]
if family == "normal":
    rows = ([{"parameter": f"mean of {v}", "value": float(par["mu"][i])} for i, v in enumerate(variables)]
            + [{"parameter": f"SD of {v}", "value": float(np.sqrt(par["Sigma"][i, i]))} for i, v in enumerate(variables)])
    extra = {"mean": float(par["mu"][0]), "sd": float(np.sqrt(par["Sigma"][0, 0]))} if d == 1 else {}
elif family == "lognormal":
    rows = [{"parameter": "mean of log", "value": par["meanlog"]}, {"parameter": "SD of log", "value": par["sdlog"]}]
    extra = {"meanlog": par["meanlog"], "sdlog": par["sdlog"]}
else:
    rows = [{"parameter": "shape", "value": par["shape"]}, {"parameter": "scale", "value": par["scale"]}]
    extra = {"shape": par["shape"], "scale": par["scale"]}
fits = "is compatible with" if p >= alpha else "departs from"
how = f"{n_boot} parametric bootstrap samples, each refitted" if calibration == "parametric" else f"{n_boot} wild-bootstrap sign patterns (parameters held fixed)"
summary = (f"The {fam_label} model {fits} the data in {', '.join(variables)} (n·KSD² = {stat:.4g}, {cs.fmt_p(p)}; {how}). "
           f"The unbiased KSD² estimate is {res['ksd2']:.4g} (0 = the model fits exactly).")
nx, nd = signflip.null_curve(res["null"])
cs.publish({
    "method": "distribution.ksd",
    "methodVersion": "1.0.0",
    "title": "Kernel Stein discrepancy test",
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": n,
    "summary": summary,
    "apa": f"n·KSD² = {cs.fmt_num(stat)}, {cs.fmt_p(p)}",
    "statistics": [{"key": "statistic", "label": "n·KSD²", "value": stat}, {"key": "p", "label": "p", "value": p, "format": "p"},
                   {"key": "ksd2", "label": "KSD² (unbiased)", "value": res["ksd2"]}],
    "tables": [{"key": "fit", "title": f"Fitted {fam_label} model (maximum likelihood)",
                "columns": [{"key": "parameter", "label": "Parameter", "type": "string"}, {"key": "value", "label": "Estimate", "type": "number"}],
                "rows": rows}],
    "effectSizes": [],
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": [f"Inverse multiquadric kernel (1 + ‖x − y‖²/h²)^(−1/2) with h = {res['bandwidth']:.4g}, the median distance between rows on the fitted model's own scale (whitened for the normal; divided by the fitted scale otherwise); "
              f"bootstrap on the shared seeded stream (seed {seed}), p = (1 + count) / (B + 1)."],
    "values": {"family": family, "calibration": calibration, "n": n, "d": d, "statistic": stat, "ksd2": res["ksd2"], "p": p,
               "n_boot": n_boot, "bandwidth": res["bandwidth"], **extra},
    "charts": [cs.chart("null", "null-distribution", "n·KSD² under the fitted model", {
        "x": cs.col("n·KSD²", nx), "density": cs.col("Density", nd), "observed": cs.col("Observed", np.full(nx.size, stat))},
        controls={"alternative": "greater"})],
})
R

The exact script CodeSplash ran for example “Normal one variable” · R version 4.5.1 (2025-06-13)

# Kernel Stein discrepancy goodness-of-fit test
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method distribution.ksd 1.0.0 · spec cac092c3894a83d4
# Dataset: airquality (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/airquality.parquet", col_select = c("Wind")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("Wind")]), , 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("Wind"))  # infinite values stop the run (registry/errors.yaml)

# %% Test
# Kernel Stein discrepancy (Liu, Lee & Jordan 2016; Chwialkowski et al. 2016): how far the data are from the
# fitted model, using only its score function grad log p; IMQ kernel with the median-distance bandwidth.
variables <- c("Wind")
family <- "normal"  # normal | lognormal | gamma
calibration <- "parametric"  # parametric | wild
n_boot <- as.integer(99)
alpha <- 0.05
seed <- 42  # portable Wichmann-Hill stream: Python simulates the same bootstrap data
X <- as.matrix(df[variables])
storage.mode(X) <- "double"
n <- nrow(X)
d <- ncol(X)
cs_check_rows(n, 5, "The kernel Stein discrepancy test")
for (v in variables) cs_check_not_constant(as.numeric(df[[v]]), v)
if (family != "normal" && d != 1) cs_error("CS_E_INVALID_OPTION", option = "Model", allowed = "the normal model when you test more than one variable", value = family)
if (family != "normal" && any(X <= 0)) cs_error("CS_E_INVALID_VALUES", column = variables[1], requirement = "positive (the lognormal and gamma models need values above 0)", count = sum(X <= 0))
if (n > 2000) stop(sprintf("The test builds an n × n kernel matrix for every bootstrap sample; %d rows is too many (at most 2000).", n))
res <- cs_ksd_test(X, family, calibration, n_boot, seed)
stat <- res$statistic
p <- res$p
par <- res$params

# %% Assumptions
assumptions <- list(
  list(key = "independence", label = "Independent rows", status = "info",
       detail = "The test treats the rows as independent draws from one distribution."),
  list(key = "calibration", label = "Calibration accounts for fitting", status = if (calibration == "parametric") "pass" else "warn",
       detail = if (calibration == "parametric") "Each bootstrap sample is refitted, so the p-value accounts for estimating the parameters." else
         "The wild bootstrap holds the fitted parameters fixed; with estimated parameters its p-value is only approximate (usually too large).")
)

# %% Result
fam_label <- switch(family, normal = if (d > 1) "multivariate normal" else "normal", lognormal = "lognormal", gamma = "gamma")
extra <- list()
if (family == "normal") {
  rows <- c(lapply(seq_len(d), function(i) list(parameter = paste("mean of", variables[i]), value = par$mu[[i]])),
            lapply(seq_len(d), function(i) list(parameter = paste("SD of", variables[i]), value = sqrt(par$Sigma[i, i]))))
  if (d == 1) extra <- list(mean = par$mu[[1]], sd = sqrt(par$Sigma[1, 1]))
} else if (family == "lognormal") {
  rows <- list(list(parameter = "mean of log", value = par$meanlog), list(parameter = "SD of log", value = par$sdlog))
  extra <- list(meanlog = par$meanlog, sdlog = par$sdlog)
} else {
  rows <- list(list(parameter = "shape", value = par$shape), list(parameter = "scale", value = par$scale))
  extra <- list(shape = par$shape, scale = par$scale)
}
fits <- if (p >= alpha) "is compatible with" else "departs from"
how <- if (calibration == "parametric") sprintf("%d parametric bootstrap samples, each refitted", n_boot) else sprintf("%d wild-bootstrap sign patterns (parameters held fixed)", n_boot)
summary <- sprintf("The %s model %s the data in %s (n·KSD² = %s, %s; %s). The unbiased KSD² estimate is %s (0 = the model fits exactly).",
                   fam_label, fits, paste(variables, collapse = ", "), format(signif(stat, 4)), cs_fmt_p(p), how, format(signif(res$ksd2, 4)))
nc <- cs_signflip_null_curve(res$null)
values <- c(list(family = family, calibration = calibration, n = n, d = d, statistic = stat, ksd2 = res$ksd2, p = p,
                 n_boot = n_boot, bandwidth = res$bandwidth), extra)
cs_publish(list(
  method = "distribution.ksd",
  methodVersion = "1.0.0",
  title = "Kernel Stein discrepancy test",
  engine = cs_engine_info("stats", "nanoparquet"),
  n = n,
  summary = summary,
  apa = sprintf("n·KSD² = %s, %s", cs_fmt_num(stat), cs_fmt_p(p)),
  statistics = list(list(key = "statistic", label = "n·KSD²", value = stat), list(key = "p", label = "p", value = p, format = "p"),
                    list(key = "ksd2", label = "KSD² (unbiased)", value = res$ksd2)),
  tables = list(list(key = "fit", title = sprintf("Fitted %s model (maximum likelihood)", fam_label),
                     columns = list(list(key = "parameter", label = "Parameter", type = "string"), list(key = "value", label = "Estimate", type = "number")),
                     rows = rows)),
  effectSizes = list(),
  assumptions = assumptions,
  warnings = warnings,
  notes = list(sprintf("Inverse multiquadric kernel (1 + ‖x − y‖²/h²)^(−1/2) with h = %s, the median distance between rows on the fitted model's own scale (whitened for the normal; divided by the fitted scale otherwise); bootstrap on the shared seeded stream (seed %d), p = (1 + count) / (B + 1).",
                       format(signif(res$bandwidth, 4)), as.integer(seed))),
  values = values,
  charts = list(cs_chart("null", "null-distribution", "n·KSD² under the fitted model", list(
    x = cs_col("n·KSD²", nc$x), density = cs_col("Density", nc$density), observed = cs_col("Observed", rep(stat, length(nc$x)))),
    controls = list(alternative = "greater")))
))

Sources

  • Liu, Q., Lee, J. D., & Jordan, M. I. (2016). A kernelized Stein discrepancy for goodness-of-fit tests. Proceedings of ICML, 276–284.
  • Chwialkowski, K., Strathmann, H., & Gretton, A. (2016). A kernel test of goodness of fit. Proceedings of ICML, 2606–2615.
  • Gorham, J., & Mackey, L. (2017). Measuring sample quality with kernels. Proceedings of ICML, 1292–1301.
  • Minka, T. P. (2002). Estimating a gamma distribution. Microsoft Research technical note.

From the CodeSplash method registry · distribution.ksd v1.0.0.