Wine:降维是否有助于分类?#

目标:完成一次有独立测试集的比较,理解 PCA 原理、参数选择与数据泄漏。先阅读 PCA 正文。

数据和运行条件#

采用 scikit-learn 内置 Wine 数据:178 个样本、13 个数值特征、3 个类别。数据随库提供,无需联网下载。使用 CPU,不需要 GPU 或付费接口。

下载文件与安装依赖#

先下载 完整学生实验包 ai-course-examples.zip,解压到自己的电脑。依赖文件 requirements-examples.txt 位于解压后的最外层,与 README.md、examples/ 文件夹在同一层;这层就是项目根目录。完整下载与环境说明见获取代码与安装实验依赖。

也可以单独下载 requirements-examples.txt 和 pca_classification.py。如果采用单独下载,将它们整理成下面的目录;浏览器不要把依赖文件另存成 requirements-examples.txt.txt:

ai-course/
  requirements-examples.txt
  examples/
    pca_classification.py

依赖清单不是安装程序:它列出 NumPy、scikit-learn、Matplotlib 等包及版本,pip install -r 才会按清单下载并安装。这个 PCA 示例使用 NumPy / scikit-learn 作对照,只需本页的依赖,不必先安装 PyTorch 或 Sphinx。

Windows:从下载到运行#

以解压目录 D:\ai-course 为例。把第一行路径换成自己的实际目录,在 PowerShell 中逐行执行:

cd "D:\ai-course"
python -m venv .venv
.\.venv\Scripts\python.exe -m pip install -r requirements-examples.txt
.\.venv\Scripts\python.exe examples/pca_classification.py --output-dir artifacts/pca --seed 42

python -m venv .venv 在项目根目录创建独立 Python 环境;下一行把第三方包安装到这个环境里。-r requirements-examples.txt 表示读取当前目录中的清单。最后一行用同一个环境运行脚本。建议使用 Python 3.12;若已经有本站的 .venv,跳过创建环境这一行即可。

macOS / Linux#

在终端进入实际解压目录后执行:

cd "/你的实际路径/ai-course"
python3 -m venv .venv
.venv/bin/python -m pip install -r requirements-examples.txt
.venv/bin/python examples/pca_classification.py --output-dir artifacts/pca --seed 42

已有环境同样跳过创建步骤。安装需要能连接 Python 包下载源;只下载 TXT 文件不会自动装好依赖。后续重新运行实验不必重复安装,直接在项目根目录执行:

.\.venv\Scripts\python.exe examples/pca_classification.py --output-dir artifacts/pca --seed 42

协议#

  1. 按类别分层保留 25% 测试样本,种子固定为 42。

  2. 无 PCA 基线为 StandardScaler → LogisticRegression。

  3. 对照为 StandardScaler → PCA → LogisticRegression;仅在训练集内三折交叉验证,以 macro-F1 选择 2 / 4 / 8 / 12 维。

  4. 流水线在各训练折中拟合预处理;方案确定后报告两个方法的测试 accuracy 与 macro-F1。

  5. 比较 NumPy 与 scikit-learn 的投影矩阵和解释方差,验证核心实现。

运行产物#

文件

作用

artifacts/pca/metrics.json

环境、训练 / 测试索引、参数选择、数值校验、最终指标、耗时

artifacts/pca/explained_variance.png

训练集累计解释方差

artifacts/pca/pca_scatter.png

训练样本在前两个主成分上的坐标

数值结果以实际运行产物为准。最终测试比较是教学示例:PCA 可能更好、相当或更差;单一小数据集和一次划分不能证明普遍结论。

首次验证结果#

2026-12-03 在 Windows、Python 3.12.9、NumPy 2.5.5、scikit-learn 1.9.1 下运行,默认种子为 42。训练集 133 个样本,测试集 45 个样本,训练内交叉验证选择了 2 个主成分。

方法

测试 accuracy

测试 macro-F1

标准化 + 逻辑回归

1.0000

1.0000

标准化 + PCA + 逻辑回归

0.9111

0.9159

PCA 在本次协议下丢失了部分分类所需信息。基线在 45 个测试样本上全对,也不等于模型在总体上不会出错。此结果用于演示正确的比较过程,不用于给方法排出普遍名次。

