Beyond means: energy, MMD and DISCO
Compare whole multivariate distributions with distance and kernel statistics, calibrated by permutation, and learn what each can and can't tell you.
What runs in CodeSplash
- STAT168Energy two sample or k sample test Runs in CodeSplash
- STAT169Maximum mean discrepancy test Runs in CodeSplash
- STAT174DISCO test Runs in CodeSplash
- Multivariate tests of equal distributions (energy, MMD, DISCO, classifier) Verified in Python and R
You will be able to
- Explain the idea behind the energy distance and MMD
- Choose a bandwidth or exponent, and scale variables first when needed
- Read a DISCO decomposition, and the p-value floor of a permutation test
When means aren't the question
ReadT² and MANOVA ask if group means differ. Groups can share a mean and still differ in spread, in shape, or in how the variables relate.
Tests of equal distributions ask a broader question: could these rows have come from the same distribution? The answer isn't tied to any one feature of the data. The price is that a rejection doesn't say which feature differs.
Predict what they catch
PredictPredict first
Two groups have identical mean vectors, but one has twice the spread of the other.
Which test has real power to detect this?
Reveal
The energy test. T² compares means and has only its nominal false-positive rate here, however large the sample. Energy statistics respond to any difference between distributions, once the sample is large enough.
The energy distance
ReadTake one row from each group and measure the distance. Compare that with typical distances within each group:
This is zero only if the two distributions are identical, and positive otherwise. The energy testEnergy distanceTwice the mean distance between samples minus the mean distances within each; zero only when the distributions are equal. scales it by the sample sizes.
On the simulated two-group study, E = 9.64. No formula gives a reference distribution, so the labels are shuffled.
The permutation floor
PredictPredict first
This run used 199 permutations. What is the smallest p-value it can report?
Make your guess between 0 and 0.05 smallest possible p, then reveal.
Reveal
, which is 0.005. And that is what it reports. So the result means "p at or below this value", not this exact value. Raise Permutations when you need a finer floor.
Maximum mean discrepancy
ReadMMDMaximum mean discrepancyThe distance between two distributions' average kernel embeddings; zero when they are equal. does the same job with a kernel. It compares average similarity within groups and across groups.
Everything depends on the kernel's width σ. With Median heuristic, σ is set from the data's typical distance, here 2.18, and MMD² = 0.078.
With Fixed σ at 1, MMD² = 0.081. Both p-values sit at the floor.
Pick σ before you look at the p-value: trying several and keeping the best is a forking path.
DISCO decomposes distances
In the appDISCO is to distances what ANOVA is to squares. Total dispersion splits into between and within parts.
DISCO (distance components), F = 4.43, p = .005
- F
- 4.430
- p
- .005
Plots
View data
| group | PCoA 1 (42.4%) | PCoA 2 (32.5%) |
|---|---|---|
| g1 | 1.880 | −0.0590 |
| g1 | −1.612 | 0.8910 |
| g1 | 1.852 | 0.2849 |
| g1 | 1.182 | 0.9049 |
| g1 | 0.6558 | 0.7322 |
| g1 | −1.723 | 2.557 |
| g1 | −0.3537 | 1.066 |
| g1 | 0.8733 | 1.373 |
| g1 | −1.190 | −0.0974 |
| g1 | −1.994 | −0.0357 |
| g1 | 2.363 | 1.065 |
| g1 | −0.9171 | 0.3980 |
| g1 | 1.105 | 0.4423 |
| g1 | −0.8731 | 0.2165 |
| g1 | 1.609 | 3.095 |
| g1 | 0.7412 | −0.9501 |
| g1 | 1.794 | −0.2277 |
| g1 | 1.202 | 0.0360 |
| g1 | 0.8136 | 1.379 |
| g1 | 0.6387 | −0.6940 |
| g1 | −0.6997 | 0.1242 |
| g1 | 0.4424 | 0.5991 |
| g1 | 0.2818 | 1.578 |
| g1 | 1.449 | −0.7876 |
| g1 | 0.5212 | −0.4453 |
| g1 | 0.2217 | −1.750 |
| g1 | 2.778 | −1.161 |
| g1 | −1.653 | −0.0826 |
| g1 | 1.813 | −0.1413 |
| g1 | 1.168 | −0.9665 |
| g1 | 0.9167 | 1.327 |
| g1 | 1.130 | 0.4960 |
| g1 | −0.4198 | 0.8517 |
| g1 | 0.3646 | −0.3902 |
| g1 | 0.4888 | 0.4014 |
| g1 | 1.132 | −0.9397 |
| g1 | −0.8284 | 0.1889 |
| g1 | −1.268 | 0.8131 |
| g1 | −1.258 | −1.108 |
| g1 | 0.3973 | 1.515 |
| g2 | 0.3005 | −1.929 |
| g2 | 2.515 | −1.324 |
| g2 | −0.2758 | 0.0576 |
| g2 | 0.8521 | −0.7303 |
| g2 | −0.2571 | 1.649 |
| g2 | −1.075 | −0.8621 |
| g2 | 1.336 | 0.2787 |
| g2 | 0.1976 | 0.4148 |
| g2 | −1.410 | −0.4676 |
| g2 | −0.5506 | −1.262 |
| g2 | 0.4851 | −0.0900 |
| g2 | −0.9148 | −2.405 |
| g2 | −0.6339 | −0.7328 |
| g2 | −1.124 | 0.1816 |
| g2 | 0.1908 | −0.2489 |
| g2 | −1.143 | −0.1104 |
| g2 | 0.4909 | 1.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.
Distance components (exponent 1)
| Source | df | Sum of distances | Mean | F | p |
|---|---|---|---|---|---|
| group | 1 | 4.821 | 4.821 | 4.430 | .005 |
| Within | 88 | 95.764 | 1.088 | — | — |
| Total | 89 | 100.59 | — | — | — |
Groups
| group | n |
|---|---|
| g1 | 40 |
| g2 | 50 |
- 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 def1e01e176c46b8
# 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 <- "disco" # 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())
))
DISCO (distance components), F = 4.43, p = .005
- F
- 4.430
- 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.
Distance components (exponent 1)
| Source | df | Sum of distances | Mean | F | p |
|---|---|---|---|---|---|
| group | 1 | 4.821 | 4.821 | 4.430 | .005 |
| Within | 88 | 95.764 | 1.088 | — | — |
| Total | 89 | 100.59 | — | — | — |
Groups
| group | n |
|---|---|
| g1 | 40 |
| g2 | 50 |
- 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 def1e01e176c46b8
# 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 = "disco" # 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 []),
})
Total 100.6 splits into between 4.8 and within 95.8, with F = 4.43.
With Distance exponent α at 2, the split reduces to classical sums of squares, so DISCO looks only at means. On two iris variables, that gives F = 98.0. Keep α below 2 to see more than means.
Scale before you measure
ReflectDistances are dominated by the variables with the largest numbers. A variable in dollars beats one in percentages, whatever matters to you.
On iris with four variables, Transform first set to Standardize gives E = 269.4, 0.01 with 99 permutations.
Which variables in your own data would swamp the others if you didn't scale them?
Check your understanding
CheckpointCheck yourself
You run 999 permutations and none is at least as extreme as the observed statistic. What p-value is reported?
Show the answer
Answer: 0.001
. The observed arrangement counts as one.
Check yourself
The energy test gives p = 0.004. What can you say?
Show the answer
Answer: c
A broad test says "something differs". Follow it with plots, T² for means, and Box's M or PERMDISP for spread.
Check yourself
Why is the default distance exponent below 2 for DISCO?
Show the answer
Answer: b
Below 2, the energy distance can detect any difference between distributions. At 2 it only sees the means.
Do it in CodeSplash
In the appChoose Variables and Groups, then the Test. The ordination chart shows the rows in a few principal coordinates, by group.
import pandas as pd
import dcor
df = pd.read_csv("study.csv")
cols = ["y1", "y2", "y3"]
x1 = df.loc[df["group"] == "g1", cols].to_numpy()
x2 = df.loc[df["group"] == "g2", cols].to_numpy()
print(dcor.homogeneity.energy_test(x1, x2, num_resamples=999))# install.packages("energy")
df <- read.csv("study.csv")
X <- scale(df[c("y1", "y2", "y3")])
energy::eqdist.etest(X, sizes = table(df$group), R = 999)
energy::disco(X, factors = df$group, R = 999)Recap
Recap- Energy, MMD and DISCO compare whole distributions, not only means.
- A rejection says the distributions differ, not how.
- Permutation p-values have a floor of .
- Scale variables first, and pick the bandwidth or exponent before you look.
Concepts in this lesson