A Kernel Two-Sample Test
Authors: Arthur Gretton, Karsten M. Borgwardt, Malte J. Rasch, Bernhard Schölkopf, Alexander Smola, Alex J. Smola
Published: 2012
Journal: Journal of Machine Learning Research
Link: PDF
Summary
This paper provides a comprehensive treatment of the Maximum Mean Discrepancy (MMD) as a statistic for two-sample testing. It establishes theoretical properties, efficient estimators, and practical guidelines for kernel selection.
Key Contributions
1. Maximum Mean Discrepancy (MMD)
The MMD between distributions and is:
For unit ball in RKHS :
2. Characteristic Kernels
Definition: Kernel is characteristic if .
Examples of characteristic kernels:
- Gaussian RBF:
- Laplacian:
- Matérn family
3. Unbiased MMD Estimator
Given and :
where:
4. Asymptotic Distribution
Under :
where and are eigenvalues of the covariance operator.
Statistical Test Framework
Hypothesis Test
Test Statistic Variants
1. Quadratic-time statistic (U-statistic):
2. Linear-time statistic:
Threshold Selection
Permutation test (recommended for finite samples):
- Compute observed
- Pool samples, permute, compute
- Repeat times
- Reject if observed exceeds quantile
Asymptotic test (large samples):
- Estimate eigenvalues
- Simulate null distribution
- Use appropriate quantile
Implementation
import numpy as np
from scipy.spatial.distance import cdist
def rbf_kernel(X, Y, sigma=1.0):
"""Compute RBF kernel matrix."""
sq_dist = cdist(X, Y, 'sqeuclidean')
return np.exp(-sq_dist / (2 * sigma**2))
def mmd_squared_u_statistic(X, Y, kernel_func):
"""
Compute unbiased MMD^2 U-statistic.
"""
n, m = len(X), len(Y)
K_XX = kernel_func(X, X)
K_YY = kernel_func(Y, Y)
K_XY = kernel_func(X, Y)
# Remove diagonal for unbiased estimate
term1 = (K_XX.sum() - np.trace(K_XX)) / (n * (n - 1))
term2 = (K_YY.sum() - np.trace(K_YY)) / (m * (m - 1))
term3 = 2 * K_XY.mean()
return term1 + term2 - term3
def mmd_linear_time(X, Y, kernel_func):
"""
Compute linear-time MMD estimator.
"""
n = min(len(X), len(Y))
n = n - (n % 2) # Make even
X, Y = X[:n], Y[:n]
# Pair up samples
h_values = []
for i in range(0, n, 2):
x1, x2 = X[i:i+1], X[i+1:i+2]
y1, y2 = Y[i:i+1], Y[i+1:i+2]
h = (kernel_func(x1, x2)[0,0] + kernel_func(y1, y2)[0,0]
- kernel_func(x1, y2)[0,0] - kernel_func(x2, y1)[0,0])
h_values.append(h)
return np.mean(h_values)
def mmd_permutation_test(X, Y, kernel_func, n_permutations=1000, alpha=0.05):
"""
Perform MMD two-sample test with permutation.
"""
# Observed statistic
observed = mmd_squared_u_statistic(X, Y, kernel_func)
# Pool and permute
combined = np.vstack([X, Y])
n = len(X)
null_statistics = []
for _ in range(n_permutations):
perm = np.random.permutation(len(combined))
X_perm = combined[perm[:n]]
Y_perm = combined[perm[n:]]
null_statistics.append(mmd_squared_u_statistic(X_perm, Y_perm, kernel_func))
# Compute p-value
p_value = np.mean(np.array(null_statistics) >= observed)
return {
'statistic': observed,
'p_value': p_value,
'reject': p_value < alpha,
'threshold': np.quantile(null_statistics, 1 - alpha)
}
Kernel Selection
Median Heuristic
Set bandwidth to median of pairwise distances:
Multiple Kernel MMD
Use multiple bandwidths for robustness:
Optimized Kernel Selection
Maximize test power by optimizing kernel parameters on held-out data.
Applications
- Model Validation: Test if generator matches real data distribution
- Feature Selection: Test which features differ between groups
- Change Detection: Detect distribution shifts in streaming data
- Domain Adaptation: Measure domain discrepancy
Power Analysis
Test power depends on:
- Sample size: Power increases with
- Kernel bandwidth: Optimal depends on distribution separation
- Dimensionality: Power decreases in high dimensions
For well-chosen kernel:
Citation
@article{gretton2012kernel,
title={A kernel two-sample test},
author={Gretton, Arthur and Borgwardt, Karsten M and Rasch, Malte J
and Sch{\"o}lkopf, Bernhard and Smola, Alexander},
journal={Journal of Machine Learning Research},
volume={13},
pages={723--773},
year={2012}
}
Further Reading
- Borgwardt, K., et al. (2006). Integrating structured biological data by kernel MMD
- Sutherland, D., et al. (2017). Generative models and model criticism via optimized MMD
- Liu, F., et al. (2020). Learning deep kernels for non-parametric two-sample tests