Wine 训练集累计解释方差随主成分数增加的曲线

训练数据上的累计解释方差。它与分类正确率是不同指标。#

Wine 训练样本在前两个主成分方向的散点图,颜色表示类别

标签仅用于着色,不参与 PCA 拟合。图中只展示训练样本。#

讨论题#

解释方差为何会随维数单调增长?分类分数是否也单调增长?如果先在所有样本上做标准化,评估协议发生了什么变化?二维图中的类别分离能否替代测试指标?

源码与下载#

下载完整脚本。

  1"""PCA from NumPy to a leakage-safe classification experiment (CPU, no downloads).
  2
  3Run from the repository root:
  4    python examples/pca_classification.py --output-dir artifacts/pca
  5"""
  6
  7from __future__ import annotations
  8
  9import argparse
 10import json
 11import platform
 12from pathlib import Path
 13from time import perf_counter
 14
 15import matplotlib
 16
 17matplotlib.use("Agg")
 18import matplotlib.pyplot as plt
 19import numpy as np
 20import sklearn
 21from sklearn.datasets import load_wine
 22from sklearn.decomposition import PCA
 23from sklearn.linear_model import LogisticRegression
 24from sklearn.metrics import accuracy_score, f1_score
 25from sklearn.model_selection import GridSearchCV, StratifiedKFold, cross_val_score, train_test_split
 26from sklearn.pipeline import Pipeline
 27from sklearn.preprocessing import StandardScaler
 28
 29
 30def fit_numpy_pca(x: np.ndarray, n_components: int):
 31    """Fit centered PCA with thin SVD; return mean, row directions, variances."""
 32    x = np.asarray(x, dtype=float)
 33    if x.ndim != 2 or x.shape[0] < 2:
 34        raise ValueError("Expected a 2D array with at least two samples")
 35    if not 1 <= n_components <= min(x.shape):
 36        raise ValueError("n_components must be between 1 and min(x.shape)")
 37    if not np.isfinite(x).all():
 38        raise ValueError("Input must contain only finite values")
 39    mean = x.mean(axis=0)
 40    centered = x - mean
 41    _, singular_values, vt = np.linalg.svd(centered, full_matrices=False)
 42    explained_variance = singular_values**2 / (x.shape[0] - 1)
 43    return mean, vt[:n_components], explained_variance[:n_components]
 44
 45
 46def make_pipeline(n_components: int | None = None) -> Pipeline:
 47    steps = [("scale", StandardScaler())]
 48    if n_components is not None:
 49        steps.append(("pca", PCA(n_components=n_components, svd_solver="full")))
 50    steps.append(("classifier", LogisticRegression(max_iter=2000)))
 51    return Pipeline(steps)
 52
 53
 54def main() -> None:
 55    parser = argparse.ArgumentParser(description=__doc__)
 56    parser.add_argument("--output-dir", type=Path, default=Path("artifacts/pca"))
 57    parser.add_argument("--seed", type=int, default=42)
 58    args = parser.parse_args()
 59    started = perf_counter()
 60    args.output_dir.mkdir(parents=True, exist_ok=True)
 61
 62    x, y = load_wine(return_X_y=True)
 63    indices = np.arange(len(y))
 64    train_idx, test_idx = train_test_split(
 65        indices, test_size=0.25, random_state=args.seed, stratify=y
 66    )
 67    x_train, x_test, y_train, y_test = x[train_idx], x[test_idx], y[train_idx], y[test_idx]
 68    cv = StratifiedKFold(n_splits=3, shuffle=True, random_state=args.seed)
 69
 70    baseline = make_pipeline()
 71    baseline_cv = cross_val_score(baseline, x_train, y_train, cv=cv, scoring="f1_macro")
 72    search = GridSearchCV(
 73        make_pipeline(2),
 74        {"pca__n_components": [2, 4, 8, 12]},
 75        cv=cv,
 76        scoring="f1_macro",
 77        n_jobs=1,
 78        error_score="raise",
 79    )
 80    search.fit(x_train, y_train)
 81    baseline.fit(x_train, y_train)
 82
 83    # NumPy vs. sklearn: fit on training samples only; compare subspace projectors.
 84    scaled_train = search.best_estimator_.named_steps["scale"].transform(x_train)
 85    k = search.best_params_["pca__n_components"]
 86    mean, directions, variances = fit_numpy_pca(scaled_train, k)
 87    selected_pca = search.best_estimator_.named_steps["pca"]
 88    projector = directions.T @ directions
 89    sklearn_projector = selected_pca.components_.T @ selected_pca.components_
 90    np.testing.assert_allclose(projector, sklearn_projector, atol=1e-8)
 91    np.testing.assert_allclose(variances, selected_pca.explained_variance_, rtol=1e-8)
 92    centered = scaled_train - mean
 93    reconstruction_mse = float(np.mean((centered - centered @ projector) ** 2))
 94
 95    test_metrics = {}
 96    for name, model in {"baseline": baseline, "pca": search.best_estimator_}.items():
 97        predictions = model.predict(x_test)
 98        test_metrics[name] = {
 99            "accuracy": float(accuracy_score(y_test, predictions)),
100            "macro_f1": float(f1_score(y_test, predictions, average="macro")),
101        }
102
103    # Figures use training samples only. Labels color the plot, not the PCA fit.
104    full_pca = PCA(svd_solver="full").fit(scaled_train)
105    projected = full_pca.transform(scaled_train)
106    fig, ax = plt.subplots(figsize=(6.4, 4.0), layout="constrained")
107    ax.plot(np.arange(1, x.shape[1] + 1), np.cumsum(full_pca.explained_variance_ratio_), "o-")
108    ax.set(xlabel="Number of principal components", ylabel="Cumulative explained variance",
109           title="Wine: training-set variance", ylim=(0, 1.02))
110    ax.grid(alpha=0.2)
111    fig.savefig(args.output_dir / "explained_variance.png", dpi=160)
112    plt.close(fig)
113
114    fig, ax = plt.subplots(figsize=(6.4, 4.0), layout="constrained")
115    for label in np.unique(y_train):
116        mask = y_train == label
117        ax.scatter(projected[mask, 0], projected[mask, 1], label=f"Class {label}", s=26, alpha=0.8)
118    ax.set(xlabel="PC 1", ylabel="PC 2", title="Wine: training samples in PCA space")
119    ax.legend()
120    fig.savefig(args.output_dir / "pca_scatter.png", dpi=160)
121    plt.close(fig)
122
123    result = {
124        "environment": {
125            "python": platform.python_version(), "platform": platform.platform(),
126            "numpy": np.__version__, "scikit_learn": sklearn.__version__,
127            "matplotlib": matplotlib.__version__,
128        },
129        "dataset": {"name": "sklearn.datasets.load_wine", "samples": len(y), "features": x.shape[1]},
130        "protocol": {"seed": args.seed, "test_fraction": 0.25, "cv_folds": 3,
131                     "selection_metric": "f1_macro", "classifier_max_iter": 2000,
132                     "pca_solver": "full", "train_indices": train_idx.tolist(),
133                     "test_indices": test_idx.tolist()},
134        "selection": {"n_components": int(k), "baseline_cv_macro_f1": baseline_cv.tolist(),
135                      "pca_cv_mean_macro_f1": search.cv_results_["mean_test_score"].tolist(),
136                      "pca_cv_std_macro_f1": search.cv_results_["std_test_score"].tolist(),
137                      "candidates": [2, 4, 8, 12]},
138        "numerical_check": {"projector_max_abs_error": float(np.max(np.abs(projector - sklearn_projector))),
139                            "training_reconstruction_mse": reconstruction_mse},
140        "test": test_metrics,
141        "training_explained_variance_ratio": selected_pca.explained_variance_ratio_.tolist(),
142        "elapsed_seconds": perf_counter() - started,
143    }
144    result_path = args.output_dir / "metrics.json"
145    result_path.write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8")
146    print(json.dumps({"selected_components": int(k), "test": test_metrics,
147                      "metrics_file": str(result_path.resolve())}, ensure_ascii=False, indent=2))
148
149
150if __name__ == "__main__":
151    main()