Kernel Mean Embeddings & Two-Sample Tests
Comparing distributions with kernels: the MMD.
Do the inputs your model meets in production come from the same distribution as its training data? Do two groups of patients differ in some way nobody thought to measure? Kernels answer such questions by mapping an entire probability distribution to a single point of an RKHS. The distance between two such points, the maximum mean discrepancy, compares distributions in any dimension, and it yields tests whose false-alarm rate is controlled exactly.
What you’ll learn
- Define the kernel mean embedding , show that , and explain when the embedding is injective (characteristic kernels).
- Derive , its unbiased estimator, and the witness function.
- Build a kernel two-sample test with a permutation threshold, and state its asymptotics under the null and the alternative.
- Extend the construction to independence testing (HSIC), and weigh its uses (shift detection, generative models, domain adaptation) against its limits.
A distribution as a point
Let be a kernel with RKHS and feature map . For a distribution with , the kernel mean embedding is the average feature vector,
The identity is the reproducing property moved inside an expectation (Smola, Gretton, Song & Schölkopf, 2007): one inner product with computes the expectation of any function in the RKHS. A sample gives the empirical embedding .
| Kernel | What records |
|---|---|
| linear, | the mean |
| polynomial, | the mean and the second moments |
| polynomial, | all moments up to order |
| Gaussian RBF | the whole distribution: is blurred by a Gaussian, and the blur can be undone |
and is the Laplace distribution with mean 0 and variance 1. For which kernel is ?
- The linear kernel
- The polynomial kernel
- The Gaussian RBF kernel
- None of them, since the two distributions share their mean and variance
Show the answer
C. The Gaussian RBF kernel
The Gaussian kernel is characteristic, so distinct distributions have distinct embeddings. The other two embeddings record only moments up to order 1 or 2, where these distributions agree; they first differ in the fourth moment (kurtosis 3 against 6).
The maximum mean discrepancy
Move the reproducing property inside both expectations:
By Cauchy–Schwarz the supremum over the unit ball is attained by the normalized witness function, and equals the distance between the embeddings:
Expand the square and use , with and all independent. Only kernel evaluations are needed:
Replace each expectation by an average over distinct pairs. Leaving out the terms makes the estimator unbiased (a U-statistic); keeping them gives the plug-in , which is biased upward. The cost is kernel evaluations.
The witness function shows where the distributions differ. With a Gaussian kernel it is the difference of two smoothed densities: positive where puts more mass, negative where does. Its empirical version, a difference of two kernel sums, is worth plotting whenever a test rejects.
Compare with using the Gaussian kernel . For and independent, . What is ?
Show the answer
0.18
and , so . As the means separate it approaches . The value depends on the kernel's length scale, which is why MMD values are compared within one kernel, never across kernels.
The kernel two-sample test
Given samples and , test against by rejecting when exceeds a threshold. The difficulty is the threshold: the statistic's null distribution is not simple.
The null limit depends on the unknown , so practical tests simulate the null instead. Pool the points, reassign the labels "from " and "from " at random times, and recompute the statistic each time. Under the pooled sample is exchangeable, so the observed statistic is just one more draw from this permutation distribution, and
gives a test whose level is at most for every sample size, every kernel and every dimension: exact, not asymptotic. Any data-dependent choice must respect the symmetry. The median heuristic, which sets the Gaussian length scale to the median distance between points of the pooled sample (Gretton et al., 2012), ignores the labels and is safe; tuning the kernel to make this sample look different is not, and needs a separate split of the data.
import numpy as np
def mmd2_u(K, m):
# K: Gram matrix of the pooled sample; its first m rows are X, the rest Y
n = len(K) - m
Kxx, Kyy, Kxy = K[:m, :m], K[m:, m:], K[:m, m:]
return ((Kxx.sum() - np.trace(Kxx)) / (m * (m - 1))
+ (Kyy.sum() - np.trace(Kyy)) / (n * (n - 1))
- 2 * Kxy.mean())
def mmd_permutation_test(X, Y, B=1000, seed=0):
Z = np.vstack([X, Y])
sq = ((Z[:, None, :] - Z[None, :, :]) ** 2).sum(-1)
ell = np.median(np.sqrt(sq[sq > 0])) # median heuristic: label-blind
K = np.exp(-sq / (2 * ell**2)) # Gaussian kernel, computed once
m, rng = len(X), np.random.default_rng(seed)
stat = mmd2_u(K, m)
null = [mmd2_u(K[np.ix_(p, p)], m) for p in (rng.permutation(len(Z)) for _ in range(B))]
return stat, (1 + np.sum(np.array(null) >= stat)) / (1 + B)A complete kernel two-sample test. The Gram matrix is computed once; each permutation only relabels its rows and columns, so the test costs . The unbiased statistic can be slightly negative when .
Independence, and the MMD at work
and are independent exactly when the joint distribution equals the product of its marginals, . Embed both sides with the product kernel and measure the MMD between them: the result is the Hilbert–Schmidt independence criterion (Gretton, Bousquet, Smola & Schölkopf, 2005),
the squared Hilbert–Schmidt norm of the cross-covariance operator between the two feature spaces. With characteristic kernels on both variables, such as Gaussians, if and only if : it detects nonlinear dependence that correlation misses. Its plug-in estimate is , with and the Gram matrices of the and the and ; a permutation test shuffles the against the (Gretton et al., 2008).
Where the MMD earns its keep:
- Detecting distribution shift. Compare training inputs with recent production inputs. In a large empirical study, Rabanser, Günnemann & Lipton (2019) found that two-sample tests applied to the outputs of a pretrained classifier, used to reduce the dimension first, detected shift best (Covariate, Label & Concept Shift).
- Training generative models. A generator can be trained to minimize the MMD between its samples and the data, with no discriminator: generative moment matching networks (Li, Swersky & Zemel, 2015; Dziugaite, Roy & Ghahramani, 2015). MMD GANs learn the kernel adversarially (Li, Chang, Cheng, Yang & Póczos, 2017).
- Evaluating generative models. The Kernel Inception Distance is a squared MMD between features of real and generated images (Bińkowski, Sutherland, Arbel & Gretton, 2018).
- Domain adaptation. Deep adaptation networks add an MMD penalty, with several kernels, that pulls the feature distributions of a source and a target domain together (Long, Cao, Wang & Jordan, 2015).
Key takeaways
- The kernel mean embedding turns a distribution into a point of the RKHS, with . Characteristic kernels (Gaussian, Laplacian, Matérn: full Fourier support) make the embedding injective.
- , and has an unbiased U-statistic estimator costing .
- Under the statistic is a degenerate U-statistic of order with an infinite chi-squared-mixture limit; permutation thresholds give exact level for any sample size, and a characteristic kernel makes the test consistent against every alternative.
- HSIC, the MMD between a joint distribution and the product of its marginals, detects any dependence with characteristic kernels; energy distance and distance covariance are special cases. Uses include shift detection, MMD-trained generators, generator evaluation and domain adaptation; power falls in high dimension, and kernel choice matters.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
With the linear kernel , what is ?
- Always zero
- The distance between the means,
- The Kullback–Leibler divergence between and
- The difference between the two variances
Show the answer
B. The distance between the means,
The linear kernel's features are the inputs themselves, so is the mean and the MMD is the Euclidean distance between the means. It is blind to every other difference, which is why characteristic kernels are needed.
Why does the unbiased estimator leave out the terms and ?
- To save computation
- Because does not estimate for independent copies; keeping these terms biases the estimate upward, so it is positive even when
- Because for every kernel
- Because the diagonal makes the Gram matrix singular
Show the answer
B. Because does not estimate for independent copies; keeping these terms biases the estimate upward, so it is positive even when
needs two independent draws. A diagonal term pairs a point with itself (for the Gaussian kernel it always equals 1), so including the diagonal adds a positive bias of order . The plug-in therefore has a positive expectation even for two samples from the same distribution, where the unbiased statistic averages exactly zero.
What guarantees that the permutation MMD test has level ?
- The central limit theorem, once and are large
- The characteristic property of the Gaussian kernel
- Gaussian data
- Exchangeability: under every relabeling of the pooled sample is equally likely, whatever the sample size, kernel or dimension
Show the answer
D. Exchangeability: under every relabeling of the pooled sample is equally likely, whatever the sample size, kernel or dimension
If , all points are i.i.d., so the observed split is a uniformly random one among all relabelings, and the observed statistic is exchangeable with the permuted ones. This makes the level exact in finite samples, provided the kernel was not chosen by looking at the labels.
The population HSIC between and , computed with Gaussian kernels on both, is zero. What follows?
- and are independent
- and are uncorrelated, but may still be dependent
- Nothing, because HSIC can vanish for dependent variables with any kernel
- and are equal in distribution
Show the answer
A. and are independent
HSIC is the MMD between and ; with characteristic kernels on both variables it vanishes only when the two coincide, which is independence.
Further reading
- A. Gretton, K. M. Borgwardt, M. J. Rasch, B. Schölkopf & A. Smola, "A kernel two-sample test," Journal of Machine Learning Research 13, 723–773 (2012).
- A. Smola, A. Gretton, L. Song & B. Schölkopf, "A Hilbert space embedding for distributions," Algorithmic Learning Theory (ALT 2007), 13–31 (Springer, 2007).
- B. K. Sriperumbudur, A. Gretton, K. Fukumizu, B. Schölkopf & G. R. G. Lanckriet, "Hilbert space embeddings and metrics on probability measures," Journal of Machine Learning Research 11, 1517–1561 (2010).
- A. Gretton, O. Bousquet, A. Smola & B. Schölkopf, "Measuring statistical dependence with Hilbert-Schmidt norms," Algorithmic Learning Theory (ALT 2005), 63–77 (Springer, 2005).
- K. Muandet, K. Fukumizu, B. Sriperumbudur & B. Schölkopf, "Kernel mean embedding of distributions: a review and beyond," Foundations and Trends in Machine Learning 10(1–2), 1–141 (2017).