神经网络表征相似度度量 CKA:google-research representation_similarity 参考实现与原理解析

原创2026-09-21 09:40:511,424 阅读
文章标签:人工智能深度学习NLP计算机视觉强化学习

神经网络表征相似度度量 CKA:google-research representation_similarity 参考实现与原理解析

本篇文章围绕 google-research 仓库中 representation_similarity 目录及其演示 Notebook,系统讲解 ICML 2019 论文《Similarity of Neural Network Representations Revisited》配套的 CKA(Centered Kernel Alignment,中心核对齐)参考实现。读完本文,你将掌握 CKA 的数学原理、两种等价的线性核计算方式、RBF 核带宽的设定技巧、去偏(debiased)估计的实现细节,以及 CKA 与 CCA 在不变性上的本质差异,并能在 Colab 或本机 Jupyter 中完整复现全部演示结果。

一、目录概览:一个轻量的 CKA 演示与参考实现

representation_similarity 目录是 google-research 仓库中的一个独立子目录,其中只包含两个文件:

README 明确指出,本目录存放的是以下论文的 demonstration/reference code(演示/参考代码):

Kornblith, S., Norouzi, M., Lee, H. & Hinton, G. (2019). Similarity of Neural Network Representations Revisited. Proceedings of the 36th International Conference on Machine Learning, in PMLR 97:3519–3529.(论文编号 arXiv:1905.00414)

也就是说,该目录并不依赖 TensorFlow/PyTorch 等重型框架,而是用纯 NumPy 实现 CKA 度量本身,定位是"演示 + 参考",便于研究者直接阅读、验证和迁移到自己的表征比较流程中。从实现上看,全部代码仅调用 numpy 标准 API,依赖面极小;Notebook 元数据中声明的是 Python 2 内核(kernelspec: python2,属于历史遗留),但代码未使用 Python 2 专属语法,可平滑运行在主流 Python 3 环境。

二、快速开始:两种运行方式

方式一:Google Colab 云端运行(推荐)

README 顶部提供了在 Google Colab 中一键打开该 Notebook 的入口(即 README 中的 "To launch the Colab, click here" 链接)。点击后在云端浏览器中即可直接按顺序执行全部单元格,无需在本地安装任何环境。

方式二:本机 Jupyter 运行

本目录没有 requirements.txt 等额外配置文件,依赖面极小(仅 numpy)。在仓库根目录执行:

pip install numpy jupyter
jupyter notebook representation_similarity/Demo.ipynb

打开后按顺序运行单元格即可复现教程中全部结果。由于数据生成使用了固定随机种子(见下文第三节),每次运行得到的数值输出与本文记录一致。

三、核心原理:从 Gram 矩阵到 CKA

CKA(中心核对齐)的基本思路是:用两个表征各自内部的**样本间相似性矩阵(Gram 矩阵/核矩阵)**来衡量两组特征空间的对齐程度,而不是直接比较特征坐标。这样做的好处在于,Gram 矩阵只关心样本间的内积结构,天然不依赖具体的特征坐标基。

3.1 线性核与 RBF 核的 Gram 矩阵

代码首先提供两个核函数实现:

def gram_linear(x):
  """Compute Gram (kernel) matrix for a linear kernel.

  Args:
    x: A num_examples x num_features matrix of features.

  Returns:
    A num_examples x num_examples Gram matrix of examples.
  """
  return x.dot(x.T)

gram_linear 计算线性核矩阵 K = X·Xᵀ,形状为 num_examples × num_examples,即样本两两之间的内积。

def gram_rbf(x, threshold=1.0):
  """Compute Gram (kernel) matrix for an RBF kernel.

  Args:
    x: A num_examples x num_features matrix of features.
    threshold: Fraction of median Euclidean distance to use as RBF kernel
      bandwidth. (This is the heuristic we use in the paper. There are other
      possible ways to set the bandwidth; we didn't try them.)

  Returns:
    A num_examples x num_examples Gram matrix of examples.
  """
  dot_products = x.dot(x.T)
  sq_norms = np.diag(dot_products)
  sq_distances = -2 * dot_products + sq_norms[:, None] + sq_norms[None, :]
  sq_median_distance = np.median(sq_distances)
  return np.exp(-sq_distances / (2 * threshold ** 2 * sq_median_distance))

