Simple Algorithm
Machine Learning · Convergence · 28 min

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 μP=EP[k(X,⋅)]\mu_P=\E_P[k(X,\cdot)], show that ⟨f,μP⟩=EPf\langle f,\mu_P\rangle=\E_Pf, and explain when the embedding is injective (characteristic kernels).
  • Derive MMD2=Ek(X,X′)+Ek(Y,Y′)−2Ek(X,Y)\mathrm{MMD}^2=\E k(X,X')+\E k(Y,Y')-2\E k(X,Y), 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 kk be a kernel with RKHS H\mathcal H and feature map φ(x)=k(x,⋅)\varphi(x)=k(x,\cdot). For a distribution PP with EPk(X,X)<∞\E_P\sqrt{k(X,X)}<\infty, the kernel mean embedding is the average feature vector,

μP=EX∼P[k(X,⋅)]∈H,so that⟨f,μP⟩H=EP[f(X)]  for every f∈H.\mu_P=\E_{X\sim P}\big[k(X,\cdot)\big]\in\mathcal H,\qquad\text{so that}\qquad\langle f,\mu_P\rangle_{\mathcal H}=\E_P\big[f(X)\big]\ \text{ for every }f\in\mathcal H.

The identity is the reproducing property moved inside an expectation (Smola, Gretton, Song & Schölkopf, 2007): one inner product with μP\mu_P computes the expectation of any function in the RKHS. A sample gives the empirical embedding μ^P=1m∑i=1mk(xi,⋅)\hat\mu_P=\frac1m\sum_{i=1}^mk(x_i,\cdot).

KernelWhat μP\mu_P records
linear, x⊤z\mathbf x^\top\mathbf zthe mean EP[X]\E_P[X]
polynomial, (1+x⊤z)2(1+\mathbf x^\top\mathbf z)^2the mean and the second moments EP[XX⊤]\E_P[XX^\top]
polynomial, (1+x⊤z)p(1+\mathbf x^\top\mathbf z)^pall moments up to order pp
Gaussian RBFthe whole distribution: μP(t)=EPe−∥X−t∥2/(2ℓ2)\mu_P(\mathbf t)=\E_Pe^{-\norm{X-\mathbf t}^2/(2\ell^2)} is PP blurred by a Gaussian, and the blur can be undone
The embedding keeps exactly the information the kernel's features can see. The Gaussian blur is invertible because the Gaussian's Fourier transform never vanishes.
Check your understanding

P=N(0,1)P=\mathcal N(0,1) and QQ is the Laplace distribution with mean 0 and variance 1. For which kernel is ∥μP−μQ∥H>0\norm{\mu_P-\mu_Q}_{\mathcal H}>0?

  1. The linear kernel xzxz
  2. The polynomial kernel (1+xz)2(1+xz)^2
  3. The Gaussian RBF kernel
  4. 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

DerivationFrom the supremum to a formula
  1. EPf(X)−EQf(Y)=⟨f,μP⟩−⟨f,μQ⟩=⟨f, μP−μQ⟩H\E_P f(X)-\E_Q f(Y)=\langle f,\mu_P\rangle-\langle f,\mu_Q\rangle=\langle f,\,\mu_P-\mu_Q\rangle_{\mathcal H}

    Move the reproducing property inside both expectations:

  2. f⋆=μP−μQ∥μP−μQ∥H,sup⁡∥f∥≤1⟨f,μP−μQ⟩=∥μP−μQ∥Hf^\star=\frac{\mu_P-\mu_Q}{\norm{\mu_P-\mu_Q}_{\mathcal H}},\qquad\sup_{\norm f\le1}\langle f,\mu_P-\mu_Q\rangle=\norm{\mu_P-\mu_Q}_{\mathcal H}

    By Cauchy–Schwarz the supremum over the unit ball is attained by the normalized witness function, and equals the distance between the embeddings:

  3. MMD2(P,Q)=E k(X,X′)+E k(Y,Y′)−2 E k(X,Y)\mathrm{MMD}^2(P,Q)=\E\,k(X,X')+\E\,k(Y,Y')-2\,\E\,k(X,Y)

    Expand the square and use ⟨μP,μQ⟩=E k(X,Y)\langle\mu_P,\mu_Q\rangle=\E\,k(X,Y), with X,X′∼PX,X'\sim P and Y,Y′∼QY,Y'\sim Q all independent. Only kernel evaluations are needed:

  4. MMD^u2=∑i≠jk(xi,xj)m(m−1)+∑i≠jk(yi,yj)n(n−1)−2mn∑i=1m∑j=1nk(xi,yj)\widehat{\mathrm{MMD}}{}^2_u=\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}{mn}\sum_{i=1}^m\sum_{j=1}^nk(x_i,y_j)

    Replace each expectation by an average over distinct pairs. Leaving out the i=ji=j terms makes the estimator unbiased (a U-statistic); keeping them gives the plug-in ∥μ^P−μ^Q∥2\norm{\hat\mu_P-\hat\mu_Q}^2, which is biased upward. The cost is O((m+n)2)\order{(m+n)^2} kernel evaluations.

