Skip to content

Kernel tests of dependence and fit: HSIC and the Stein discrepancy

HSIC asks whether two sets of variables are independent, in any form; the kernel Stein discrepancy asks whether data follow a model known only up to a constant. Both depend on kernels and on calibration that respects the design.

Advanced ~14 min8 steps

What runs in CodeSplash

You will be able to

  • Read an HSIC test where the linear correlation is near zero
  • Calibrate HSIC by permuting one member of each pair, with blocks for sequences
  • Explain why the kernel Stein discrepancy needs only the model's score function
  • Choose between refitting and a fixed-parameter bootstrap for a fitted model

Read first

01

Dependence of any shape

Read

A correlation near zero rules out a straight-line relationship, not a relationship. HSICHSICA kernel measure of dependence between two sets of variables; zero under independence for Gaussian kernels. (the Hilbert–Schmidt independence criterion) compares the two variables' kernel similarity matrices KK and LL after centering:

HSIC^b=1n2tr⁡(KHLH),H=I−1n11⊤.\widehat{\mathrm{HSIC}}_b = \frac{1}{n^2}\operatorname{tr}(K H L H), \qquad H = I - \tfrac{1}{n}\mathbf 1 \mathbf 1^\top .

With characteristic kernels it is zero only under independence. In the reference's five-point example, where y=x2y = x^2, it is 0.112. Either side can be a whole set of variables: an embedding against a nuisance attribute, or one modality against another.

Reference · EVA017 · Runs in CodeSplashHSIC independence testTests dependence between representations, nuisance attributes, or paired modalities; extends baseline entry 86.
02

A curve that correlation misses

Explore
Test of independence: HSICRecorded · Python and R agreeRecorded 2026-11-25 · 22 values compared
R

HSIC = 0.019, p = .005, N = 118

HSIC
0.0194
p
.005
n
118

Effect size

  • HSIC 0.0194

Plots

y quadratic against xHow do two numeric variables move together?
View data
xy quadratic
0.52060.8319
−1.0800.1154
0.1392−1.026
−0.0847−0.6384
−0.66660.9804
−2.5166.778
−1.0201.064
0.11360.3246
−0.47380.4670
−0.40820.4326
−0.73040.6322
−0.22140.2123
−0.2258−0.6691
−2.5477.544
1.3471.722
0.61640.6260
0.2176−0.6333
−0.80470.4650
0.68970.8538
−0.32870.1813
−0.16470.1581
−1.3921.285
1.4662.395
0.0482−0.2532
1.9082.810
1.7313.307
0.05810.0112
0.64530.0495
1.7263.115
−0.5290−0.6496
0.16641.067
0.33280.2743
0.1824−0.0805
1.1650.7660
0.59350.5174
−0.89180.5918
0.57731.096
−0.82490.1289
−1.1572.008
0.77800.8816
−1.2040.9219
0.3067−0.0010
−0.83370.2404
1.4181.011
0.71181.461
−0.40250.9465
0.79940.7091
0.4265−0.5284
−1.1701.625
−0.2062−0.4512
−0.93061.165
0.44940.6359
−0.64480.5104
−0.23140.0189
−1.2362.067
−0.96101.459
0.13400.2288
−0.99910.9358
−0.14150.4886
0.16730.1283

First 60 of 118 rows.

Assumptions

  • Independent rows — Permutation and cross tests assume exchangeable rows; for time series or clustered data use block methods.
  • Ties — Ties are handled by midranks or exact distances.

The same variables under other dependence measures

MeasureValueSensitive to
Pearson r−0.0277Linear association
Spearman ρ−0.0254Monotonic association
ξ(x → y)0.4019y is a function of x (any shape)
ξ(y → x)0.0034x is a function of y (any shape)
Hoeffding 30·D0.0676Any departure from independence (ranks)
Distance correlation0.4592Any dependence (finite means)
Bias-corrected dCor0.1767Any dependence; ≈ 0 under independence
HSIC (median bandwidth)0.0194Any dependence (kernel)
  • 2 of 120 rows were left out because a value was missing.
  • HSIC; one-sided test of independence (199 Monte Carlo permutations (seed 42)).