gram_rbf 实现 RBF(径向基)核。值得注意的实现细节:

  • 平方距离矩阵通过恒等式 ‖a - b‖² = ‖a‖² + ‖b‖² - 2aᵀb 一次向量化算得,即 -2·XXᵀ + diag 范数扩展,避免显式双重循环;
  • 带宽(bandwidth)采用论文中的启发式设定:取平方距离矩阵的中位数 sq_median_distance,再乘上参数 threshold(threshold 的语义是"以中位欧氏距离的多少倍作为带宽")。代码注释明确说明:"这是我们在论文中使用的启发式方法,我们没有尝试其他设定带宽的方式";
  • 默认 threshold=1.0,教程中则使用了 threshold=0.5,对应"带宽取距离矩阵中位距离的 1/2"。

3.2 核矩阵的中心化

在计算对齐度之前,需要先对 Gram 矩阵做中心化(等价于先对核诱导的特征空间做中心化):

def center_gram(gram, unbiased=False):
  """Center a symmetric Gram matrix.

  This is equvialent to centering the (possibly infinite-dimensional) features
  induced by the kernel before computing the Gram matrix.

  Args:
    gram: A num_examples x num_examples symmetric matrix.
    unbiased: Whether to adjust the Gram matrix in order to compute an unbiased
      estimate of HSIC. Note that this estimator may be negative.

  Returns:
    A symmetric matrix with centered columns and rows.
  """
  if not np.allclose(gram, gram.T):
    raise ValueError('Input must be a symmetric matrix.')
  gram = gram.copy()

  if unbiased:
    # This formulation of the U-statistic, from Szekely, G. J., & Rizzo, M.
    # L. (2014). Partial distance correlation with methods for dissimilarities.
    # The Annals of Statistics, 42(6), 2382-2412, seems to be more numerically
    # stable than the alternative from Song et al. (2007).
    n = gram.shape[0]
    np.fill_diagonal(gram, 0)
    means = np.sum(gram, 0, dtype=np.float64) / (n - 2)
    means -= np.sum(means) / (2 * (n - 1))
    gram -= means[:, None]
    gram -= means[None, :]
    np.fill_diagonal(gram, 0)
  else:
    means = np.mean(gram, 0, dtype=np.float64)
    means -= np.mean(means) / 2
    gram -= means[:, None]
    gram -= means[None, :]

  return gram

center_gram 的要点:

  • 首先校验输入必须是对称矩阵,否则抛出 ValueError('Input must be a symmetric matrix.');
  • unbiased=False(默认)时使用标准的均值中心化;
  • unbiased=True 时采用 U 统计量形式:代码注释指出,该公式取自 Székely & Rizzo(2014)关于偏距离相关的论文,比 Song et al.(2007)的替代形式在数值上更稳定;同时注释明确警告:"该估计量可能为负"。

3.3 CKA 定义:归一化的 HSIC

有了中心化后的 Gram 矩阵,CKA 的计算就非常简洁:

def cka(gram_x, gram_y, debiased=False):
  """Compute CKA.

  Args:
    gram_x: A num_examples x num_examples Gram matrix.
    gram_y: A num_examples x num_examples Gram matrix.
    debiased: Use unbiased estimator of HSIC. CKA may still be biased.

  Returns:
    The value of CKA between X and Y.
  """
  gram_x = center_gram(gram_x, unbiased=debiased)
  gram_y = center_gram(gram_y, unbiased=debiased)

  # Note: To obtain HSIC, this should be divided by (n-1)**2 (biased variant) or
  # n*(n-3) (unbiased variant), but this cancels for CKA.
  scaled_hsic = gram_x.ravel().dot(gram_y.ravel())

  normalization_x = np.linalg.norm(gram_x)
  normalization_y = np.linalg.norm(gram_y)
  return scaled_hsic / (normalization_x * normalization_y)

数学上,CKA 定义为:

