Skip to content

Are two samples the same? MMD, energy and classifier tests

Three ways to ask whether two sets of rows, embeddings or generated records come from one distribution. Each is calibrated by permutation or a held-out design, each depends on its representation, and none proves the two are the same.

Advanced ~15 min11 steps

What runs in CodeSplash

You will be able to

  • Compute and read the unbiased MMD² and the energy statistic
  • Run a classifier two-sample test with training, tuning and scoring kept apart
  • Calibrate each test by a permutation that matches the design
  • Say what failing to reject does and doesn't show

Read first

01

The question

Read

Real records against generated ones, last month's embeddings against this month's, one site's patients against another's: are the two samples draws from the same distribution? Comparing means one column at a time misses changes in spread, shape and relationships between columns.

The three tests here compare whole distributions. Their nulls are the same, P=QP = Q. They differ in what kind of difference they notice best and in how they are calibrated.

02

Maximum mean discrepancy

Read

MMDMaximum mean discrepancyThe distance between two distributions' average kernel embeddings; zero when they are equal. compares the average kernel similarity within each sample with the average across samples:

MMD^u2=∑i≠jk(xi,xj)m(m−1)+∑i≠jk(yi,yj)n(n−1)−2∑i,jk(xi,yj)mn.\widehat{\mathrm{MMD}}^2_u = \frac{\sum_{i \ne j} k(x_i, x_j)}{m(m-1)} + \frac{\sum_{i \ne j} k(y_i, y_j)}{n(n-1)} - \frac{2\sum_{i,j} k(x_i, y_j)}{mn}.

With a characteristic kernel such as the Gaussian, it is zero only when the distributions are equal. The unbiased estimate can be negative. In the reference's three-against-three example it is 0.312. The bandwidth and the feature representation are hyperparameters: fix them before testing, or include their choice in the calibration.

Reference · EVA016 · Runs in CodeSplashMaximum mean discrepancy two-sample testTests equality of distributions using a kernel-space discrepancy; this extends baseline entry 169 to learned representations and generative evaluation.
03

The energy statistic

Read

The energy distanceEnergy distanceTwice the mean distance between samples minus the mean distances within each; zero only when the distributions are equal. uses plain distances:

E(P,Q)=2 E∥X−Y∥−E∥X−X′∥−E∥Y−Y′∥.\mathcal E(P, Q) = 2\,\mathbb E\lVert X - Y\rVert - \mathbb E\lVert X - X'\rVert - \mathbb E\lVert Y - Y'\rVert .

It needs finite first moments and no bandwidth. In the reference's example it is 2.222. V-statistic and U-statistic versions differ slightly in small samples; say which one you report.

Both tests are calibrated the same way: shuffle the group labels many times, recompute the statistic, and count how often it reaches the observed value. That needs independent, exchangeable units. Resample whole subjects or recordings, never correlated frames.

Reference · EVA018 · Runs in CodeSplashEnergy two-sample testCompares within- and between-sample distances; extends baseline entry 168 to embeddings and model outputs.
04

Two tests, one dataset

Explore
Maximum mean discrepancy testRecorded · Python and R agreeRecorded 2026-11-21 · 14 values compared
R

Maximum mean discrepancy test, MMD²ᵤ = 0.08, p = .005

MMD²ᵤ
0.0784
p
.005

Plots

Principal coordinates of the rows by groupDo the groups separate in the dissimilarity space, and do they differ in where they sit or in how spread out they are?
View data
groupPCoA 1 (42.4%)PCoA 2 (32.5%)
g11.880−0.0590
g1−1.6120.8910
g11.8520.2849
g11.1820.9049
g10.65580.7322
g1−1.7232.557
g1−0.35371.066
g10.87331.373
g1−1.190−0.0974
g1−1.994−0.0357
g12.3631.065
g1−0.91710.3980
g11.1050.4423
g1−0.87310.2165
g11.6093.095
g10.7412−0.9501
g11.794−0.2277
g11.2020.0360
g10.81361.379
g10.6387−0.6940
g1−0.69970.1242
g10.44240.5991
g10.28181.578
g11.449−0.7876
g10.5212−0.4453
g10.2217−1.750
g12.778−1.161
g1−1.653−0.0826
g11.813−0.1413
g11.168−0.9665
g10.91671.327
g11.1300.4960
g1−0.41980.8517
g10.3646−0.3902
g10.48880.4014
g11.132−0.9397
g1−0.82840.1889
g1−1.2680.8131
g1−1.258−1.108
g10.39731.515
g20.3005−1.929
g22.515−1.324
g2−0.27580.0576
g20.8521−0.7303
g2−0.25711.649
g2−1.075−0.8621
g21.3360.2787
g20.19760.4148
g2−1.410−0.4676
g2−0.5506−1.262
g20.4851−0.0900
g2−0.9148−2.405
g2−0.6339−0.7328
g2−1.1240.1816
g20.1908−0.2489
g2−1.143−0.1104
g20.49091.963
g2−0.9839−0.6186
g2−0.5787−1.013
g2−1.271−1.232

First 60 of 90 rows.

Assumptions

  • Exchangeable rows — Under the null the group labels are exchangeable; rows must be independent.
  • Comparable scales — Distances use the raw values, so variables with large units dominate; standardize when units differ.

Groups

groupn
g140
g250
  • Euclidean distances of the variables; p from 199 label permutations on the shared seeded stream (seed 42).
The exact R script · R R version 4.5.1 (2025-06-13)
# Multivariate tests of equal distributions (energy, MMD, DISCO, classifier)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method multivariate.distribution_test 1.1.0 · spec d0c86492e7c712ac
# Dataset: mv_guide (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/mv_guide.parquet", col_select = c("y1", "y2", "y3", "group")))
n_input <- nrow(df)
df[["group"]] <- factor(df[["group"]], levels = c("g1", "g2"))  # stored level order
df <- df[stats::complete.cases(df[c("y1", "y2", "y3", "group")]), , 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("y1", "y2", "y3", "group"))  # infinite values stop the run (registry/errors.yaml)

