蓝色天空.知识 · 实践 · 创造
我的收藏
AI 数学基础 教程目录 54章
课程介绍
AI 数学基础 / LEARN BY DOING

PCA 降维与可视化

用协方差特征分解从三个坐标提取前两个主成分,并量化重建误差。

学完这一章,你能够

  • 用协方差特征分解从三个坐标提取前两个主成分,并量化重建误差。

选择最能区分样本的方向

主成分分析将多列数值改用一组互相垂直的轴表示。想象一批沿传送带分布的包裹位置:散布最宽的方向能分辨较多位置差异。当厚度方向很窄时,可以把点投到平面,并量化丢失的差异。保留多少维由任务和测量尺度决定。

中心化、分解和投影

令 X 有 n 行样本和 d 列特征。逐列减均值,得 Xc。n 大于 1 时,样本协方差 C = XcᵀXc/(n−1)。对称矩阵 C 可分解为 VΛVᵀ。按特征值从大到小选 k 列 Vₖ,坐标 Z = XcVₖ。用 ZVₖᵀ 加回均值可得到原坐标的近似值。

第 i 个解释方差比例是 λᵢ 除以全部特征值之和。总方差为零时,这个比例没有定义。若变量量纲差别很大,应先说明是否标准化。特征向量整体变号时坐标也随之变号,重建和解释方差不变。

在固定输入上检查结果

本站用四个独立的正负号组合成三维点。样本协方差的特征值恰为 9、1、0.25,保留两维后解释 40/41,约 97.56% 的方差。对照图左侧显示原特征平面,右侧显示主成分坐标。用同一输入还会运行 scikit-learn 的独立实现作对照。

左图绘制中心化样本的前两列,右图绘制同一批样本的两个主成分坐标。
本站程序实际输出。按样本位置对照原特征平面和主成分坐标。

历史示例用固定种子的旧随机数接口和 300 个样本。按相同参数复算出的特征值约为 10.8773、0.0903、0.0406,前两维累计约 99.631%。能否舍去第三维还要看目标任务。对推荐评分表做低秩 SVD 时,中心化方式与缺失值处理需要单独设计。

PCA 的五种应用

用途步骤与适用范围
投影散点图将多列样本投到两个主成分坐标上,前两维比例小的时候还应检查剩余分布。
压缩输入用训练集拟合均值与投影,再对测试集应用同一变换。避免数据泄漏并实测预测效果。
低秩近似以低秩重建减弱部分小方差变化。任务相关信号也可能落在这些方向。
主成分重建把对齐图像展成行,以均值图和少数基图重建。高低维效果应在留出的图像上评估。
低秩评分模型中心化样本的 SVD 与 PCA 共享右奇异子空间。用户评分矩阵有缺项时,需要单独的建模处理。

从三维点得到主成分坐标和散点对照

含完整源码 · 108 行
展开查看收起
python
"""Compare a hand-written PCA with a library PCA and save the observed scatter plot."""
from hashlib import sha256
from itertools import product
import json
from pathlib import Path
import platform
import struct

import matplotlib
matplotlib.use("Agg")
from matplotlib import pyplot as plt
import numpy as np
import sklearn
from sklearn.decomposition import PCA


CASES = []


def record(name, operation, inputs, expected, actual):
    assert actual == expected, (name, expected, actual)
    CASES.append(dict(name=name, operation=operation, inputs=inputs,
                      expected=expected, actual=actual, passed=True))


def decompose(samples):
    mean = samples.mean(axis=0)
    centered = samples - mean
    covariance = centered.T @ centered / (len(samples) - 1)
    eigenvalues, axes = np.linalg.eigh(covariance)
    descending = np.argsort(eigenvalues)[::-1]
    return mean, centered, covariance, eigenvalues[descending], axes[:, descending]


def historical_eigenvalues():
    rng = np.random.RandomState(42)
    common = rng.standard_normal(300)
    draws = np.column_stack((3 * common + 0.3 * rng.standard_normal(300),
                             1.5 * common + 0.3 * rng.standard_normal(300),
                             0.2 * rng.standard_normal(300)))
    return decompose(draws)[3]