CKA(K, L) = HSIC(K, L) / √(HSIC(K, K) · HSIC(L, L))

实现中用 Frobenius 内积 ⟨vec(Gx), vec(Gy)⟩ 计算(未归一化的)HSIC 分子,用两个 Gram 矩阵的 Frobenius 范数做归一化。代码注释特别说明:严格意义上的 HSIC 需要再除以 (n-1)²(有偏变体)或 n·(n-3)(无偏变体),但该因子在 CKA 的分子分母中会抵消,因此实现中直接省略。debiased=True 时用 HSIC 的无偏估计量替代分子分母中的有偏估计量,注释同时提醒"CKA 本身可能仍是有偏的"。

3.4 线性 CKA 的特征空间快速版本

当特征数少于样本数时,基于 Gram 矩阵(n × n)的计算开销大于基于特征内积(d × d)的计算。Notebook 利用了如下恒等式:

⟨vec(XXᵀ), vec(YYᵀ)⟩ = ‖YᵀX‖²_F

即"样本间内积的相似度"等价于"特征间内积的 Frobenius 范数平方"。由此给出线性 CKA 的特征空间版本:

def _debiased_dot_product_similarity_helper(
    xty, sum_squared_rows_x, sum_squared_rows_y, squared_norm_x, squared_norm_y,
    n):
  """Helper for computing debiased dot product similarity (i.e. linear HSIC)."""
  # This formula can be derived by manipulating the unbiased estimator from
  # Song et al. (2007).
  return (
      xty - n / (n - 2.) * sum_squared_rows_x.dot(sum_squared_rows_y)
      + squared_norm_x * squared_norm_y / ((n - 1) * (n - 2)))


def feature_space_linear_cka(features_x, features_y, debiased=False):
  """Compute CKA with a linear kernel, in feature space.

  This is typically faster than computing the Gram matrix when there are fewer
  features than examples.

  Args:
    features_x: A num_examples x num_features matrix of features.
    features_y: A num_examples x num_features matrix of features.
    debiased: Use unbiased estimator of dot product similarity. CKA may still be
      biased. Note that this estimator may be negative.

  Returns:
    The value of CKA between X and Y.
  """
  features_x = features_x - np.mean(features_x, 0, keepdims=True)
  features_y = features_y - np.mean(features_y, 0, keepdims=True)

  dot_product_similarity = np.linalg.norm(features_x.T.dot(features_y)) ** 2
  normalization_x = np.linalg.norm(features_x.T.dot(features_x))
  normalization_y = np.linalg.norm(features_y.T.dot(features_y))

  if debiased:
    n = features_x.shape[0]
    # Equivalent to np.sum(features_x ** 2, 1) but avoids an intermediate array.
    sum_squared_rows_x = np.einsum('ij,ij->i', features_x, features_x)
    sum_squared_rows_y = np.einsum('ij,ij->i', features_y, features_y)
    squared_norm_x = np.sum(sum_squared_rows_x)
    squared_norm_y = np.sum(sum_squared_rows_y)

    dot_product_similarity = _debiased_dot_product_similarity_helper(
        dot_product_similarity, sum_squared_rows_x, sum_squared_rows_y,
        squared_norm_x, squared_norm_y, n)
    normalization_x = np.sqrt(_debiased_dot_product_similarity_helper(
        normalization_x ** 2, sum_squared_rows_x, sum_squared_rows_x,
        squared_norm_x, squared_norm_x, n))
    normalization_y = np.sqrt(_debiased_dot_product_similarity_helper(
        normalization_y ** 2, sum_squared_rows_y, sum_squared_rows_y,
        squared_norm_y, squared_norm_y, n))

  return dot_product_similarity / (normalization_x * normalization_y)

实现要点:

  • 先对特征矩阵按列做中心化(减列均值),与 center_gram 的默认分支等价;
  • 分子 ‖XᵀY‖²_F、分母范数均以 d × d 的矩阵运算完成,特征数 d 远小于样本数 n 时明显更快;
  • debiased=True 时,利用 Song et al.(2007)无偏估计量推导出的辅助公式 _debiased_dot_product_similarity_helper 对分子、分母逐项修正;计算行平方和时用 np.einsum('ij,ij->i', ...) 技巧,避免产生中间大数组(代码注释明确说明这一点);
  • Notebook 中对"基于样本"与"基于特征"两种线性 CKA 做了等价性断言(np.testing.assert_almost_equal),验证两者数学等价。

