BCompare groups · Guide test 169
Maximum mean discrepancy test
Tests equality of distributions by comparing their embeddings in a kernel function space.
Do it in CodeSplash
In the app, set it up in Analyze with this method:
- Multivariate tests of equal distributions (energy, MMD, DISCO, classifier) — Do the groups come from the same multivariate distribution — in location, spread or shape?
In Multivariate tests of equal distributions (energy, MMD, DISCO, classifier), choose Test = Maximum mean discrepancy (MMD).
Do it in CodeSplash Run this test on your own data, in Python or R.
Bench
Change the design, drag the data, move α. The statistic, its reference distribution and the verdict follow.
Bench · Maximum mean discrepancy test
Your data
Simulated with known truth2 groups on two measurements; crosses mark the group means.
If H₀ were true
- The reference: how MMD² varies across samples when H₀ is true, MMD² over relabelings of the pooled rows (permutation null: 199 relabelings of these data (seed 20261107)).
- Your statistic, from the data above.
- The p-value: the area at least as extreme as yours (p = .080).
- The hatched rejection region at α = .050: statistics landing here reject H₀.
The formula
With your numbers
- Gaussian kernel with bandwidth 1
- unbiased estimate: can be slightly negative under H₀
The verdict
MMD² = 0.065, p = .080
p > α = .050: compatible with H₀
Choosing the bandwidth after looking at the data invalidates the permutation p-value; fix it in advance or select it inside each permutation.
- Statistic
- 0.065
- p-value
- 0.0800
Maximum mean discrepancy test on two groups of 20 and 25 rows on two variables: MMD² = 0.065, p = .080. The p-value is above α = .050, so the data are compatible with H₀.
Question and hypotheses
H0: PX=PY.
Assumptions
Independent samples; a characteristic kernel for consistency against all alternatives; bounded kernel or suitable moment assumptions.
Formula
Parameters and notation
k is a positive definite kernel with specified bandwidth; unbiased MMD² may be negative in finite samples.
Structure of the method
Evaluate a positive-definite kernel on pooled observations and combine within-sample off-diagonal means with cross-sample means. The displayed quadratic-time unbiased MMD-squared estimator is a U-statistic and can be negative in finite samples. Permuting labels gives a null reference without assuming a normal limit for the degenerate null statistic.
Estimated and nuisance parameters
Empirical kernel means are estimated distribution embeddings. A fixed kernel needs no fitted model weights; if an encoder or kernel is learned, its parameters are an additional fitted component and must be included in the testing protocol.
Settings and design choices
Specify characteristic kernel, bandwidth, scaling, biased versus unbiased estimator, exact/Monte Carlo permutation count, and seed. Label-blind pooled bandwidth selection can be permutation-invariant; optimizing bandwidth against observed group separation requires independent tuning or repeating the selection during calibration.
Fitting and adaptation
Construct the Gram matrix after defining preprocessing. Keep label-independent pooled operations fixed only when their invariance justifies it. Train a deep kernel on separate data or use a valid split/selection-aware procedure; tuning for the largest observed MMD and applying a fixed-kernel p-value is invalid.
Sensitivity and robustness
Very broad or narrow kernels can have little power, and distance concentration worsens interpretation in high dimension. Small samples, ties, heavy-tailed kernels, and dependence need care. Quadratic memory may motivate linear-time approximations, but those are different estimators with their own calibration. Report the kernel and estimator, not merely 'MMD test'.
How to use and calibrate
Use permutations or a justified degenerate U-statistic null approximation. Keep kernel selection within a valid testing protocol.
Example application
Test whether training and deployment feature distributions differ.
Interpretation and pitfalls
Watch out
The null is not ordinarily normal for the quadratic statistic. Data-adaptive kernel searches need corrected calibration.
What changed in edition 2
- New sections: structure of the method, estimated and nuisance parameters, settings and design choices, fitting and adaptation, sensitivity and robustness.
Python and R
Unbiased squared MMD with fixed Gaussian bandwidth one. The unbiased estimate may be negative; upper-tail label permutations calibrate it.
Validated — Executed successfully in the validation environment · needs numpy, scipy
import numpy as np
from scipy import stats
rng = np.random.default_rng(2026)
X=rng.normal(size=(40,3));Y=rng.normal(.3,1,size=(50,3))
Z=np.vstack([X,Y]);n=len(X);m=len(Y);K=np.exp(-np.sum((Z[:,None]-Z[None,:])**2,axis=2)/2)
def mmd(j):
a,b=j[:n],j[n:];A=K[np.ix_(a,a)];B=K[np.ix_(b,b)]
return (A.sum()-np.trace(A))/(n*(n-1))+(B.sum()-np.trace(B))/(m*(m-1))-2*K[np.ix_(a,b)].mean()
t=mmd(np.arange(n+m));B=999;null=np.array([mmd(rng.permutation(n+m)) for _ in range(B)])
print(t,(1+np.sum(null>=t))/(B+1))
Output
0.012999444718273523 0.136
Validated — Executed successfully in the validation environment · needs Base/standard library
set.seed(2026)
X<-matrix(rnorm(120),ncol=3);Y<-matrix(rnorm(150,mean=.3),ncol=3)
Z<-rbind(X,Y);n<-nrow(X);m<-nrow(Y);K<-exp(-as.matrix(dist(Z))^2/2)
MMD<-function(j) {a<-j[1:n];b<-j[n+1:m];(sum(K[a,a])-sum(diag(K)[a]))/(n*(n-1))+(sum(K[b,b])-sum(diag(K)[b]))/(m*(m-1))-2*mean(K[a,b])}
T<-MMD(1:(n+m));B<-999;null<-replicate(B,MMD(sample.int(n+m)))
print(c(MMD2=T,p=(1+sum(null>=T))/(B+1)))
Output
MMD2 p 0.08057116 0.00100000
Sources
- Statistics guide v4 (historical):
- R: Executed successfully in the validation environment
- Reference's record:
- Edition 2 review: Python: executed · R: not executed (Rscript unavailable). Python: Ran in the reference's review, on this exact code. R: Reviewed but not run: R wasn't available to the reference's authors.
From the CodeSplash statistics guide (v4), entry 169, updated from the reference's edition 2 (reviewed 14 November 2026) as STAT169.