蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

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

PYTHONWindows、Python 3.12.14。numpy 2.5.4;sklearn 1.9.1;matplotlib 3.11.2。pca-projection.py
pca-projection.py108 行
"""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()

本例需在 Windows、Python 3.12.14。numpy 2.5.4;sklearn 1.9.1;matplotlib 3.11.2。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows、Python 3.12.14。numpy 2.5.4;sklearn 1.9.1;matplotlib 3.11.2。

入口文件:projects/ai-math-pca-visualization-lab/pca-projection.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 pca-projection.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows、Python 3.12.14。numpy 2.5.4;sklearn 1.9.1;matplotlib 3.11.2。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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