# %% Test
# Do the groups come from the same multivariate distribution? Energy distance (Szekely & Rizzo 2004),
# maximum mean discrepancy with a Gaussian kernel (Gretton et al. 2012) or DISCO (Rizzo & Szekely 2010)
# on Euclidean distances, each with a label-permutation p from the shared Wichmann-Hill stream.
variables <- c("y1", "y2", "y3")
g <- "group"
test <- "mmd"  # energy | mmd | disco | c2st
transform_kind <- "none"
seed <- 42
n_perm <- as.integer(199)
alpha <- 0.05
levels_g <- levels(df[[g]])
codes <- as.integer(df[[g]]) - 1L
k <- length(levels_g)
if (k < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = g, min = 2, k = k)
if (test == "mmd" && k != 2) stop(sprintf("The MMD test compares exactly two groups; %s has %d. Use the energy test or DISCO for more.", g, k))
if (test == "c2st" && k != 2) cs_error("CS_E_GROUP_COUNT", column = g, expected = 2, k = k)
Y <- cs_mvd_transform(as.matrix(df[variables]), transform_kind)
n <- nrow(Y)
if (n > 5000) stop(sprintf("These tests use an n × n distance matrix; %d rows is too many (at most 5000).", n))
D <- cs_mvd_distance(Y, "euclidean")
group_n <- tabulate(codes + 1L, nbins = k)
extra <- list()
if (test == "energy") {
  res <- cs_mvd_energy_test(D, codes, k, n_perm, seed)
  stat <- res$statistic
  symbol <- "E"
  label <- "Energy test of equal distributions"
} else if (test == "c2st") {
  # Classifier two-sample test (Stage 12.7): fit on one half, score the other, AUC against a label permutation null.
  if (min(group_n) < 4) cs_error("CS_E_TOO_FEW_ROWS", what = "Each group in the classifier two-sample test", min = 4, n = min(group_n))
  classifier <- "logistic"  # logistic | knn
  res <- cs_c2st(Y, codes, classifier, 0.5, as.integer(10), n_perm, seed)
  stat <- res$auc
  symbol <- "AUC"
  label <- "Classifier two-sample test (held-out AUC)"
  extra <- list(classifier = classifier, c2st_accuracy = res$accuracy, baseline_accuracy = res$baseline, n_train = res$n_train, n_test = res$n_test)
} else if (test == "mmd") {
  sigma <- cs_mvd_mmd_bandwidth(D, "median", 1)
  res <- cs_mvd_mmd_test(D, codes, sigma, n_perm, seed)
  stat <- res$statistic
  symbol <- "MMD²ᵤ"
  label <- "Maximum mean discrepancy test"
  extra <- list(sigma = sigma)
} else {
  exponent <- 1
  res <- cs_mvd_disco(D, codes, k, exponent, n_perm, seed)
  stat <- res$f
  symbol <- "F"
  label <- "DISCO (distance components)"
  extra <- list(between = res$between, within = res$within, total = res$total, df1 = res$df1, df2 = res$df2, exponent = exponent)
}
p <- res$p

# %% Assumptions
scaled <- transform_kind %in% c("standardize", "range")
assumptions <- list(
  list(key = "exchangeable", label = "Exchangeable rows", status = "info",
       detail = "Under the null the group labels are exchangeable; rows must be independent."),
  list(key = "scaling", label = "Comparable scales", status = if (scaled || length(variables) == 1) "pass" else "info",
       detail = if (scaled) paste0("Variables were ", if (transform_kind == "standardize") "standardized" else "range-scaled", " before the distances.") else
         "Distances use the raw values, so variables with large units dominate; standardize when units differ.")
)

# %% Result
what <- if (p < alpha) "differ in distribution (location, spread or shape)" else "show no evidence of differing in distribution"
summary <- sprintf("%s on %s: the %d groups of %s %s (%s = %s, %s, %d permutations).", label, paste(variables, collapse = ", "), k, g, what,
                   symbol, format(signif(stat, 4)), cs_fmt_p(p), n_perm)
if (test == "mmd") summary <- paste(summary, sprintf("Gaussian kernel bandwidth σ = %s.", format(signif(extra$sigma, 4))))
if (test == "c2st") summary <- paste(summary, sprintf("A %s fitted on %d rows told the groups apart on %d new rows with AUC %.3f (0.5 = no better than chance) and accuracy %.1f%% (always guessing the larger group: %.1f%%).",
  if (extra$classifier == "logistic") "logistic regression" else "nearest-neighbor classifier", as.integer(extra$n_train), as.integer(extra$n_test), stat,
  100 * extra$c2st_accuracy, 100 * extra$baseline_accuracy))
values <- list(test = test, statistic = stat, p = p, k = k, n = n, n_perm = n_perm, sigma = NULL, between = NULL, within = NULL,
               total = NULL, df1 = NULL, df2 = NULL, exponent = NULL)
for (key in names(extra)) values[[key]] <- extra[[key]]
values$missing_share <- if (n_input > 0) n_dropped / n_input else 0
tables <- list(list(key = "groups", title = "Groups",
                    columns = list(list(key = "group", label = g, type = "string"), list(key = "n", label = "n", type = "integer")),
                    rows = data.frame(group = levels_g, n = as.integer(group_n))))
if (test == "disco") {
  tables <- c(list(list(key = "components", title = sprintf("Distance components (exponent %s)", format(extra$exponent)),
    columns = list(list(key = "source", label = "Source", type = "string"), list(key = "df", label = "df", type = "integer"),
                   list(key = "dist", label = "Sum of distances", type = "number"), list(key = "mean", label = "Mean", type = "number"),
                   list(key = "f", label = "F", type = "number"), list(key = "p", label = "p", type = "pvalue")),
    rows = list(list(source = g, df = extra$df1, dist = extra$between, mean = extra$between / extra$df1, f = stat, p = p),
                list(source = "Within", df = extra$df2, dist = extra$within, mean = extra$within / extra$df2, f = NULL, p = NULL),
                list(source = "Total", df = n - 1, dist = extra$total, mean = NULL, f = NULL, p = NULL)))), tables)
}
pc <- cs_mvd_pcoa(D)
V <- pc$vectors
ex <- pc$explained
ax1 <- if (ncol(V) > 0) V[, 1] else rep(0, n)
ax2 <- if (ncol(V) > 1) V[, 2] else rep(0, n)
cs_publish(list(
  method = "multivariate.distribution_test",
  methodVersion = "1.1.0",
  title = label,
  engine = cs_engine_info("stats", "nanoparquet"),
  n = n,
  summary = summary,
  apa = sprintf("%s, %s = %s, %s", label, symbol, cs_fmt_num(stat), cs_fmt_p(p)),
  statistics = list(list(key = "statistic", label = symbol, value = stat), list(key = "p", label = "p", value = p, format = "p")),
  tables = tables,
  effectSizes = list(),
  assumptions = assumptions,
  warnings = warnings,
  notes = list(if (test != "c2st") sprintf("Euclidean distances of the %svariables; p from %d label permutations on the shared seeded stream (seed %d).",
                       if (transform_kind == "standardize") "standardized " else "", n_perm, as.integer(seed)) else
               sprintf("Rows split by group on the shared seeded stream (seed %d): %d to fit, %d to test; variables standardized with the fitting half. p: the test half's labels permuted %d times with the classifier fixed (one-sided: AUC above chance).",
                       as.integer(seed), as.integer(extra$n_train), as.integer(extra$n_test), n_perm)),
  values = values,
  charts = c(list(cs_chart("ordination", "pcoa-centroids", sprintf("Principal coordinates of the rows by %s", g), list(
    x = cs_col(if (ncol(V) > 0) sprintf("PCoA 1 (%.1f%%)", 100 * ex[1]) else "PCoA 1", ax1),
    y = cs_col(if (ncol(V) > 1) sprintf("PCoA 2 (%.1f%%)", 100 * ex[2]) else "PCoA 2", ax2),
    group = cs_col(g, as.character(df[[g]]), levels = levels_g)), controls = list(center = "centroid", spokes = FALSE, hulls = TRUE))),
    if (test == "c2st") {
      nc <- cs_signflip_null_curve(res$null)
      list(cs_chart("null", "null-distribution", "Held-out AUC when the test half's labels are shuffled", list(
        x = cs_col("AUC", nc$x), density = cs_col("Density", nc$density), observed = cs_col("Observed", rep(stat, length(nc$x)))),
        controls = list(alternative = "greater")))
    } else list())
))
Python

