"""协方差特征分解,并用 sklearn 核对投影方向。""" import json import matplotlib.pyplot as plt import numpy as np # sklearn 的 PCA 只作独立核对,手算方向仍由 NumPy 的特征分解给出。 from sklearn.decomposition import PCA def main(): # 两列均为无单位评分。若单位不同,应另做标准化实验。 samples = np.array([[-3.0, -1], [-1, -2], [1, 0], [3, 3]]) # samples 形状为 (4, 2),axis=0 求每列均值,广播后逐行减去。 centered = samples - samples.mean(axis=0) # (2, 4) × (4, 2) 得到特征间的协方差矩阵,分母采用 n。 covariance = centered.T @ centered / len(samples) eigenvalues, basis = np.linalg.eigh(covariance) # eigh 的特征值默认升序。取最大特征值对应的单位向量。 direction = basis[:, -1].copy() if direction[0] < 0: direction *= -1 # 每个样本投影成 PC1 上的一个标量;外积将这四个坐标变回中心化平面上的点。 scores = centered @ direction reconstruction = np.outer(scores, direction) # 分子是 PC1 方向的方差。二维保留一维时,丢掉的方差等于平均平方重构误差。 ratio = eigenvalues[-1] / eigenvalues.sum() error = np.square(centered - reconstruction).sum() / len(samples) # sklearn 的 explained_variance_ 使用样本协方差,分母为 n-1。 library = PCA(n_components=1).fit(samples) np.testing.assert_allclose(abs(library.components_[0] @ direction), 1.0) np.testing.assert_allclose(library.explained_variance_ratio_[0], ratio) np.testing.assert_allclose(covariance, [[5.0, 3.5], [3.5, 3.5]]) np.testing.assert_allclose(error, eigenvalues[0]) # 圆点是中心化样本,叉号是投影,灰线长度衡量单个样本的重构偏差。 fig, ax = plt.subplots(figsize=(5.4, 4), layout="constrained") ax.scatter(*centered.T, label="Centered samples") ax.scatter(*reconstruction.T, marker="x", label="PC1 projections") for point, projection in zip(centered, reconstruction): ax.plot(*np.vstack((point, projection)).T, color="gray", linewidth=0.8) ax.set(xlabel="Feature 1", ylabel="Feature 2", aspect="equal") ax.legend() print("LAB_RESULT " + json.dumps({"ratio": ratio, "direction": direction.tolist(), "mse": error})) plt.show() if __name__ == "__main__": main()