The exact R script · R R version 4.5.1 (2025-06-13)
# Test for any dependence (ξ, Hoeffding, distance correlation, HSIC)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method correlation.dependence 1.0.1 · spec 1bbdf96f6284112d
# Dataset: f_dependence (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/f_dependence.parquet", col_select = c("x", "y quadratic")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("x", "y quadratic")]), , 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("x", "y quadratic"))  # infinite values stop the run (registry/errors.yaml)

# %% Dependence
x_cols <- c("x")
y_cols <- c("y quadratic")
measure <- "hsic"
calibration <- "auto"
n_perm <- as.integer(199)
bandwidth <- "median"
standardize <- TRUE
max_n <- as.integer(1000)
seed <- 42  # shared Wichmann-Hill streams: ties in x, permutations, subsample, split
univariate <- length(x_cols) == 1 && length(y_cols) == 1
if (measure %in% c("xi", "hoeffding") && !univariate) stop("ξ and Hoeffding's D compare one x variable with one y variable.")
if (length(intersect(x_cols, y_cols))) stop("A column cannot be both an x and a y variable.")
X <- as.matrix(df[x_cols]); storage.mode(X) <- "double"
Y <- as.matrix(df[y_cols]); storage.mode(Y) <- "double"
n <- nrow(df)
if (n < 10) cs_error("CS_E_TOO_FEW_ROWS", what = "A dependence test", min = 10, n = n)
for (col in c(x_cols, y_cols)) {
  # a constant variable cannot depend on anything (most measures are 0 / 0)
  if (length(unique(as.double(df[[col]]))) < 2) cs_error("CS_E_CONSTANT", column = col)
}
if (n > max_n) {  # n x n matrices: analyze a seeded random subsample
  idx <- sort(cs_rperm(cs_rng(seed + 2), n)[seq_len(max_n)])
  warnings <- c(warnings, sprintf("Distance and kernel measures used a random subsample of %d of %d rows (seed %d).", max_n, n, as.integer(seed)))
} else {
  idx <- seq_len(n)
}
Xs <- X[idx, , drop = FALSE]
Ys <- Y[idx, , drop = FALSE]
n_used <- if (measure != "xi") length(idx) else n
scaled <- function(M) {
  if (!standardize) return(M)
  sweep(sweep(M, 2, colMeans(M), "-"), 2, apply(M, 2, stats::sd), "/")
}

if (calibration == "auto") {
  calibration <- c(xi = "asymptotic", hoeffding = "permutation", dcor = "permutation", hsic = "permutation")[measure]
  if (is.na(calibration)) calibration <- "normal"
  calibration <- unname(calibration)
}
if (measure %in% c("cross_hsic", "cross_dcov")) {
  calibration <- "normal"
} else if (calibration == "asymptotic" && !(measure %in% c("xi", "dcor"))) {
  stop("Only ξ and distance correlation have an asymptotic test; choose permutations.")
}
z <- NULL; test_statistic <- NULL; dof <- NULL; count <- NULL
bw_x <- NULL; bw_y <- NULL
used_perm <- calibration == "permutation"
if (measure == "xi") {
  xv <- X[, 1]; yv <- Y[, 1]
  res <- cs_xi(xv, yv, seed)
  statistic <- res$statistic
  label <- "Chatterjee's ξ(x → y)"
  if (used_perm) {
    pr <- cs_perm_pvalue(function(pm) cs_xi(xv, yv[pm], seed)$statistic, statistic, n, n_perm, seed + 1)
    p <- pr$p; count <- pr$count
  } else {
    z <- res$z; p <- res$p
  }
} else if (measure == "hoeffding") {
  xv <- Xs[, 1]; yv <- Ys[, 1]
  statistic <- cs_hoeffding_d(xv, yv)
  label <- "Hoeffding's D"
  pr <- cs_perm_pvalue(function(pm) cs_hoeffding_d(xv, yv[pm]), statistic, length(xv), n_perm, seed + 1)
  p <- pr$p; count <- pr$count
} else if (measure == "dcor") {
  dc <- cs_dcov(scaled(Xs), scaled(Ys))
  if (used_perm) {
    A <- dc$A; B <- dc$B
    statistic <- dc$dcor; test_statistic <- dc$nv2
    label <- "Distance correlation"
    m <- nrow(A)
    pr <- cs_perm_pvalue(function(pm) m * mean(A * B[pm, pm]), test_statistic, m, n_perm, seed + 1)
    p <- pr$p; count <- pr$count
  } else {
    statistic <- dc$dcor_bc; test_statistic <- dc$t; dof <- dc$df; p <- dc$p_t
    label <- "Bias-corrected distance correlation"
  }
} else if (measure == "hsic") {
  Xh <- scaled(Xs); Yh <- scaled(Ys)
  if (bandwidth == "median") { bw_x <- cs_median_bandwidth(Xh); bw_y <- cs_median_bandwidth(Yh) } else { bw_x <- 1; bw_y <- 1 }
  hs <- cs_hsic(Xh, Yh, bw_x, bw_y)
  statistic <- hs$statistic
  label <- "HSIC"
  Kc <- hs$Kc; Lc <- hs$Lc
  m <- nrow(Kc)
  pr <- cs_perm_pvalue(function(pm) sum(Kc * Lc[pm, pm]) / (m - 1)^2, statistic, m, n_perm, seed + 1)
  p <- pr$p; count <- pr$count
} else {
  Xh <- scaled(Xs); Yh <- scaled(Ys)
  kernel <- if (measure == "cross_hsic") "gaussian" else "distance"
  if (kernel == "gaussian") {
    if (bandwidth == "median") { bw_x <- cs_median_bandwidth(Xh); bw_y <- cs_median_bandwidth(Yh) } else { bw_x <- 1; bw_y <- 1 }
  }
  res <- cs_cross_stat(Xh, Yh, kernel, if (is.null(bw_x)) 1 else bw_x, if (is.null(bw_y)) 1 else bw_y, seed + 3)
  statistic <- res$statistic; z <- res$z; p <- res$p
  label <- if (kernel == "gaussian") "Cross HSIC" else "Cross distance covariance"
  n_used <- 2 * res$half
}

