Skip to content

BCompare groups · Guide test 169

Maximum mean discrepancy test

Tests equality of distributions by comparing their embeddings in a kernel function space.

Runs in CodeSplashPython example validatedR example validated

Do it in CodeSplash

In the app, set it up in Analyze with this method:

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

20
25
0.60
0.00
0.50
0.050

Your data

Simulated with known truth

2 groups on two measurements; crosses mark the group means.

If H₀ were true

MMD² = 0.06
  1. 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)).
  2. Your statistic, from the data above.
  3. The p-value: the area at least as extreme as yours (p = .080).
  4. The hatched rejection region at α = .050: statistics landing here reject H₀.

The formula

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

With your numbers

MMD^2=0.06,n=20, m=25\widehat{\mathrm{MMD}}^2 = 0.06,\qquad n = 20,\ m = 25
k(a,b)=e−∥a−b∥2/2k(a,b) = e^{-\|a-b\|^2/2}
Gaussian kernel with bandwidth 1
MMD^2\widehat{\mathrm{MMD}}^2
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 H0.

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

MMD^u2=∑i≠jk(Xi,Xj)m(m−1)+∑i≠jk(Yi,Yj)n(n−1)−2∑ijk(Xi,Yj)mn\widehat{MMD}_u^2=\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_{ij}k(X_i,Y_j)}{mn}

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.

Python · native

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
R

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

  • Gretton et al. (2012) — Gretton et al. (2012) · A Kernel Two-Sample Testjmlr.org
  • gretton12ajmlr.org
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.