Maximum mean discrepancy test, MMD²ᵤ = 0.08, p = .005

MMD²ᵤ
0.0784
p
.005

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

Assumptions

  • Exchangeable rows — Under the null the group labels are exchangeable; rows must be independent.
  • Comparable scales — Distances use the raw values, so variables with large units dominate; standardize when units differ.

Groups

groupn
g140
g250
  • Euclidean distances of the variables; p from 199 label permutations on the shared seeded stream (seed 42).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Multivariate tests of equal distributions (energy, MMD, DISCO, classifier)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method multivariate.distribution_test 1.1.0 · spec d0c86492e7c712ac
# Dataset: mv_guide (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.stats import mvdist

# %% Data
df = pd.read_parquet("tests/parity/fixtures/mv_guide.parquet", columns=["y1", "y2", "y3", "group"])
n_input = len(df)
df["group"] = pd.Categorical(df["group"], categories=["g1", "g2"])  # stored level order
df = df.dropna(subset=["y1", "y2", "y3", "group"])  # listwise deletion over the analysis columns
df["group"] = df["group"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
    warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
    cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["y1", "y2", "y3", "group"])  # infinite values stop the run (registry/errors.yaml)

# %% Test
# Do the groups come from the same multivariate distribution? Energy distance (Székely & Rizzo 2004),
# maximum mean discrepancy with a Gaussian kernel (Gretton et al. 2012) or DISCO (Rizzo & Székely 2010)
# on Euclidean distances, each with a label-permutation p from the shared Wichmann–Hill stream.
variables = ["y1", "y2", "y3"]
g = "group"
test = "mmd"  # energy | mmd | disco | c2st
transform_kind = "none"
seed = 42
n_perm = int(199)
alpha = 0.05
levels = [str(lv) for lv in df[g].cat.categories]
codes = df[g].cat.codes.to_numpy().astype(int)
k = len(levels)
if k < 2:
    cs.cs_error("CS_E_TOO_FEW_GROUPS", column=g, min=2, k=k)
if test == "mmd" and k != 2:
    raise ValueError(f"The MMD test compares exactly two groups; {g} has {k}. Use the energy test or DISCO for more.")
if test == "c2st" and k != 2:
    cs.cs_error("CS_E_GROUP_COUNT", column=g, expected=2, k=k)
Y = mvdist.transform(df[variables].to_numpy(dtype=float), transform_kind)
n = int(Y.shape[0])
if n > 5000:
    raise ValueError(f"These tests use an n × n distance matrix; {n} rows is too many (at most 5000).")
D = mvdist.distance(Y, "euclidean")
group_n = np.bincount(codes, minlength=k)
if test == "energy":
    res = mvdist.energy_test(D, codes, k, n_perm, seed)
    stat, symbol, label = res["statistic"], "E", "Energy test of equal distributions"
    extra = {}
elif test == "c2st":
    # Classifier two-sample test (Stage 12.7): fit on one half, score the other, AUC against a label permutation null.
    from codesplash.stats import c2st as c2
    if int(group_n.min()) < 4:
        cs.cs_error("CS_E_TOO_FEW_ROWS", what="Each group in the classifier two-sample test", min=4, n=int(group_n.min()))
    classifier = "logistic"  # logistic | knn
    res = c2.c2st(Y, codes, classifier, 0.5, int(10), n_perm, seed)
    stat, symbol, label = res["auc"], "AUC", "Classifier two-sample test (held-out AUC)"
    extra = {"classifier": classifier, "c2st_accuracy": res["accuracy"], "baseline_accuracy": res["baseline"],
             "n_train": res["n_train"], "n_test": res["n_test"]}
elif test == "mmd":
    sigma = mvdist.mmd_bandwidth(D, "median", 1)
    res = mvdist.mmd_test(D, codes, sigma, n_perm, seed)
    stat, symbol, label = res["statistic"], "MMD²ᵤ", "Maximum mean discrepancy test"
    extra = {"sigma": sigma}
else:
    exponent = 1
    res = mvdist.disco(D, codes, k, exponent, n_perm, seed)
    stat, symbol, label = res["f"], "F", "DISCO (distance components)"
    extra = {"between": res["between"], "within": res["within"], "total": res["total"], "df1": res["df1"], "df2": res["df2"], "exponent": exponent}
p = res["p"]

# %% Assumptions
assumptions = [
    {"key": "exchangeable", "label": "Exchangeable rows", "status": "info",
     "detail": "Under the null the group labels are exchangeable; rows must be independent."},
    {"key": "scaling", "label": "Comparable scales", "status": "pass" if transform_kind in ("standardize", "range") or len(variables) == 1 else "info",
     "detail": ("Variables were " + ("standardized" if transform_kind == "standardize" else "range-scaled") + " before the distances."
                if transform_kind in ("standardize", "range") else
                "Distances use the raw values, so variables with large units dominate; standardize when units differ.")},
]

# %% Result
what = "differ in distribution (location, spread or shape)" if p < alpha else "show no evidence of differing in distribution"
summary = (f"{label} on {', '.join(variables)}: the {k} groups of {g} {what} ({symbol} = {stat:.4g}, {cs.fmt_p(p)}, {n_perm} permutations).")
if test == "mmd":
    summary += f" Gaussian kernel bandwidth σ = {extra['sigma']:.4g}."
if test == "c2st":
    summary += (f" A {'logistic regression' if extra['classifier'] == 'logistic' else 'nearest-neighbor classifier'} fitted on {extra['n_train']} rows"
                f" told the groups apart on {extra['n_test']} new rows with AUC {stat:.3f} (0.5 = no better than chance) and accuracy {extra['c2st_accuracy']:.1%}"
                f" (always guessing the larger group: {extra['baseline_accuracy']:.1%}).")