# %% Profile: the same pair under other measures (estimates only)
xi_xy <- NULL; xi_yx <- NULL; hoeffding_30d <- NULL; pearson <- NULL; spearman <- NULL
Xp <- scaled(Xs); Yp <- scaled(Ys)
dcor_all <- cs_dcov(Xp, Yp)
dcor_v <- dcor_all$dcor; dcor_bc <- dcor_all$dcor_bc
rows <- list()
if (univariate) {
  xa <- Xs[, 1]; ya <- Ys[, 1]
  pearson <- stats::cor(xa, ya)
  spearman <- stats::cor(rank(xa), rank(ya))
  xi_xy <- cs_xi(xa, ya, seed)$statistic
  xi_yx <- cs_xi(ya, xa, seed)$statistic
  hoeffding_30d <- 30 * cs_hoeffding_d(xa, ya)
  rows <- list(list(measure = "Pearson r", value = pearson, detects = "Linear association"),
               list(measure = "Spearman ρ", value = spearman, detects = "Monotonic association"),
               list(measure = "ξ(x → y)", value = xi_xy, detects = "y is a function of x (any shape)"),
               list(measure = "ξ(y → x)", value = xi_yx, detects = "x is a function of y (any shape)"),
               list(measure = "Hoeffding 30·D", value = hoeffding_30d, detects = "Any departure from independence (ranks)"))
}
hsic_med <- cs_hsic(Xp, Yp, cs_median_bandwidth(Xp), cs_median_bandwidth(Yp))$statistic
rows <- c(rows, list(list(measure = "Distance correlation", value = dcor_v, detects = "Any dependence (finite means)"),
                     list(measure = "Bias-corrected dCor", value = dcor_bc, detects = "Any dependence; ≈ 0 under independence"),
                     list(measure = "HSIC (median bandwidth)", value = hsic_med, detects = "Any dependence (kernel)")))

# %% Result
alpha <- 0.050000000000000044
verdict <- if (p < alpha) sprintf("The variables are not independent (%s).", cs_fmt_p(p)) else sprintf("The data are compatible with independence (%s).", cs_fmt_p(p))
summary <- sprintf("%s between %s and %s was %.3f (n = %d). %s", label, paste(x_cols, collapse = ", "), paste(y_cols, collapse = ", "), statistic, as.integer(n_used), verdict)
how <- switch(calibration,
              asymptotic = if (measure == "xi") "asymptotic normal p-value" else "bias-corrected t-test",
              permutation = sprintf("%d Monte Carlo permutations (seed %d)", n_perm, as.integer(seed)),
              normal = "studentized cross statistic, standard normal p-value")