def main():
    signs = np.array(tuple(product((-1, 1), repeat=3)))
    x = signs * np.sqrt(7 / 8) * [3, 1, 0.5]
    rotation = np.array([[np.sqrt(.5), -np.sqrt(.5), 0],
                         [np.sqrt(.5), np.sqrt(.5), 0],
                         [0, 0, 1]])
    samples = x @ rotation.T + [12, 7, -3]
    mean, centered, covariance, eigvals, axes = decompose(samples)
    record("manual_center_and_covariance", "center each feature and divide cross-products by n-1",
           {"samples": 8, "features": 3}, [[12., 7., -3.], [0., 0., 0.], [[5., 4., 0.], [4., 5., 0.], [0., 0., .25]]],
           [np.round(mean, 8).tolist(), np.round(centered.mean(axis=0), 8).tolist(), np.round(covariance, 8).tolist()])
    projection = axes[:, :2]
    reduced = centered @ projection
    ratio = float(eigvals[:2].sum() / eigvals.sum())
    record("pca_two_components", "take the first two eigenvectors and project",
           {"samples": 8, "components": 2}, [[8, 2], [9., 1., .25], .97560976],
           [list(reduced.shape), np.round(eigvals, 8).tolist(), round(ratio, 8)])
    approx = reduced @ projection.T + mean
    residual = float(np.square(samples - approx).sum() / (len(samples) - 1))
    record("discarded_variance_matches_residual", "reconstruct from two coordinates and measure residual",
           {"kept": 2, "discarded": 1}, .25, round(residual, 8))
    restored = (centered @ axes) @ axes.T + mean
    record("reconstruct_at_full_rank", "project and reconstruct with all three axes",
           {"kept": 3}, True, bool(np.allclose(restored, samples)))
    opposite = projection * [-1, 1]
    record("component_sign_invariance", "flip a component axis and its projected coordinates",
           [-1, 1], True, bool(np.allclose((centered @ opposite) @ opposite.T + mean, approx)))
    fitted = PCA(n_components=2, svd_solver="full").fit(samples)
    record("sklearn_subspace_comparison", "fit library PCA and compare projection matrices and eigenvalues",
           {"components": 2, "solver": "full"}, [True, True],
           [bool(np.allclose(projection @ projection.T, fitted.components_.T @ fitted.components_)),
            bool(np.allclose(eigvals[:2], fitted.explained_variance_))])
    _, singular, _ = np.linalg.svd(centered, full_matrices=False)
    record("covariance_and_svd_agree", "convert singular values to sample variances",
           {"denominator": 7}, True, bool(np.allclose(singular ** 2 / (len(samples) - 1), eigvals)))
    old = historical_eigenvalues()
    record("historical_seeded_covariance", "reconstruct the parameterized historical random draw",
           {"seed": 42, "samples": 300}, [[10.877265, .09032, .040607], 99.631124],
           [np.round(old, 6).tolist(), round(float(old[:2].sum() / old.sum() * 100), 6)])
    output = Path(__file__).resolve().parent / "outputs/pca-view.png"
    output.parent.mkdir(exist_ok=True)
    fig, panels = plt.subplots(1, 2, figsize=(9, 3.9), layout="constrained")
    hue = np.where(signs[:, 0] > 0, "#136f7e", "#a95128")
    panels[0].scatter(centered[:, 0], centered[:, 1], c=hue, s=45)
    panels[0].set(title="Centered feature plane", xlabel="Feature 1", ylabel="Feature 2")
    panels[1].scatter(reduced[:, 0], reduced[:, 1], c=hue, s=45)
    panels[1].set(title="PCA coordinates", xlabel="Component 1", ylabel="Component 2")
    for panel in panels:
        panel.set(xlim=(-3.3, 3.3), ylim=(-3.3, 3.3), aspect="equal")
        panel.grid(alpha=.3)
    fig.savefig(output, dpi=100)
    plt.close(fig)
    data = output.read_bytes()
    record("pca_scatter_rendered", "render two scatter plots and verify PNG dimensions",
           {"points_per_panel": len(samples)}, [[900, 390], True],
           [list(struct.unpack(">II", data[16:24])), data.startswith(b"\x89PNG\r\n\x1a\n")])
    CASES[-1]["artifact"] = dict(path="outputs/pca-view.png", sha256=sha256(data).hexdigest(), bytes=len(data))
    print(json.dumps(dict(version=platform.python_version(), library_versions={
        "numpy": np.__version__, "sklearn": sklearn.__version__, "matplotlib": matplotlib.__version__}, cases=CASES)))


if __name__ == "__main__":
    main()

输出 8×2 主成分坐标和 900×390 散点对照图。两维解释方差约 97.56%。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

复跑实验

解压后按 README 运行自编程序。

下载本章实验包 (mbskycom202612a33.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:AI 数学基础

课程关联工程包(登记关联54章) · 含当前章节或实例 · mbskycom202612a33.zip

下载课程关联工程包:AI 数学基础

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a77.zip

常见错误与边界检查

  • 协方差特征值比较的是方差,结果随测量单位变化。
  • 低方差方向的删除会损失信息,保留维数按下游目标验证。

技术规范与官方资料

练习与参考解答

查看参考解答

该特征空间内可以选取不同的标准正交基,单根轴不唯一。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习