四、分步实战教程与预期输出

4.1 构造演示数据

np.random.seed(1337)
X = np.random.randn(100, 10)
Y = np.random.randn(100, 10) + X

教程生成 100 × 10 的随机特征矩阵:Y 在 X 的基础上叠加噪声(+ X),因此两者之间存在可控的相关结构。固定随机种子 1337 保证结果可复现。

4.2 线性 CKA:样本视角 vs 特征视角

cka_from_examples = cka(gram_linear(X), gram_linear(Y))
cka_from_features = feature_space_linear_cka(X, Y)

print('Linear CKA from Examples: {:.5f}'.format(cka_from_examples))
print('Linear CKA from Features: {:.5f}'.format(cka_from_features))
np.testing.assert_almost_equal(cka_from_examples, cka_from_features)

预期输出:

Linear CKA from Examples: 0.55761
Linear CKA from Features: 0.55761

两条路径得到完全一致的数值,并由 np.testing.assert_almost_equal 自动验证等价性。

4.3 RBF 核 CKA

rbf_cka = cka(gram_rbf(X, 0.5), gram_rbf(Y, 0.5))
print('RBF CKA: {:.5f}'.format(rbf_cka))

预期输出:

RBF CKA: 0.65483

这里带宽取"中位距离的 1/2"(threshold=0.5),非线性核捕获了线性核无法看到的更高阶结构,因此数值高于线性 CKA。

4.4 去偏(Debiased)线性 CKA

当样本数较少时,有偏估计可能引入系统性偏差。代码通过将 HSIC 视为 U 统计量(Song et al., 2007),并用无偏估计替换分子分母中的有偏项,得到偏差更小的 CKA 变体:

cka_from_examples_debiased = cka(gram_linear(X), gram_linear(Y), debiased=True)
cka_from_features_debiased = feature_space_linear_cka(X, Y, debiased=True)

print('Linear CKA from Examples (Debiased): {:.5f}'.format(
    cka_from_examples_debiased))
print('Linear CKA from Features (Debiased): {:.5f}'.format(
    cka_from_features_debiased))

np.testing.assert_almost_equal(cka_from_examples_debiased,
                               cka_from_features_debiased)

预期输出:

Linear CKA from Examples (Debiased): 0.51346
Linear CKA from Features (Debiased): 0.51346

同样地,样本视角与特征视角的去偏结果一致并被断言验证。注意:无偏的 HSIC 估计量可能为负,因此去偏后的 CKA 数值也可能出现负值,这是该变体的已知特性。

五、CKA 与 CCA 的对比与不变性验证

5.1 平均平方 CCA 相关(R²_CCA)

Notebook 同时给出经典对比方法 CCA(典型相关分析)的实现:

def cca(features_x, features_y):
  """Compute the mean squared CCA correlation (R^2_{CCA}).

  Args:
    features_x: A num_examples x num_features matrix of features.
    features_y: A num_examples x num_features matrix of features.

  Returns:
    The mean squared CCA correlations between X and Y.
  """
  qx, _ = np.linalg.qr(features_x)  # Or use SVD with full_matrices=False.
  qy, _ = np.linalg.qr(features_y)
  return np.linalg.norm(qx.T.dot(qy)) ** 2 / min(
      features_x.shape[1], features_y.shape[1])

print('Mean Squared CCA Correlation: {:.5f}'.format(cca(X, Y)))

实现采用 QR 分解(注释提示也可用 SVD with full_matrices=False)得到两组特征的规范正交基,再计算 ‖QxᵀQy‖² 并除以特征维度较小者,得到平均平方 CCA 相关。预期输出:

Mean Squared CCA Correlation: 0.54312

5.2 不变性验证

Notebook 最后通过一组断言,直观验证 CKA 与 CCA 在变换下的行为差异(这是论文反复强调的关键性质):