apa <- sprintf("%s = %.3f, %s, N = %d", label, statistic, cs_fmt_p(p), as.integer(n_used))
statistics_rows <- list(list(key = "statistic", label = label, value = statistic))
if (!is.null(test_statistic)) statistics_rows <- c(statistics_rows, list(list(key = "test_statistic", label = if (!is.null(dof)) "t" else "nV²", value = test_statistic)))
if (!is.null(z)) statistics_rows <- c(statistics_rows, list(list(key = "z", label = "z", value = z)))
statistics_rows <- c(statistics_rows, list(list(key = "p", label = "p", value = p, format = "p"), list(key = "n", label = "n", value = n_used)))
charts <- list()
if (univariate) {
  sel <- unique(round(seq(1, n, length.out = min(n, 5000))))
  charts <- list(cs_chart("scatter", "scatter", sprintf("%s against %s", y_cols[1], x_cols[1]), list(x = cs_col(x_cols[1], X[sel, 1]), y = cs_col(y_cols[1], Y[sel, 1]))))
}
cs_publish(list(
  method = "correlation.dependence",
  methodVersion = "1.0.1",
  title = sprintf("Test of independence: %s", label),
  engine = cs_engine_info("stats", "nanoparquet"),
  n = n_used,
  summary = summary,
  apa = apa,
  statistics = statistics_rows,
  tables = list(list(key = "profile", title = "The same variables under other dependence measures", columns = list(
    list(key = "measure", label = "Measure", type = "string"), list(key = "value", label = "Value", type = "number"),
    list(key = "detects", label = "Sensitive to", type = "string")), rows = rows)),
  effectSizes = list(list(key = "statistic", label = label, value = statistic, method = how)),
  assumptions = list(
    list(key = "independence", label = "Independent rows", status = "info",
         detail = "Permutation and cross tests assume exchangeable rows; for time series or clustered data use block methods."),
    list(key = "ties", label = "Ties", status = "info",
         detail = if (measure == "xi") "Ties in x are broken at random (seeded) for ξ." else "Ties are handled by midranks or exact distances.")
  ),
  charts = charts,
  warnings = warnings,
  notes = list(sprintf("%s; one-sided test of independence (%s).", label, how)),
  values = list(measure = measure, measure_label = label, statistic = statistic, z = z, test_statistic = test_statistic, df = dof,
                p = p, calibration = calibration, n = n, n_used = n_used, n_perm = if (used_perm) n_perm else NULL, count = count,
                xi_xy = xi_xy, xi_yx = xi_yx, dcor = dcor_v, dcor_bc = dcor_bc, hoeffding_30d = hoeffding_30d, hsic = hsic_med,
                pearson = pearson, spearman = spearman, bandwidth_x = bw_x, bandwidth_y = bw_y)
))
Python

HSIC = 0.019, p = .005, N = 118

HSIC
0.0194
p
.005
n
118

Effect size

  • HSIC 0.0194

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

Assumptions

  • Independent rows — Permutation and cross tests assume exchangeable rows; for time series or clustered data use block methods.
  • Ties — Ties are handled by midranks or exact distances.

The same variables under other dependence measures

MeasureValueSensitive to
Pearson r−0.0277Linear association
Spearman ρ−0.0254Monotonic association
ξ(x → y)0.4019y is a function of x (any shape)
ξ(y → x)0.0034x is a function of y (any shape)
Hoeffding 30·D0.0676Any departure from independence (ranks)
Distance correlation0.4592Any dependence (finite means)
Bias-corrected dCor0.1767Any dependence; ≈ 0 under independence
HSIC (median bandwidth)0.0194Any dependence (kernel)
  • 2 of 120 rows were left out because a value was missing.
  • HSIC; one-sided test of independence (199 Monte Carlo permutations (seed 42)).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Test for any dependence (ξ, Hoeffding, distance correlation, HSIC)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method correlation.dependence 1.0.1 · spec 1bbdf96f6284112d
# Dataset: f_dependence (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
from scipy import stats

import codesplash as cs
from codesplash.stats import dependence
from codesplash.stats.rng import Rng

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

# %% Dependence
x_cols = ["x"]
y_cols = ["y quadratic"]
measure = "hsic"
calibration = "auto"
n_perm = int(199)
bandwidth = "median"
standardize = True
max_n = int(1000)
seed = 42  # shared Wichmann–Hill streams: ties in x, permutations, subsample, split
univariate = len(x_cols) == 1 and len(y_cols) == 1
if measure in ("xi", "hoeffding") and not univariate:
    raise ValueError("ξ and Hoeffding's D compare one x variable with one y variable.")
