{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "# 实验 A：预测、比较与降维\n",
        "先猜：直线、森林和只猜平均值，谁会更好？运行后看 MAE 和预测图。观察点离对角线有多远，再解释误差。PCA 的颜色来自目标，仅用于观察，不参与降维拟合。\n",
        "**数据声明：本实验使用固定随机种子生成的模拟教学数据，不是真实材料数据。**\n",
        "先安装依赖，再依次运行下方两格。图片和结果保存在当前目录的 outputs 文件夹。\n"
      ],
      "id": "lab-a-0"
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "\"\"\"共同的模拟教学数据；不代表真实材料测量或物理规律。\"\"\"\n",
        "from pathlib import Path\n",
        "import csv\n",
        "import numpy as np\n",
        "\n",
        "OUT = Path.cwd() / 'outputs'\n",
        "OUT.mkdir(exist_ok=True)\n",
        "\n",
        "def materials():\n",
        "    rng = np.random.default_rng(42)\n",
        "    temperature = rng.uniform(300, 900, 240)\n",
        "    fraction = rng.uniform(0, 1, 240)\n",
        "    size = rng.uniform(10, 100, 240)\n",
        "    X = np.column_stack([temperature, fraction, size])\n",
        "    y = 2 + .004 * temperature + 3 * fraction**2 - .015 * size + rng.normal(0, .15, 240)\n",
        "    with (OUT / 'simulated_materials.csv').open('w', newline='', encoding='utf-8') as f:\n",
        "        w = csv.writer(f)\n",
        "        w.writerow(['temperature_K', 'fraction', 'size_nm', 'teaching_response'])\n",
        "        w.writerows(np.column_stack([X, y]))\n",
        "    return X, y\n"
      ],
      "id": "lab-a-1"
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "\"\"\"实验 A：相同数据划分下比较基线、直线、森林，并观察 PCA。\"\"\"\n",
        "import json\n",
        "import matplotlib\n",
        "matplotlib.use('Agg')\n",
        "import matplotlib.pyplot as plt\n",
        "from sklearn.model_selection import train_test_split, GridSearchCV, KFold\n",
        "from sklearn.pipeline import make_pipeline\n",
        "from sklearn.preprocessing import StandardScaler\n",
        "from sklearn.dummy import DummyRegressor\n",
        "from sklearn.linear_model import LinearRegression\n",
        "from sklearn.ensemble import RandomForestRegressor\n",
        "from sklearn.metrics import mean_absolute_error\n",
        "from sklearn.decomposition import PCA\n",
        "\n",
        "\n",
        "X, y = materials()\n",
        "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.25, random_state=42)\n",
        "print('训练／测试形状:', X_train.shape, X_test.shape)\n",
        "cv = KFold(n_splits=5, shuffle=True, random_state=42)\n",
        "forest = GridSearchCV(RandomForestRegressor(n_estimators=100, random_state=42),\n",
        "                      {'max_depth': [3, 6, None]}, cv=cv, scoring='neg_mean_absolute_error')\n",
        "models = {'mean': DummyRegressor(), 'linear': make_pipeline(StandardScaler(), LinearRegression()), 'forest': forest}\n",
        "scores = {}\n",
        "fig, axes = plt.subplots(1, 3, figsize=(12, 4), constrained_layout=True)\n",
        "for ax, (name, model) in zip(axes, models.items()):\n",
        "    model.fit(X_train, y_train)\n",
        "    prediction = model.predict(X_test)\n",
        "    scores[name] = float(mean_absolute_error(y_test, prediction))\n",
        "    ax.scatter(y_test, prediction, s=16)\n",
        "    lo, hi = min(y_test), max(y_test)\n",
        "    ax.plot([lo, hi], [lo, hi], '--', color='gray')\n",
        "    ax.set(xlabel='Measured teaching response', ylabel='Prediction', title=f'{name}: MAE={scores[name]:.3f}')\n",
        "fig.savefig(OUT / 'a_predictions.png', dpi=150)\n",
        "plt.close(fig)\n",
        "# PCA 只在训练集拟合；颜色只是帮助观察，与 PCA 拟合无关。\n",
        "projection = make_pipeline(StandardScaler(), PCA(n_components=2))\n",
        "z = projection.fit_transform(X_train)\n",
        "ratio = projection[-1].explained_variance_ratio_\n",
        "fig, ax = plt.subplots(figsize=(6, 4), constrained_layout=True)\n",
        "points = ax.scatter(z[:, 0], z[:, 1], c=y_train, s=18)\n",
        "fig.colorbar(points, ax=ax, label='Teaching response')\n",
        "ax.set(xlabel='PC1', ylabel='PC2', title=f'PCA: variance retained={sum(ratio):.1%}')\n",
        "fig.savefig(OUT / 'a_pca.png', dpi=150)\n",
        "plt.close(fig)\n",
        "result = {'test_mae': scores, 'forest_best_parameters': forest.best_params_, 'pca_variance_ratio': ratio.tolist()}\n",
        "(OUT / 'a_results.json').write_text(json.dumps(result, indent=2), encoding='utf-8')\n",
        "print(json.dumps(result, indent=2))\n"
      ],
      "id": "lab-a-2"
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 运行后回答\n",
        "先猜：直线、森林和只猜平均值，谁会更好？运行后看 MAE 和预测图。观察点离对角线有多远，再解释误差。PCA 的颜色来自目标，仅用于观察，不参与降维拟合。\n",
        "提交结果表、输出图、150 字解释和一个局限。改变设置属于新实验；不要看测试结果反复挑设置。\n"
      ],
      "id": "lab-a-3"
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "name": "python",
      "version": "3.12"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 5
}