values = {"test": test, "statistic": stat, "p": p, "k": k, "n": n, "n_perm": n_perm,
          **{key: None for key in ("sigma", "between", "within", "total", "df1", "df2", "exponent")}, **extra}
values["missing_share"] = n_dropped / n_input if n_input else 0.0
tables = [{"key": "groups", "title": "Groups",
           "columns": [{"key": "group", "label": g, "type": "string"}, {"key": "n", "label": "n", "type": "integer"}],
           "rows": [{"group": lv, "n": int(m)} for lv, m in zip(levels, group_n)]}]
if test == "disco":
    tables.insert(0, {"key": "components", "title": f"Distance components (exponent {extra['exponent']:g})",
                      "columns": [{"key": "source", "label": "Source", "type": "string"}, {"key": "df", "label": "df", "type": "integer"},
                                  {"key": "dist", "label": "Sum of distances", "type": "number"}, {"key": "mean", "label": "Mean", "type": "number"},
                                  {"key": "f", "label": "F", "type": "number"}, {"key": "p", "label": "p", "type": "pvalue"}],
                      "rows": [{"source": g, "df": extra["df1"], "dist": extra["between"], "mean": extra["between"] / extra["df1"], "f": stat, "p": p},
                               {"source": "Within", "df": extra["df2"], "dist": extra["within"], "mean": extra["within"] / extra["df2"], "f": None, "p": None},
                               {"source": "Total", "df": n - 1, "dist": extra["total"], "mean": None, "f": None, "p": None}]})
pc = mvdist.pcoa(D)
V, ex = pc["vectors"], pc["explained"]
ax1 = V[:, 0] if V.shape[1] else np.zeros(n)
ax2 = V[:, 1] if V.shape[1] > 1 else np.zeros(n)
cs.publish({
    "method": "multivariate.distribution_test",
    "methodVersion": "1.1.0",
    "title": label,
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": n,
    "summary": summary,
    "apa": f"{label}, {symbol} = {cs.fmt_num(stat)}, {cs.fmt_p(p)}",
    "statistics": [{"key": "statistic", "label": symbol, "value": stat}, {"key": "p", "label": "p", "value": p, "format": "p"}],
    "tables": tables,
    "effectSizes": [],
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": [f"Euclidean distances of the {('standardized ' if transform_kind == 'standardize' else '')}variables; p from {n_perm} label permutations on the shared seeded stream (seed {seed})."
              if test != "c2st" else
              f"Rows split by group on the shared seeded stream (seed {seed}): {extra['n_train']} to fit, {extra['n_test']} to test; variables standardized with the fitting half. "
              f"p: the test half's labels permuted {n_perm} times with the classifier fixed (one-sided: AUC above chance)."],
    "values": values,
    "charts": [cs.chart("ordination", "pcoa-centroids", f"Principal coordinates of the rows by {g}", {
        "x": cs.col(f"PCoA 1 ({100 * ex[0]:.1f}%)" if V.shape[1] else "PCoA 1", ax1),
        "y": cs.col(f"PCoA 2 ({100 * ex[1]:.1f}%)" if V.shape[1] > 1 else "PCoA 2", ax2),
        "group": cs.col(g, df[g].astype(str).to_numpy(), levels=levels)}, controls={"center": "centroid", "spokes": False, "hulls": True})]
        + ([cs.chart("null", "null-distribution", "Held-out AUC when the test half's labels are shuffled", {
            "x": cs.col("AUC", c2.null_curve(res["null"])[0]), "density": cs.col("Density", c2.null_curve(res["null"])[1]),
            "observed": cs.col("Observed", np.full(40, stat))}, controls={"alternative": "greater"})] if test == "c2st" else []),
})

Two groups of three variables. MMD² is 0.0784 with a median-heuristic bandwidth of 2.18, and p = .005 from 199 permutations. The energy test on the same data gives E = 9.64, p = .005.

With 199 permutations the smallest possible p is 1/2001/200: more permutations sharpen small p-values, not the evidence.

05

The classifier two-sample test

Read

Train a classifier to tell the samples apart. If it does better than chance on rows it never saw, the distributions differ. The classifier two-sample testClassifier two-sample testIf a classifier can tell new rows from training rows, the data has shifted; its AUC measures by how much. needs three things kept apart: split before any preprocessing, fit and tune on one part, score once on the other.

The exact binomial reference holds when each held-out label is an independent fair coin. Forcing equal class counts is a different design; then use a permutation of the held-out labels with the classifier fixed. In the reference's example, 68 correct out of 100 gives a one-sided binomial p of 0.00020.

Reference · EVA019 · Partly runs in CodeSplashClassifier two-sample testUses held-out discrimination between samples as evidence that their distributions differ.
06

A classifier at work

Explore
Classifier two-sample test (held-out AUC)Recorded · Python and R agreeRecorded 2026-11-21 · 19 values compared
R

Classifier two-sample test (held-out AUC), AUC = 0.72, p = .015

AUC
0.7240
p
.015

Plots

Principal coordinates of the rows by groupDo the groups separate in the dissimilarity space, and do they differ in where they sit or in how spread out they are?
View data
groupPCoA 1 (42.4%)PCoA 2 (32.5%)
g11.880−0.0590
g1−1.6120.8910
g11.8520.2849
g11.1820.9049
g10.65580.7322
g1−1.7232.557
g1−0.35371.066
g10.87331.373
g1−1.190−0.0974
g1−1.994−0.0357
g12.3631.065
g1−0.91710.3980
g11.1050.4423
g1−0.87310.2165
g11.6093.095
g10.7412−0.9501
g11.794−0.2277
g11.2020.0360
g10.81361.379
g10.6387−0.6940
g1−0.69970.1242
g10.44240.5991
g10.28181.578
g11.449−0.7876
g10.5212−0.4453
g10.2217−1.750
g12.778−1.161
g1−1.653−0.0826
g11.813−0.1413
g11.168−0.9665
g10.91671.327
g11.1300.4960
g1−0.41980.8517
g10.3646−0.3902
g10.48880.4014
g11.132−0.9397
g1−0.82840.1889
g1−1.2680.8131
g1−1.258−1.108
g10.39731.515
g20.3005−1.929
g22.515−1.324
g2−0.27580.0576
g20.8521−0.7303
g2−0.25711.649
g2−1.075−0.8621
g21.3360.2787
g20.19760.4148
g2−1.410−0.4676
g2−0.5506−1.262
g20.4851−0.0900
g2−0.9148−2.405
g2−0.6339−0.7328
g2−1.1240.1816
g20.1908−0.2489
g2−1.143−0.1104
g20.49091.963
g2−0.9839−0.6186
g2−0.5787−1.013
g2−1.271−1.232