if set(x_cols) & set(y_cols):
    raise ValueError("A column cannot be both an x and a y variable.")
X = df[x_cols].to_numpy(dtype=float)
Y = df[y_cols].to_numpy(dtype=float)
n = len(df)
if n < 10:
    cs.cs_error("CS_E_TOO_FEW_ROWS", what="A dependence test", min=10, n=n)
for col, v in zip(x_cols + y_cols, np.column_stack([X, Y]).T):
    if len(np.unique(v)) < 2:  # a constant variable cannot depend on anything (most measures are 0 / 0)
        cs.cs_error("CS_E_CONSTANT", column=col)
if n > max_n:  # n × n matrices: analyze a seeded random subsample
    idx = np.sort(Rng(seed + 2).permutation(n)[:max_n])
    warnings.append(f"Distance and kernel measures used a random subsample of {max_n} of {n} rows (seed {seed}).")
else:
    idx = np.arange(n)
Xs, Ys = X[idx], Y[idx]
n_used = len(idx) if measure != "xi" else n


def scaled(M):
    return (M - M.mean(axis=0)) / M.std(axis=0, ddof=1) if standardize else M


if calibration == "auto":
    calibration = {"xi": "asymptotic", "hoeffding": "permutation", "dcor": "permutation", "hsic": "permutation"}.get(measure, "normal")
if measure in ("cross_hsic", "cross_dcov"):
    calibration = "normal"
elif calibration == "asymptotic" and measure not in ("xi", "dcor"):
    raise ValueError("Only ξ and distance correlation have an asymptotic test; choose permutations.")
z = test_statistic = dof = count = None
bw_x = bw_y = None
used_perm = calibration == "permutation"
if measure == "xi":
    xv, yv = X[:, 0], Y[:, 0]
    res = dependence.xi(xv, yv, seed)
    statistic = res["statistic"]
    label = "Chatterjee's ξ(x → y)"
    if used_perm:
        pr = dependence.perm_pvalue(lambda pm: dependence.xi(xv, yv[pm], seed)["statistic"], statistic, n, n_perm, seed + 1)
        p, count = pr["p"], pr["count"]
    else:
        z, p = res["z"], res["p"]
elif measure == "hoeffding":
    xv, yv = Xs[:, 0], Ys[:, 0]
    statistic = dependence.hoeffding_d(xv, yv)
    label = "Hoeffding's D"
    pr = dependence.perm_pvalue(lambda pm: dependence.hoeffding_d(xv, yv[pm]), statistic, len(xv), n_perm, seed + 1)
    p, count = pr["p"], pr["count"]
elif measure == "dcor":
    dc = dependence.dcov(scaled(Xs), scaled(Ys))
    if used_perm:
        A, B = dc["A"], dc["B"]
        statistic, test_statistic = dc["dcor"], dc["nv2"]
        label = "Distance correlation"
        m = A.shape[0]
        pr = dependence.perm_pvalue(lambda pm: m * float(np.mean(A * B[np.ix_(pm, pm)])), test_statistic, m, n_perm, seed + 1)
        p, count = pr["p"], pr["count"]
    else:
        statistic, test_statistic, dof, p = dc["dcor_bc"], dc["t"], dc["df"], dc["p_t"]
        label = "Bias-corrected distance correlation"
elif measure == "hsic":
    Xh, Yh = scaled(Xs), scaled(Ys)
    bw_x, bw_y = (dependence.median_bandwidth(Xh), dependence.median_bandwidth(Yh)) if bandwidth == "median" else (1.0, 1.0)
    hs = dependence.hsic(Xh, Yh, bw_x, bw_y)
    statistic = hs["statistic"]
    label = "HSIC"
    Kc, Lc = hs["Kc"], hs["Lc"]
    m = Kc.shape[0]
    pr = dependence.perm_pvalue(lambda pm: float(np.sum(Kc * Lc[np.ix_(pm, pm)]) / (m - 1) ** 2), statistic, m, n_perm, seed + 1)
    p, count = pr["p"], pr["count"]