transform = np.random.randn(10, 10)
_, orthogonal_transform = np.linalg.eigh(transform.T.dot(transform))

# CKA is invariant only to orthogonal transformations.
np.testing.assert_almost_equal(
    feature_space_linear_cka(X, Y),
    feature_space_linear_cka(X.dot(orthogonal_transform), Y))
np.testing.assert_(not np.isclose(
    feature_space_linear_cka(X, Y),
    feature_space_linear_cka(X.dot(transform), Y)))

# CCA is invariant to any invertible linear transform.
np.testing.assert_almost_equal(cca(X, Y), cca(X.dot(orthogonal_transform), Y))
np.testing.assert_almost_equal(cca(X, Y), cca(X.dot(transform), Y))

# Both CCA and CKA are invariant to isotropic scaling.
np.testing.assert_almost_equal(cca(X, Y), cca(X * 1.337, Y))
np.testing.assert_almost_equal(
    feature_space_linear_cka(X, Y),
    feature_space_linear_cka(X * 1.337, Y))

从这组测试可以归纳出代码验证的结论:

变换类型 线性 CKA CCA
正交变换(orthogonal) 不变(断言通过) 不变
一般可逆线性变换(invertible linear) 会改变(assert not np.isclose 通过) 不变
各向同性缩放(isotropic scaling) 不变 不变

这意味着:CKA 只对正交变换不变,而 CCA 对任意可逆线性变换不变。前者保证了 CKA 对神经元排列等"合理重排"鲁棒,后者则是经典相关分析的一贯特性。理解这一差异,有助于在实际使用中正确解读两类指标的变化含义。

六、使用建议与注意事项

综合源码 docstring 与教程注释,使用本参考实现时建议注意以下几点:

  1. 按数据规模选择计算路径:当特征数小于样本数时,用 feature_space_linear_cka 直接基于特征内积计算线性 CKA,避免构造 n × n 的 Gram 矩阵;反之(特征维度过高、样本数较少)则用 gram_linear + cka 的 Gram 路径。两条路径数学等价,教程已用断言验证。
  2. RBF 带宽的设置:gram_rbf 的 threshold 参数语义是"中位欧氏距离的倍数",默认 1.0,论文中使用的启发式即本实现;代码注释也坦承"存在其他设置带宽的方式,作者并未尝试",说明该启发式是论文场景下的经验选择。
  3. 去偏估计量的使用场景:样本数较小时可尝试 debiased=True 以减小偏差;但无偏 HSIC 估计量可能为负,导致去偏 CKA 出现负值,属正常现象;且"去偏"只针对 HSIC,CKA 本身仍可能是有偏的。
  4. 输入合法性校验:center_gram 会校验 Gram 矩阵的对称性,非对称输入会抛出 ValueError,这在自定义核矩阵时需要留意。
  5. 演示代码的定位:本目录是论文的"演示/参考实现",聚焦 CKA 度量本身(纯 NumPy),并非端到端的深度网络训练框架;将 CKA 接入真实模型时,通常需要自行完成"提取各层激活特征 → 组织成 num_examples × num_features 矩阵 → 调用上述函数"的管线。

七、引用方式

README 与 Notebook 均给出了论文的标准引用信息,供在学术工作中引用:

@inproceedings{pmlr-v97-kornblith19a,
  title = {Similarity of Neural Network Representations Revisited},
  author = {Kornblith, Simon and Norouzi, Mohammad and Lee, Honglak and Hinton, Geoffrey},
  booktitle = {Proceedings of the 36th International Conference on Machine Learning},
  pages = {3519--3529},
  year = {2019},
  volume = {97},
  month = {09--15 Jun},
  publisher = {PMLR}
}

八、延伸阅读指引

本文覆盖了该目录的全部内容——从论文背景、运行方式,到 CKA 的核矩阵构造、中心化、去偏估计、特征空间加速路径、与 CCA 的对比及不变性验证。你可以直接对照 Demo.ipynb 逐格运行,将其中的函数作为模块复用到自己的表征相似度研究中。

登录后查看全文
google-research