First 60 of 90 rows.

Held-out AUC when the test half's labels are shuffledHow unusual is the observed statistic if the null hypothesis were true?
View data
DensityObservedAUC
0.36410.72400.2069
00.72400.2207
00.72400.2345
00.72400.2483
00.72400.2621
0.36410.72400.2759
0.36410.72400.2897
0.36410.72400.3035
0.72830.72400.3173
0.72830.72400.3311
0.36410.72400.3449
1.0920.72400.3587
2.1850.72400.3725
4.3700.72400.3863
2.1850.72400.4001
3.2770.72400.4139
2.5490.72400.4277
4.3700.72400.4415
1.8210.72400.4553
1.4570.72400.4691
3.2770.72400.4829
2.9130.72400.4967
6.9190.72400.5105
4.7340.72400.5243
5.4620.72400.5381
2.5490.72400.5519
4.3700.72400.5657
3.6410.72400.5795
2.1850.72400.5933
1.4570.72400.6071
2.1850.72400.6209
1.8210.72400.6347
0.72830.72400.6485
1.4570.72400.6623
00.72400.6761
0.36410.72400.6899
0.72830.72400.7037
0.36410.72400.7175
00.72400.7313
0.72830.72400.7451

Assumptions

  • Exchangeable rows — Under the null the group labels are exchangeable; rows must be independent.
  • Comparable scales — Distances use the raw values, so variables with large units dominate; standardize when units differ.

Groups

groupn
g140
g250
  • Rows split by group on the shared seeded stream (seed 42): 45 to fit, 45 to test; variables standardized with the fitting half. p: the test half's labels permuted 199 times with the classifier fixed (one-sided: AUC above chance).
The exact R script · R R version 4.5.1 (2025-06-13)
# Multivariate tests of equal distributions (energy, MMD, DISCO, classifier)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method multivariate.distribution_test 1.1.0 · spec c753b66079ec0ef6
# Dataset: mv_guide (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/mv_guide.parquet", col_select = c("y1", "y2", "y3", "group")))
n_input <- nrow(df)
df[["group"]] <- factor(df[["group"]], levels = c("g1", "g2"))  # stored level order
df <- df[stats::complete.cases(df[c("y1", "y2", "y3", "group")]), , 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("y1", "y2", "y3", "group"))  # infinite values stop the run (registry/errors.yaml)

# %% Test
# Do the groups come from the same multivariate distribution? Energy distance (Szekely & Rizzo 2004),
# maximum mean discrepancy with a Gaussian kernel (Gretton et al. 2012) or DISCO (Rizzo & Szekely 2010)
# on Euclidean distances, each with a label-permutation p from the shared Wichmann-Hill stream.
variables <- c("y1", "y2", "y3")
g <- "group"
test <- "c2st"  # energy | mmd | disco | c2st
transform_kind <- "none"
seed <- 42
n_perm <- as.integer(199)
alpha <- 0.05
levels_g <- levels(df[[g]])
codes <- as.integer(df[[g]]) - 1L
k <- length(levels_g)
if (k < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = g, min = 2, k = k)
if (test == "mmd" && k != 2) stop(sprintf("The MMD test compares exactly two groups; %s has %d. Use the energy test or DISCO for more.", g, k))
if (test == "c2st" && k != 2) cs_error("CS_E_GROUP_COUNT", column = g, expected = 2, k = k)
Y <- cs_mvd_transform(as.matrix(df[variables]), transform_kind)
n <- nrow(Y)
if (n > 5000) stop(sprintf("These tests use an n × n distance matrix; %d rows is too many (at most 5000).", n))
D <- cs_mvd_distance(Y, "euclidean")
group_n <- tabulate(codes + 1L, nbins = k)
extra <- list()
if (test == "energy") {
  res <- cs_mvd_energy_test(D, codes, k, n_perm, seed)
  stat <- res$statistic
  symbol <- "E"
  label <- "Energy test of equal distributions"
} else if (test == "c2st") {
  # Classifier two-sample test (Stage 12.7): fit on one half, score the other, AUC against a label permutation null.
  if (min(group_n) < 4) cs_error("CS_E_TOO_FEW_ROWS", what = "Each group in the classifier two-sample test", min = 4, n = min(group_n))
  classifier <- "logistic"  # logistic | knn
  res <- cs_c2st(Y, codes, classifier, 0.5, as.integer(10), n_perm, seed)
  stat <- res$auc
  symbol <- "AUC"
  label <- "Classifier two-sample test (held-out AUC)"
  extra <- list(classifier = classifier, c2st_accuracy = res$accuracy, baseline_accuracy = res$baseline, n_train = res$n_train, n_test = res$n_test)
} else if (test == "mmd") {
  sigma <- cs_mvd_mmd_bandwidth(D, "median", 1)
  res <- cs_mvd_mmd_test(D, codes, sigma, n_perm, seed)
  stat <- res$statistic
  symbol <- "MMD²ᵤ"
  label <- "Maximum mean discrepancy test"
  extra <- list(sigma = sigma)
} else {
  exponent <- 1
  res <- cs_mvd_disco(D, codes, k, exponent, n_perm, seed)
  stat <- res$f
  symbol <- "F"
  label <- "DISCO (distance components)"
  extra <- list(between = res$between, within = res$within, total = res$total, df1 = res$df1, df2 = res$df2, exponent = exponent)
}
p <- res$p

# %% Assumptions
scaled <- transform_kind %in% c("standardize", "range")
assumptions <- list(
  list(key = "exchangeable", label = "Exchangeable rows", status = "info",
       detail = "Under the null the group labels are exchangeable; rows must be independent."),
  list(key = "scaling", label = "Comparable scales", status = if (scaled || length(variables) == 1) "pass" else "info",
       detail = if (scaled) paste0("Variables were ", if (transform_kind == "standardize") "standardized" else "range-scaled", " before the distances.") else
         "Distances use the raw values, so variables with large units dominate; standardize when units differ.")
)

# %% Result
what <- if (p < alpha) "differ in distribution (location, spread or shape)" else "show no evidence of differing in distribution"
summary <- sprintf("%s on %s: the %d groups of %s %s (%s = %s, %s, %d permutations).", label, paste(variables, collapse = ", "), k, g, what,
                   symbol, format(signif(stat, 4)), cs_fmt_p(p), n_perm)