else:
    Xh, Yh = scaled(Xs), scaled(Ys)
    kernel = "gaussian" if measure == "cross_hsic" else "distance"
    if kernel == "gaussian":
        bw_x, bw_y = (dependence.median_bandwidth(Xh), dependence.median_bandwidth(Yh)) if bandwidth == "median" else (1.0, 1.0)
    res = dependence.cross_stat(Xh, Yh, kernel, bw_x or 1.0, bw_y or 1.0, seed + 3)
    statistic, z, p = res["statistic"], res["z"], res["p"]
    label = "Cross HSIC" if kernel == "gaussian" else "Cross distance covariance"
    n_used = 2 * res["half"]

# %% Profile: the same pair under other measures (estimates only)
xi_xy = xi_yx = hoeffding_30d = pearson = spearman = hsic_med = None
Xp, Yp = scaled(Xs), scaled(Ys)
dcor_all = dependence.dcov(Xp, Yp)
dcor_v, dcor_bc = dcor_all["dcor"], dcor_all["dcor_bc"]
rows = []
if univariate:
    xa, ya = Xs[:, 0], Ys[:, 0]
    pearson = float(np.corrcoef(xa, ya)[0, 1])
    spearman = float(np.corrcoef(stats.rankdata(xa), stats.rankdata(ya))[0, 1])
    xi_xy = dependence.xi(xa, ya, seed)["statistic"]
    xi_yx = dependence.xi(ya, xa, seed)["statistic"]
    hoeffding_30d = 30 * dependence.hoeffding_d(xa, ya)
    rows += [{"measure": "Pearson r", "value": pearson, "detects": "Linear association"},
             {"measure": "Spearman ρ", "value": spearman, "detects": "Monotonic association"},
             {"measure": "ξ(x → y)", "value": xi_xy, "detects": "y is a function of x (any shape)"},
             {"measure": "ξ(y → x)", "value": xi_yx, "detects": "x is a function of y (any shape)"},
             {"measure": "Hoeffding 30·D", "value": hoeffding_30d, "detects": "Any departure from independence (ranks)"}]
hsic_med = dependence.hsic(Xp, Yp, dependence.median_bandwidth(Xp), dependence.median_bandwidth(Yp))["statistic"]
rows += [{"measure": "Distance correlation", "value": dcor_v, "detects": "Any dependence (finite means)"},
         {"measure": "Bias-corrected dCor", "value": dcor_bc, "detects": "Any dependence; ≈ 0 under independence"},
         {"measure": "HSIC (median bandwidth)", "value": hsic_med, "detects": "Any dependence (kernel)"}]

# %% Result
alpha = 0.050000000000000044
names = lambda cols: ", ".join(cols)
verdict = (f"The variables are not independent ({cs.fmt_p(p)})." if p < alpha
           else f"The data are compatible with independence ({cs.fmt_p(p)}).")
summary = f"{label} between {names(x_cols)} and {names(y_cols)} was {statistic:.3f} (n = {n_used}). {verdict}"
how = {"asymptotic": "asymptotic normal p-value" if measure == "xi" else "bias-corrected t-test",
       "permutation": f"{n_perm} Monte Carlo permutations (seed {seed})", "normal": "studentized cross statistic, standard normal p-value"}[calibration]
apa = f"{label} = {statistic:.3f}, {cs.fmt_p(p)}, N = {n_used}"
statistics_rows = [{"key": "statistic", "label": label, "value": statistic}]
if test_statistic is not None:
    statistics_rows.append({"key": "test_statistic", "label": "t" if dof is not None else "nV²", "value": test_statistic})
if z is not None:
    statistics_rows.append({"key": "z", "label": "z", "value": z})
statistics_rows += [{"key": "p", "label": "p", "value": p, "format": "p"}, {"key": "n", "label": "n", "value": n_used}]
charts = []
if univariate:
    sel = np.unique(np.round(np.linspace(0, n - 1, min(n, 5000))).astype(int))
    charts.append(cs.chart("scatter", "scatter", f"{y_cols[0]} against {x_cols[0]}", {"x": cs.col(x_cols[0], X[sel, 0]), "y": cs.col(y_cols[0], Y[sel, 0])}))