The witness function f⋆(t)∝EPk(X,t)−EQk(Y,t)f^\star(\mathbf t)\propto\E_Pk(X,\mathbf t)-\E_Qk(Y,\mathbf t) shows where the distributions differ. With a Gaussian kernel it is the difference of two smoothed densities: positive where PP puts more mass, negative where QQ does. Its empirical version, a difference of two kernel sums, is worth plotting whenever a test rejects.

Predict before you look

Compare P=N(0,1)P=\mathcal N(0,1) with Q=N(1,1)Q=\mathcal N(1,1) using the Gaussian kernel e−(x−z)2/2e^{-(x-z)^2/2}. For X∼N(a,1)X\sim\mathcal N(a,1) and Y∼N(b,1)Y\sim\mathcal N(b,1) independent, E e−(X−Y)2/2=13e−(a−b)2/6\E\,e^{-(X-Y)^2/2}=\tfrac1{\sqrt3}e^{-(a-b)^2/6}. What is MMD2(P,Q)\mathrm{MMD}^2(P,Q)?

Show the answer

0.18

Ek(X,X′)=Ek(Y,Y′)=1/3≈0.577\E k(X,X')=\E k(Y,Y')=1/\sqrt3\approx0.577 and Ek(X,Y)=e−1/6/3≈0.489\E k(X,Y)=e^{-1/6}/\sqrt3\approx0.489, so MMD2=23(1−e−1/6)≈0.177\mathrm{MMD}^2=\tfrac2{\sqrt3}\big(1-e^{-1/6}\big)\approx0.177. As the means separate it approaches 2/3≈1.152/\sqrt3\approx1.15. 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 x1,…,xm∼Px_1,\dots,x_m\sim P and y1,…,yn∼Qy_1,\dots,y_n\sim Q, test H0:P=QH_0:P=Q against H1:P≠QH_1:P\ne Q by rejecting when MMD^u2\widehat{\mathrm{MMD}}{}^2_u exceeds a threshold. The difficulty is the threshold: the statistic's null distribution is not simple.

The null limit depends on the unknown PP, so practical tests simulate the null instead. Pool the m+nm+n points, reassign the labels "from PP" and "from QQ" at random BB times, and recompute the statistic each time. Under H0H_0 the pooled sample is exchangeable, so the observed statistic is just one more draw from this permutation distribution, and

p=1+#{b: Tb≥Tobs}1+Bp=\frac{1+\#\{b:\ T_b\ge T_{\text{obs}}\}}{1+B}

gives a test whose level is at most α\alpha 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.

python
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 O(B(m+n)2)\order{B(m+n)^2}. The unbiased statistic can be slightly negative when P=QP=Q.

Independence, and the MMD at work

XX and YY are independent exactly when the joint distribution equals the product of its marginals, PXY=PX⊗PYP_{XY}=P_X\otimes P_Y. Embed both sides with the product kernel k(x,x′) l(y,y′)k(x,x')\,l(y,y') and measure the MMD between them: the result is the Hilbert–Schmidt independence criterion (Gretton, Bousquet, Smola & Schölkopf, 2005),

HSIC=MMD2(PXY, PX⊗PY)=∥CXY∥HS2,\mathrm{HSIC}=\mathrm{MMD}^2\big(P_{XY},\,P_X\otimes P_Y\big)=\norm{C_{XY}}^2_{\mathrm{HS}},