if (test == "mmd") summary <- paste(summary, sprintf("Gaussian kernel bandwidth σ = %s.", format(signif(extra$sigma, 4))))
if (test == "c2st") summary <- paste(summary, sprintf("A %s fitted on %d rows told the groups apart on %d new rows with AUC %.3f (0.5 = no better than chance) and accuracy %.1f%% (always guessing the larger group: %.1f%%).",
  if (extra$classifier == "logistic") "logistic regression" else "nearest-neighbor classifier", as.integer(extra$n_train), as.integer(extra$n_test), stat,
  100 * extra$c2st_accuracy, 100 * extra$baseline_accuracy))
values <- list(test = test, statistic = stat, p = p, k = k, n = n, n_perm = n_perm, sigma = NULL, between = NULL, within = NULL,
               total = NULL, df1 = NULL, df2 = NULL, exponent = NULL)
for (key in names(extra)) values[[key]] <- extra[[key]]
values$missing_share <- if (n_input > 0) n_dropped / n_input else 0
tables <- list(list(key = "groups", title = "Groups",
                    columns = list(list(key = "group", label = g, type = "string"), list(key = "n", label = "n", type = "integer")),
                    rows = data.frame(group = levels_g, n = as.integer(group_n))))
if (test == "disco") {
  tables <- c(list(list(key = "components", title = sprintf("Distance components (exponent %s)", format(extra$exponent)),
    columns = list(list(key = "source", label = "Source", type = "string"), list(key = "df", label = "df", type = "integer"),
                   list(key = "dist", label = "Sum of distances", type = "number"), list(key = "mean", label = "Mean", type = "number"),
                   list(key = "f", label = "F", type = "number"), list(key = "p", label = "p", type = "pvalue")),
    rows = list(list(source = g, df = extra$df1, dist = extra$between, mean = extra$between / extra$df1, f = stat, p = p),
                list(source = "Within", df = extra$df2, dist = extra$within, mean = extra$within / extra$df2, f = NULL, p = NULL),
                list(source = "Total", df = n - 1, dist = extra$total, mean = NULL, f = NULL, p = NULL)))), tables)
}
pc <- cs_mvd_pcoa(D)
V <- pc$vectors
ex <- pc$explained
ax1 <- if (ncol(V) > 0) V[, 1] else rep(0, n)
ax2 <- if (ncol(V) > 1) V[, 2] else rep(0, n)
cs_publish(list(
  method = "multivariate.distribution_test",
  methodVersion = "1.1.0",
  title = label,
  engine = cs_engine_info("stats", "nanoparquet"),
  n = n,
  summary = summary,
  apa = sprintf("%s, %s = %s, %s", label, symbol, cs_fmt_num(stat), cs_fmt_p(p)),
  statistics = list(list(key = "statistic", label = symbol, value = stat), list(key = "p", label = "p", value = p, format = "p")),
  tables = tables,
  effectSizes = list(),
  assumptions = assumptions,
  warnings = warnings,
  notes = list(if (test != "c2st") sprintf("Euclidean distances of the %svariables; p from %d label permutations on the shared seeded stream (seed %d).",
                       if (transform_kind == "standardize") "standardized " else "", n_perm, as.integer(seed)) else
               sprintf("Rows split by group on the shared seeded stream (seed %d): %d to fit, %d to test; variables standardized with the fitting half. p: the test half's labels permuted %d times with the classifier fixed (one-sided: AUC above chance).",
                       as.integer(seed), as.integer(extra$n_train), as.integer(extra$n_test), n_perm)),
  values = values,
  charts = c(list(cs_chart("ordination", "pcoa-centroids", sprintf("Principal coordinates of the rows by %s", g), list(
    x = cs_col(if (ncol(V) > 0) sprintf("PCoA 1 (%.1f%%)", 100 * ex[1]) else "PCoA 1", ax1),
    y = cs_col(if (ncol(V) > 1) sprintf("PCoA 2 (%.1f%%)", 100 * ex[2]) else "PCoA 2", ax2),
    group = cs_col(g, as.character(df[[g]]), levels = levels_g)), controls = list(center = "centroid", spokes = FALSE, hulls = TRUE))),
    if (test == "c2st") {
      nc <- cs_signflip_null_curve(res$null)
      list(cs_chart("null", "null-distribution", "Held-out AUC when the test half's labels are shuffled", list(
        x = cs_col("AUC", nc$x), density = cs_col("Density", nc$density), observed = cs_col("Observed", rep(stat, length(nc$x)))),
        controls = list(alternative = "greater")))
    } else list())
))
Python

Classifier two-sample test (held-out AUC), AUC = 0.72, p = .015

AUC
0.7240
p
.015

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

Assumptions

  • Exchangeable rows — Under the null the group labels are exchangeable; rows must be independent.
  • Comparable scales — Distances use the raw values, so variables with large units dominate; standardize when units differ.

Groups

groupn
g140
g250
  • Rows split by group on the shared seeded stream (seed 42): 45 to fit, 45 to test; variables standardized with the fitting half. p: the test half's labels permuted 199 times with the classifier fixed (one-sided: AUC above chance).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Multivariate tests of equal distributions (energy, MMD, DISCO, classifier)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method multivariate.distribution_test 1.1.0 · spec c753b66079ec0ef6
# Dataset: mv_guide (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.stats import mvdist

# %% Data
df = pd.read_parquet("tests/parity/fixtures/mv_guide.parquet", columns=["y1", "y2", "y3", "group"])
n_input = len(df)
df["group"] = pd.Categorical(df["group"], categories=["g1", "g2"])  # stored level order
df = df.dropna(subset=["y1", "y2", "y3", "group"])  # listwise deletion over the analysis columns
df["group"] = df["group"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
    warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
    cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["y1", "y2", "y3", "group"])  # infinite values stop the run (registry/errors.yaml)

# %% Test
# Do the groups come from the same multivariate distribution? Energy distance (Székely & Rizzo 2004),
# maximum mean discrepancy with a Gaussian kernel (Gretton et al. 2012) or DISCO (Rizzo & Székely 2010)
# on Euclidean distances, each with a label-permutation p from the shared Wichmann–Hill stream.
variables = ["y1", "y2", "y3"]
g = "group"
test = "c2st"  # energy | mmd | disco | c2st
transform_kind = "none"
seed = 42
n_perm = int(199)
alpha = 0.05
levels = [str(lv) for lv in df[g].cat.categories]
codes = df[g].cat.codes.to_numpy().astype(int)
k = len(levels)
if k < 2:
    cs.cs_error("CS_E_TOO_FEW_GROUPS", column=g, min=2, k=k)
if test == "mmd" and k != 2:
    raise ValueError(f"The MMD test compares exactly two groups; {g} has {k}. Use the energy test or DISCO for more.")
if test == "c2st" and k != 2:
    cs.cs_error("CS_E_GROUP_COUNT", column=g, expected=2, k=k)