cs.publish({
    "method": "correlation.dependence",
    "methodVersion": "1.0.1",
    "title": f"Test of independence: {label}",
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": n_used,
    "summary": summary,
    "apa": apa,
    "statistics": statistics_rows,
    "tables": [{"key": "profile", "title": "The same variables under other dependence measures", "columns": [
        {"key": "measure", "label": "Measure", "type": "string"}, {"key": "value", "label": "Value", "type": "number"},
        {"key": "detects", "label": "Sensitive to", "type": "string"}], "rows": rows}],
    "effectSizes": [{"key": "statistic", "label": label, "value": statistic, "method": how}],
    "assumptions": [
        {"key": "independence", "label": "Independent rows", "status": "info",
         "detail": "Permutation and cross tests assume exchangeable rows; for time series or clustered data use block methods."},
        {"key": "ties", "label": "Ties", "status": "info",
         "detail": "Ties in x are broken at random (seeded) for ξ." if measure == "xi" else "Ties are handled by midranks or exact distances."},
    ],
    "charts": charts,
    "warnings": warnings,
    "notes": [f"{label}; one-sided test of independence ({how})."],
    "values": {"measure": measure, "measure_label": label, "statistic": statistic, "z": z, "test_statistic": test_statistic, "df": dof,
               "p": p, "calibration": calibration, "n": n, "n_used": n_used, "n_perm": n_perm if used_perm else None, "count": count,
               "xi_xy": xi_xy, "xi_yx": xi_yx, "dcor": dcor_v, "dcor_bc": dcor_bc, "hoeffding_30d": hoeffding_30d, "hsic": hsic_med,
               "pearson": pearson, "spearman": spearman, "bandwidth_x": bw_x, "bandwidth_y": bw_y},
})

Here yy is a noisy quadratic in xx. Pearson's r is −0.028, essentially zero. HSIC is 0.0194, and 199 permutations give p = .005: the variables are not independent.

The permutation shuffles yy against xx, breaking the pairs. That is valid when the pairs are independent units. For time series, shuffle blocks, or the test confuses shared trends with dependence.

03

What independence doesn't prove

Read

A common use is an audit: does an embedding still carry a sensitive attribute? A non-significant HSIC says this test, with these kernels and this many rows, found no dependence on that one attribute. It doesn't show the embedding is fair or disentangled: other attributes, proxies and combinations remain.

Testing many layers or many attributes is a family; adjust it. Small samples and badly chosen bandwidths cost power, so fix the kernels before looking.

04

Fit without the normalizing constant

Read

Many models give a density only up to a constant: energy-based models, unnormalized posteriors. The kernel Stein discrepancyKernel Stein discrepancy (KSD)A distance between the data and a model that needs only the model's score function, so it works for several variables at once. needs only the score sp(x)=∇xlog⁡p(x)s_p(x) = \nabla_x \log p(x), where the constant drops out. It averages a Stein kernel built from the score and a base kernel; that average is zero exactly when the data follow pp, under regularity conditions.

In the reference's three-point example against a standard normal, the unbiased estimate is −0.765. Negative values happen, and a raw KSD isn't a p-value: its null distribution needs a bootstrap.

Reference · EVA020 · Runs in CodeSplashKernel Stein discrepancy goodness-of-fit testTests a target density using its score function without requiring its normalizing constant.
05

A fitted model, two calibrations

Explore
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).
The exact R script · R 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")))
))
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).
The exact Python script · Python 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"})],
})

Is daily wind speed normal? The scaled statistic is 1.59 with p = .200, from 99 parametric bootstrap samples, each refitted. Refitting in every bootstrap sample builds the parameter estimation into the reference, as in Lilliefors' fix for the fitted-normal KS test.

The wild bootstrap instead holds the fitted parameters fixed. For a lognormal model of ozone it gives p = .925. When the parameters came from the same data, a fixed-parameter calibration ignores that fitting; refit when you can.

Drag a point into the tail below and watch the discrepancy grow. Then switch to the wild bootstrap and compare the p-values.

BExplorable · Kernel Stein discrepancy goodness-of-fit test

Do the data follow a model you can write down only up to its normalizing constant?

Data

Simulated data follow the settings below. The recorded examples are the data the engines ran; the settings don't change them.

60
0.60

0 under the model; positive values stretch the right tail.

1.00

1 under the model; smaller values give heavier tails.

Model

The model the data are tested against, fitted by maximum likelihood.

Bootstrap

Parametric: simulate from the fitted model and refit each sample. Wild: random sign flips of the Stein kernel with the fit held fixed (faster, but conservative when the fit comes from the same data).

199

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

0.050

Your data

Drag a point or use ↑/↓ to change it
x · n = 60 · mean 12.26

If H₀ were true