the squared Hilbert–Schmidt norm of the cross-covariance operator between the two feature spaces. With characteristic kernels on both variables, such as Gaussians, HSIC=0\mathrm{HSIC}=0 if and only if X⊥ ⁣ ⁣ ⁣⊥YX\indep Y: it detects nonlinear dependence that correlation misses. Its plug-in estimate is 1n2tr⁡(KHLH)\frac1{n^2}\operatorname{tr}(KHLH), with KK and LL the Gram matrices of the xix_i and the yiy_i and H=I−1n11⊤H=I-\frac1n\mathbf 1\mathbf 1^\top; a permutation test shuffles the yiy_i against the xix_i (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 μP=EP[k(X,⋅)]\mu_P=\E_P[k(X,\cdot)] turns a distribution into a point of the RKHS, with ⟨f,μP⟩=EPf\langle f,\mu_P\rangle=\E_Pf. Characteristic kernels (Gaussian, Laplacian, Matérn: full Fourier support) make the embedding injective.
  • MMD(P,Q)=sup⁡∥f∥≤1(EPf−EQf)=∥μP−μQ∥\mathrm{MMD}(P,Q)=\sup_{\norm f\le1}(\E_Pf-\E_Qf)=\norm{\mu_P-\mu_Q}, and MMD2=Ek(X,X′)+Ek(Y,Y′)−2Ek(X,Y)\mathrm{MMD}^2=\E k(X,X')+\E k(Y,Y')-2\E k(X,Y) has an unbiased U-statistic estimator costing O((m+n)2)\order{(m+n)^2}.
  • Under H0H_0 the statistic is a degenerate U-statistic of order 1/m1/m 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.

Question 1

With the linear kernel k(x,z)=x⊤zk(\mathbf x,\mathbf z)=\mathbf x^\top\mathbf z, what is MMD(P,Q)\mathrm{MMD}(P,Q)?

  1. Always zero
  2. The distance between the means, ∥EP[X]−EQ[Y]∥\norm{\E_P[X]-\E_Q[Y]}
  3. The Kullback–Leibler divergence between PP and QQ
  4. The difference between the two variances
Show the answer

B. The distance between the means, ∥EP[X]−EQ[Y]∥\norm{\E_P[X]-\E_Q[Y]}

The linear kernel's features are the inputs themselves, so μP\mu_P 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.

Question 2

Why does the unbiased estimator MMD^u2\widehat{\mathrm{MMD}}{}^2_u leave out the terms k(xi,xi)k(x_i,x_i) and k(yj,yj)k(y_j,y_j)?

  1. To save computation
  2. Because k(xi,xi)k(x_i,x_i) does not estimate Ek(X,X′)\E k(X,X') for independent copies; keeping these terms biases the estimate upward, so it is positive even when P=QP=Q
  3. Because k(xi,xi)=0k(x_i,x_i)=0 for every kernel
  4. Because the diagonal makes the Gram matrix singular
Show the answer

B. Because k(xi,xi)k(x_i,x_i) does not estimate Ek(X,X′)\E k(X,X') for independent copies; keeping these terms biases the estimate upward, so it is positive even when P=QP=Q

Ek(X,X′)\E k(X,X') 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 1/m1/m. The plug-in ∥μ^P−μ^Q∥2\norm{\hat\mu_P-\hat\mu_Q}^2 therefore has a positive expectation even for two samples from the same distribution, where the unbiased statistic averages exactly zero.

Question 3

What guarantees that the permutation MMD test has level α\alpha?

  1. The central limit theorem, once mm and nn are large
  2. The characteristic property of the Gaussian kernel
  3. Gaussian data
  4. Exchangeability: under H0H_0 every relabeling of the pooled sample is equally likely, whatever the sample size, kernel or dimension
Show the answer

D. Exchangeability: under H0H_0 every relabeling of the pooled sample is equally likely, whatever the sample size, kernel or dimension

If P=QP=Q, all m+nm+n 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.

Question 4

The population HSIC between XX and YY, computed with Gaussian kernels on both, is zero. What follows?

  1. XX and YY are independent
  2. XX and YY are uncorrelated, but may still be dependent
  3. Nothing, because HSIC can vanish for dependent variables with any kernel
  4. XX and YY are equal in distribution
Show the answer

A. XX and YY are independent

HSIC is the MMD between PXYP_{XY} and PX⊗PYP_X\otimes P_Y; 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).