Y = mvdist.transform(df[variables].to_numpy(dtype=float), transform_kind)
n = int(Y.shape[0])
if n > 5000:
    raise ValueError(f"These tests use an n × n distance matrix; {n} rows is too many (at most 5000).")
D = mvdist.distance(Y, "euclidean")
group_n = np.bincount(codes, minlength=k)
if test == "energy":
    res = mvdist.energy_test(D, codes, k, n_perm, seed)
    stat, symbol, label = res["statistic"], "E", "Energy test of equal distributions"
    extra = {}
elif test == "c2st":
    # Classifier two-sample test (Stage 12.7): fit on one half, score the other, AUC against a label permutation null.
    from codesplash.stats import c2st as c2
    if int(group_n.min()) < 4:
        cs.cs_error("CS_E_TOO_FEW_ROWS", what="Each group in the classifier two-sample test", min=4, n=int(group_n.min()))
    classifier = "logistic"  # logistic | knn
    res = c2.c2st(Y, codes, classifier, 0.5, int(10), n_perm, seed)
    stat, symbol, label = res["auc"], "AUC", "Classifier two-sample test (held-out AUC)"
    extra = {"classifier": classifier, "c2st_accuracy": res["accuracy"], "baseline_accuracy": res["baseline"],
             "n_train": res["n_train"], "n_test": res["n_test"]}
elif test == "mmd":
    sigma = mvdist.mmd_bandwidth(D, "median", 1)
    res = mvdist.mmd_test(D, codes, sigma, n_perm, seed)
    stat, symbol, label = res["statistic"], "MMD²ᵤ", "Maximum mean discrepancy test"
    extra = {"sigma": sigma}
else:
    exponent = 1
    res = mvdist.disco(D, codes, k, exponent, n_perm, seed)
    stat, symbol, label = res["f"], "F", "DISCO (distance components)"
    extra = {"between": res["between"], "within": res["within"], "total": res["total"], "df1": res["df1"], "df2": res["df2"], "exponent": exponent}
p = res["p"]

# %% Assumptions
assumptions = [
    {"key": "exchangeable", "label": "Exchangeable rows", "status": "info",
     "detail": "Under the null the group labels are exchangeable; rows must be independent."},
    {"key": "scaling", "label": "Comparable scales", "status": "pass" if transform_kind in ("standardize", "range") or len(variables) == 1 else "info",
     "detail": ("Variables were " + ("standardized" if transform_kind == "standardize" else "range-scaled") + " before the distances."
                if transform_kind in ("standardize", "range") else
                "Distances use the raw values, so variables with large units dominate; standardize when units differ.")},
]

# %% Result
what = "differ in distribution (location, spread or shape)" if p < alpha else "show no evidence of differing in distribution"
summary = (f"{label} on {', '.join(variables)}: the {k} groups of {g} {what} ({symbol} = {stat:.4g}, {cs.fmt_p(p)}, {n_perm} permutations).")
if test == "mmd":
    summary += f" Gaussian kernel bandwidth σ = {extra['sigma']:.4g}."
if test == "c2st":
    summary += (f" A {'logistic regression' if extra['classifier'] == 'logistic' else 'nearest-neighbor classifier'} fitted on {extra['n_train']} rows"
                f" told the groups apart on {extra['n_test']} new rows with AUC {stat:.3f} (0.5 = no better than chance) and accuracy {extra['c2st_accuracy']:.1%}"
                f" (always guessing the larger group: {extra['baseline_accuracy']:.1%}).")
values = {"test": test, "statistic": stat, "p": p, "k": k, "n": n, "n_perm": n_perm,
          **{key: None for key in ("sigma", "between", "within", "total", "df1", "df2", "exponent")}, **extra}
values["missing_share"] = n_dropped / n_input if n_input else 0.0
tables = [{"key": "groups", "title": "Groups",
           "columns": [{"key": "group", "label": g, "type": "string"}, {"key": "n", "label": "n", "type": "integer"}],
           "rows": [{"group": lv, "n": int(m)} for lv, m in zip(levels, group_n)]}]
if test == "disco":
    tables.insert(0, {"key": "components", "title": f"Distance components (exponent {extra['exponent']:g})",
                      "columns": [{"key": "source", "label": "Source", "type": "string"}, {"key": "df", "label": "df", "type": "integer"},
                                  {"key": "dist", "label": "Sum of distances", "type": "number"}, {"key": "mean", "label": "Mean", "type": "number"},
                                  {"key": "f", "label": "F", "type": "number"}, {"key": "p", "label": "p", "type": "pvalue"}],
                      "rows": [{"source": g, "df": extra["df1"], "dist": extra["between"], "mean": extra["between"] / extra["df1"], "f": stat, "p": p},
                               {"source": "Within", "df": extra["df2"], "dist": extra["within"], "mean": extra["within"] / extra["df2"], "f": None, "p": None},
                               {"source": "Total", "df": n - 1, "dist": extra["total"], "mean": None, "f": None, "p": None}]})
pc = mvdist.pcoa(D)
V, ex = pc["vectors"], pc["explained"]
ax1 = V[:, 0] if V.shape[1] else np.zeros(n)
ax2 = V[:, 1] if V.shape[1] > 1 else np.zeros(n)
cs.publish({
    "method": "multivariate.distribution_test",
    "methodVersion": "1.1.0",
    "title": label,
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": n,
    "summary": summary,
    "apa": f"{label}, {symbol} = {cs.fmt_num(stat)}, {cs.fmt_p(p)}",
    "statistics": [{"key": "statistic", "label": symbol, "value": stat}, {"key": "p", "label": "p", "value": p, "format": "p"}],
    "tables": tables,
    "effectSizes": [],
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": [f"Euclidean distances of the {('standardized ' if transform_kind == 'standardize' else '')}variables; p from {n_perm} label permutations on the shared seeded stream (seed {seed})."
              if test != "c2st" else
              f"Rows split by group on the shared seeded stream (seed {seed}): {extra['n_train']} to fit, {extra['n_test']} to test; variables standardized with the fitting half. "
              f"p: the test half's labels permuted {n_perm} times with the classifier fixed (one-sided: AUC above chance)."],
    "values": values,
    "charts": [cs.chart("ordination", "pcoa-centroids", f"Principal coordinates of the rows by {g}", {
        "x": cs.col(f"PCoA 1 ({100 * ex[0]:.1f}%)" if V.shape[1] else "PCoA 1", ax1),
        "y": cs.col(f"PCoA 2 ({100 * ex[1]:.1f}%)" if V.shape[1] > 1 else "PCoA 2", ax2),
        "group": cs.col(g, df[g].astype(str).to_numpy(), levels=levels)}, controls={"center": "centroid", "spokes": False, "hulls": True})]
        + ([cs.chart("null", "null-distribution", "Held-out AUC when the test half's labels are shuffled", {
            "x": cs.col("AUC", c2.null_curve(res["null"])[0]), "density": cs.col("Density", c2.null_curve(res["null"])[1]),
            "observed": cs.col("Observed", np.full(40, stat))}, controls={"alternative": "greater"})] if test == "c2st" else []),
})