n·KSD² = 4.66
  1. The reference: how n·KSD² varies across samples when H₀ is true, 199 parametric bootstrap samples, each refitted (parametric bootstrap: samples from the fitted model, each refitted (seed 42)).
  2. Your statistic, from the data above.
  3. The p-value: the area at least as extreme as yours (p = .005).
  4. The hatched rejection region at α = .050: statistics landing here reject H₀.

The formula

n KSD^V2=1n∑i,jup(zi,zj),KSD^U2=1n(n−1)∑i≠jup(zi,zj)n\,\widehat{\mathrm{KSD}}^2_V = \dfrac{1}{n}\sum_{i,j} u_p(z_i, z_j),\qquad \widehat{\mathrm{KSD}}^2_U = \dfrac{1}{n(n-1)}\sum_{i\ne j} u_p(z_i, z_j)

With your numbers

n KSD^V2=4.66,KSD^U2=0.04, h=0.94, n=60, B=199n\,\widehat{\mathrm{KSD}}^2_V = 4.66,\qquad \widehat{\mathrm{KSD}}^2_U = 0.04,\ h = 0.94,\ n = 60,\ B = 199
up(z,z′)u_p(z, z')
the Stein kernel: built from the model's score ∇log p and an inverse multiquadric kernel, so the constant cancels
zz
the data on the fitted model's own scale
hh
the kernel bandwidth: the median distance between rows

The verdict

n·KSD² = 4.66, p = .005

p ≤ α = .050: reject H₀

The statistic is near zero when the data follow the model. Its null is a bootstrap: the parametric one simulates from the fitted model and refits every sample; the wild bootstrap flips signs with the fit held fixed, which is conservative when the parameters were fitted to the same data. Drag a point into the tail and watch the discrepancy grow. The lesson's example with 99 bootstrap samples gives the recorded result.

Statistic
4.658
p-value
0.0050
Kernel Stein discrepancy goodness-of-fit test on x: n = 60: n·KSD² = 4.66, p = .005. The p-value is below α = .050, so the data are hard to reconcile with H0.

Kernel Stein discrepancy goodness-of-fit test on x: n = 60: n·KSD² = 4.66, p = .005. The p-value is below α = .050, so the data are hard to reconcile with H₀.

06

In CodeSplash

In the app

In Analyze, Test for any dependence offers HSIC and cross-HSIC beside distance correlation, Chatterjee's ξ and Hoeffding's D, with permutation or normal calibration. Kernel Stein discrepancy goodness-of-fit test checks normal, multivariate normal, lognormal and gamma models, calibrated by a refitting parametric bootstrap or a wild bootstrap. It is Experimental.

07

Check: HSIC and KSD

Checkpoint

Check yourself

Pearson's r is near 0 and an HSIC test rejects independence. How can both be right?

Show the answer

Answer: b

Zero correlation rules out a linear trend only. A symmetric curve gives r ≈ 0 and strong dependence.

Check yourself

How is an HSIC test calibrated for independent pairs?

Show the answer

Answer: a

Under independence, any pairing is as likely as the observed one. For time series, shuffle blocks instead.

Check yourself

An HSIC audit finds no dependence between an embedding and a recorded gender column. What does that show?

Show the answer

Answer: b

Independence from one measured attribute isn't fairness. It is one check with limited power.

Check yourself

Why can the kernel Stein discrepancy test a model whose density is known only up to a constant?

Show the answer

Answer: b

∇log⁡(c f(x))=∇log⁡f(x)\nabla \log (c\,f(x)) = \nabla \log f(x). The score needs no normalizing constant.

Check yourself

A KSD estimate is −0.003. What should you report?

Show the answer

Answer: c

A raw discrepancy isn't calibrated. The bootstrap gives the reference distribution under the model.

Check yourself

A model's parameters were estimated from the same data being tested. Which bootstrap matches the analysis?

Show the answer

Answer: a

The reference must repeat every step the real analysis took, fitting included, or the test is miscalibrated.

08

Recap

Recap
  • HSIC detects dependence of any shape between two sets of variables; permute pairs (or blocks for sequences).
  • Independence from one attribute isn't fairness; many layers or attributes are a family.
  • The kernel Stein discrepancy needs only the score, so unnormalized models can be tested; a raw value isn't a p-value.
  • When parameters were fitted on the data, refit inside the bootstrap.

Concepts in this lesson