A logistic regression fitted on 45 rows told the groups apart on 45 new rows with AUC 0.724 and accuracy 68.9%, against 55.6% for always guessing the larger group: p = .015.

A bonus over MMD: the classifier's mistakes and its most useful features show where the samples differ.

Make the groups differ only in spread below, and give each group more rows. Then compare logistic regression with nearest neighbors.

BExplorable · Classifier two-sample test

If a classifier can tell two samples apart on rows it never saw, can they come from the same distribution?

Data

Simulated data follow the settings below. The lesson's example is the data the engines ran, as recorded; the settings don't change it.

40
50
3
0.50

Added to every variable in group 2: a difference in location.

1.00

Multiplies group 2's first variable: a difference in spread only.

Classifier

Logistic regression looks for a shift in location; nearest neighbors also see spread and shape.

0.50

Rows of each group kept aside to test the classifier; the rest fit it.

10

How many of the nearest fitting rows vote on each held-out row (nearest neighbors only).

199

Permutations of the held-out labels with the classifier fixed; the smallest possible p is 1/(B + 1).

0.050

Your data

Simulated with a known difference

The first two of 3 variables; crosses mark the group means. The classifier fits 45 rows and is scored on the other 45.

If H₀ were true

AUC = 0.60
  1. The reference: how AUC varies across samples when H₀ is true, 199 permutations of the held-out labels (permutation null: the classifier stays fixed and the 45 held-out labels are shuffled (seed 43)).
  2. Your statistic, from the data above.
  3. The p-value: the area at least as extreme as yours (p = .120).
  4. The hatched rejection region at α = .050: statistics landing here reject H₀.

The formula

AUC^held out=Pr⁡(s(xgroup 2)>s(xgroup 1)),p=1+#{AUC^∗≥AUC^}B+1\widehat{\mathrm{AUC}}_{\text{held out}} = \Pr\bigl(s(x_{\text{group 2}}) > s(x_{\text{group 1}})\bigr),\qquad p = \dfrac{1 + \#\{\widehat{\mathrm{AUC}}^{*} \ge \widehat{\mathrm{AUC}}\}}{B + 1}

With your numbers

AUC^held out=0.60,accuracy=0.56, ntest=45, B=199\widehat{\mathrm{AUC}}_{\text{held out}} = 0.60,\qquad \text{accuracy} = 0.56,\ n_{\text{test}} = 45,\ B = 199
s(x)s(x)
the classifier's score, fitted on the other rows
AUC^∗\widehat{\mathrm{AUC}}^{*}
the same held-out AUC after shuffling the held-out labels, classifier fixed
BB
the number of shuffles

The verdict

AUC = 0.60, p = .120

p > α = .050: compatible with H₀

Under H0 no classifier beats chance on held-out rows, so the AUC hovers near 0.5. Make the groups differ only in spread and give each group more rows: nearest neighbors, which can see spread, catch it more reliably than logistic regression, which looks for a shift in location. Choose the lesson's example to run the data the engines ran; the AUC and p match the recorded result.

Statistic
0.604
p-value
0.1200
Classifier two-sample test on 40 rows in group 1 and 50 in group 2, on 3 variables: AUC = 0.60, p = .120. The p-value is above α = .050, so the data are compatible with H0.

Classifier two-sample test on 40 rows in group 1 and 50 in group 2, on 3 variables: AUC = 0.60, p = .120. The p-value is above α = .050, so the data are compatible with H₀.

07

What a non-rejection means

Read

Failing to reject doesn't show the distributions are equal. A weak classifier, an unsuitable kernel or an encoder that discards the difference can all miss it. A test on embeddings is only as sensitive as the encoder; a test on raw pixels may react mostly to nuisance changes.

Rejection, in turn, doesn't measure harm: with enough rows, a trivial shift is "significant". And tuning a generator against one of these tests over and over leaks: the test becomes part of training. Near-duplicates across the classifier's split make discrimination misleadingly easy.

08

In CodeSplash

In the app

In Analyze, Multivariate tests of equal distributions runs the energy test, MMD (Gaussian kernel, median-heuristic or fixed bandwidth), DISCO for several groups and the classifier test (ridge logistic or nearest neighbors, fitted on a stratified half, held-out AUC, p from permuting the held-out labels with the classifier fixed). Variables can be standardized first.

Model monitors use the same ideas for drift across many features at once, with shared permutations and Holm across the tests.

09

What runs here

Read
10

Check: two-sample tests

Checkpoint

Check yourself

An unbiased MMD² estimate comes out slightly negative. What does it mean?

Show the answer

Answer: b

Unbiased means right on average, so near zero it lands on both sides. Read the permutation p-value, not the sign.

Check yourself

You try five kernel bandwidths and report the one with the smallest p-value. What is wrong?

Show the answer

Answer: b

Picking the most favorable setting is a hidden multiple comparison. A rule fixed beforehand, such as the median heuristic, avoids it.

Check yourself

You compare real and generated videos with an energy test on individual frames, shuffling frame labels. What is wrong?

Show the answer

Answer: b

Permutation calibration needs exchangeable units. Frames share their video's content, so the unit is the video.

Check yourself

What does the energy statistic need that MMD with a Gaussian kernel doesn't?

Show the answer

Answer: a

The energy distance is built from expected distances, which must be finite. It has no bandwidth to choose.

Check yourself

In a classifier two-sample test, what must happen before standardizing the features?

Show the answer

Answer: b

Any learned step, scaling included, belongs to the fitting half. Otherwise the held-out score isn't held out.

Check yourself

A classifier test on real against synthetic records gives held-out AUC 0.51. What can you conclude?

Show the answer

Answer: b

Weak discrimination can reflect a weak classifier. It is evidence of similarity only as strong as the classifier.

Check yourself

Why may an exact binomial p-value be wrong when the held-out set was forced to exactly half real, half synthetic?

Show the answer

Answer: a

With forced equal counts, correct classifications are no longer independent Bernoulli(½) events. Permute the held-out labels with the classifier fixed instead.

11

Recap

Recap
  • MMD compares kernel similarities, energy compares distances, the classifier test asks whether a held-out classifier beats chance.
  • Calibrate by permuting exchangeable units; fix bandwidths and classifiers before testing.
  • Keep the classifier test's fitting, tuning and scoring apart, and match the p-value to the label design.
  • No rejection doesn't mean equal; a rejection doesn't measure harm.

Concepts in this lesson