{
 "nbformat": 4,
 "nbformat_minor": 5,
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3.11"
  }
 },
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# AI Preliminary / AI 入门: Neural Network Basics\n",
    "\n",
    "From a line that cannot fit sin(x) to a trainable one-hidden-layer MLP.\n",
    "This course adaptation follows the supplied Neural Network Basics slides and\n",
    "NumPy teaching notebook. It matches the website's seeded JavaScript experiment;\n",
    "the original materials are separately downloadable from the lesson.\n",
    "\n",
    "**Run all cells from top to bottom.** The model uses only the standard library.\n",
    "The figures require Matplotlib (`python -m pip install matplotlib`). No external\n",
    "data, API key, GPU, or hidden helper file is needed. Python 3.9+ is sufficient.\n",
    "\n",
    "本文件包含全部模型源码、参数说明、训练、绘图和梯度核对。先运行模型定义，\n",
    "再运行 main；之后可修改 case，比对网络宽度、激活、学习率与噪声。\n",
    "\n",
    "This is supervised regression, not an N-1 security predictor. Training points\n",
    "span [-π, π]; the 160 validation points are distinct clean interpolation targets.\n",
    "Noise affects training labels only. There is no independent final test set."
   ],
   "id": "ai-preliminary-00"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. Complete model / 完整模型\n",
    "\n",
    "`dataset` → `initialize` → `gradient` → `step` → `train`.\n",
    "`gradient` makes every chain-rule factor explicit; all gradients use the old\n",
    "parameters before any update. The row-batch equations are\n",
    "Z = XW₁ + b₁, H = σ(Z), Ŷ = HW₂ + b₂. Scalar loops implement the same equations."
   ],
   "id": "ai-preliminary-01"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "\"\"\"Readable one-hidden-layer MLP, using only the Python standard library.\n",
    "\n",
    "The website's fast JavaScript lab implements these same equations, data, PRNG\n",
    "and full-batch gradient updates. No PyTorch, hidden model weights, or API calls.\n",
    "Each row is one observation; the scalar version below makes each chain-rule\n",
    "factor explicit. See the lesson for equivalent batched matrix equations.\n",
    "\"\"\"\n",
    "import math\n",
    "\n",
    "DEFAULTS = dict(target=\"sin\", activation=\"tanh\", hidden=16, samples=64,\n",
    "                noise=0.0, lr=0.03, epochs=2500, seed=7)\n",
    "\n",
    "\n",
    "def normal_generator(seed):\n",
    "    \"\"\"Seeded Box-Muller samples; same 32-bit LCG as the browser experiment.\"\"\"\n",
    "    state = int(seed) & 0xffffffff\n",
    "\n",
    "    def uniform():\n",
    "        nonlocal state\n",
    "        state = (1664525 * state + 1013904223) & 0xffffffff\n",
    "        return (state + 0.5) / 4294967296\n",
    "\n",
    "    while True:\n",
    "        yield math.sqrt(-2 * math.log(uniform())) * math.cos(2 * math.pi * uniform())\n",
    "\n",
    "\n",
    "def settings(parameters=None):\n",
    "    c = dict(DEFAULTS, **(parameters or {}))\n",
    "    if c[\"target\"] not in (\"sin\", \"sin2\", \"cubic\"):\n",
    "        raise ValueError(\"Unknown target\")\n",
    "    if c[\"activation\"] not in (\"tanh\", \"relu\", \"sigmoid\", \"linear\"):\n",
    "        raise ValueError(\"Unknown activation\")\n",
    "    for key, lo, hi in ((\"hidden\", 1, 64), (\"samples\", 4, 128),\n",
    "                        (\"epochs\", 0, 6000), (\"seed\", 0, 4294967295)):\n",
    "        if not isinstance(c[key], int) or isinstance(c[key], bool) or not lo <= c[key] <= hi:\n",
    "            raise ValueError(\"Invalid \" + key)\n",
    "    if c[\"samples\"] % 2:\n",
    "        raise ValueError(\"Use an even sample count so validation points stay distinct\")\n",
    "    for key, lo, hi in ((\"noise\", 0, 0.5), (\"lr\", 0.0001, 2)):\n",
    "        if not math.isfinite(c[key]) or not lo <= c[key] <= hi:\n",
    "            raise ValueError(\"Invalid \" + key)\n",
    "    return c\n",
    "\n",
    "\n",
    "def target(x, name=\"sin\"):\n",
    "    return math.sin(2*x) if name == \"sin2\" else (x/math.pi)**3 if name == \"cubic\" else math.sin(x)\n",
    "\n",
    "\n",
    "def activation(z, name=\"tanh\"):\n",
    "    if name == \"relu\":\n",
    "        return max(0.0, z)\n",
    "    if name == \"linear\":\n",
    "        return z\n",
    "    if name == \"sigmoid\":\n",
    "        return 1/(1+math.exp(-z)) if z >= 0 else math.exp(z)/(1+math.exp(z))\n",
    "    return math.tanh(z)\n",
    "\n",
    "\n",
    "def derivative(z, h, name):\n",
    "    # ReLU is nondifferentiable at zero; this implementation chooses 0 there.\n",
    "    return float(z > 0) if name == \"relu\" else 1.0 if name == \"linear\" else h*(1-h) if name == \"sigmoid\" else 1-h*h\n",
    "\n",
    "\n",
    "def initialize(c):\n",
    "    normal = normal_generator(c[\"seed\"])\n",
    "    return dict(w1=[0.25*next(normal) for _ in range(c[\"hidden\"])],\n",
    "                b1=[0.0]*c[\"hidden\"],\n",
    "                w2=[0.25*next(normal) for _ in range(c[\"hidden\"])], b2=0.0)\n",
    "\n",
    "\n",
    "def copy_params(p):\n",
    "    return dict(w1=p[\"w1\"][:], b1=p[\"b1\"][:], w2=p[\"w2\"][:], b2=p[\"b2\"])\n",
    "\n",
    "\n",
    "def features(x, p, name):\n",
    "    return [activation(w*x+b, name) for w, b in zip(p[\"w1\"], p[\"b1\"])]\n",
    "\n",
    "\n",
    "def predict(x, p, name):\n",
    "    return p[\"b2\"] + sum(w*h for w, h in zip(p[\"w2\"], features(x, p, name)))\n",
    "\n",
    "\n",
    "def dataset(c):\n",
    "    \"\"\"Training: noisy endpoints grid. Validation: distinct clean midpoints.\n",
    "\n",
    "    This synthetic validation is an interpolation demonstration, not a held-out\n",
    "    assessment of a real power-system predictor. Noise is added only to training.\n",
    "    \"\"\"\n",
    "    normal = normal_generator(c[\"seed\"] ^ 0x9e3779b9)\n",
    "    x = [-math.pi + 2*math.pi*i/(c[\"samples\"]-1) for i in range(c[\"samples\"])]\n",
    "    y = [target(v, c[\"target\"]) + c[\"noise\"]*next(normal) for v in x]\n",
    "    vx = [-math.pi + 2*math.pi*(i+0.5)/160 for i in range(160)]\n",
    "    return x, y, vx, [target(v, c[\"target\"]) for v in vx]\n",
    "\n",
    "\n",
    "def mse(x, y, p, name):\n",
    "    return sum((predict(v, p, name)-truth)**2 for v, truth in zip(x, y))/len(x)\n",
    "\n",
    "\n",
    "def gradient(x, y, p, name):\n",
    "    \"\"\"Backpropagation: dL/dy -> dL/dh -> dL/dz -> parameter gradients.\"\"\"\n",
    "    g = dict(w1=[0.0]*len(p[\"w1\"]), b1=[0.0]*len(p[\"w1\"]),\n",
    "             w2=[0.0]*len(p[\"w1\"]), b2=0.0)\n",
    "    for xi, yi in zip(x, y):\n",
    "        h = features(xi, p, name)\n",
    "        y_hat = p[\"b2\"] + sum(w*hj for w, hj in zip(p[\"w2\"], h))\n",
    "        d = 2*(y_hat-yi)/len(x)  # MSE gradient includes the batch average.\n",
    "        g[\"b2\"] += d\n",
    "        for j, hj in enumerate(h):\n",
    "            dz = d*p[\"w2\"][j]*derivative(p[\"w1\"][j]*xi+p[\"b1\"][j], hj, name)\n",
    "            g[\"w2\"][j] += d*hj\n",
    "            g[\"w1\"][j] += dz*xi\n",
    "            g[\"b1\"][j] += dz\n",
    "    return g\n",
    "\n",
    "\n",
    "def step(p, g, lr):\n",
    "    # Compute every gradient before updating any weight.\n",
    "    for key in (\"w1\", \"b1\", \"w2\"):\n",
    "        for j in range(len(p[key])):\n",
    "            p[key][j] -= lr*g[key][j]\n",
    "    p[\"b2\"] -= lr*g[\"b2\"]\n",
    "\n",
    "\n",
    "def linear_fit(x, y):\n",
    "    mx, my = sum(x)/len(x), sum(y)/len(y)\n",
    "    slope = sum((v-mx)*(t-my) for v, t in zip(x, y))/sum((v-mx)**2 for v in x)\n",
    "    return dict(slope=slope, intercept=my-slope*mx)\n",
    "\n",
    "\n",
    "def train(parameters=None):\n",
    "    \"\"\"Generate data, initialize, optimize, and evaluate the completed updates.\n",
    "\n",
    "    Frames retain parameter snapshots for the website's epoch replay. A numeric\n",
    "    divergence stops the run and is explicitly reported; a finite loss alone\n",
    "    does not establish convergence or successful generalization.\n",
    "    \"\"\"\n",
    "    c = settings(parameters)\n",
    "    x, y, vx, vy = dataset(c)\n",
    "    p = initialize(c)\n",
    "    every = max(1, math.ceil(c[\"epochs\"]/80))\n",
    "    frames, completed, diverged_epoch = [], 0, None\n",
    "\n",
    "    def record(epoch):\n",
    "        frames.append(dict(epoch=epoch, train_mse=mse(x, y, p, c[\"activation\"]),\n",
    "                           validation_mse=mse(vx, vy, p, c[\"activation\"]), params=copy_params(p)))\n",
    "\n",
    "    record(0)\n",
    "    for epoch in range(1, c[\"epochs\"]+1):\n",
    "        candidate = copy_params(p)\n",
    "        step(candidate, gradient(x, y, p, c[\"activation\"]), c[\"lr\"])\n",
    "        loss = mse(x, y, candidate, c[\"activation\"])\n",
    "        if not math.isfinite(loss) or loss > 1e12:\n",
    "            diverged_epoch = epoch\n",
    "            break\n",
    "        p, completed = candidate, epoch\n",
    "        if epoch % every == 0 or epoch == c[\"epochs\"]:\n",
    "            record(epoch)\n",
    "    if frames[-1][\"epoch\"] != completed:\n",
    "        record(completed)\n",
    "    linear = linear_fit(x, y)\n",
    "    grid = [-1.25*math.pi+2.5*math.pi*i/200 for i in range(201)]\n",
    "    return dict(ok=diverged_epoch is None, case=c, completed_epochs=completed,\n",
    "                diverged_epoch=diverged_epoch, parameter_count=3*c[\"hidden\"]+1,\n",
    "                params=p, frames=frames, train_mse=frames[-1][\"train_mse\"],\n",
    "                validation_mse=frames[-1][\"validation_mse\"],\n",
    "                linear_validation_mse=sum((linear[\"slope\"]*v+linear[\"intercept\"]-t)**2 for v, t in zip(vx, vy))/len(vx),\n",
    "                linear=linear, train=dict(x=x, y=y), grid=grid,\n",
    "                target=[target(v, c[\"target\"]) for v in grid],\n",
    "                prediction=[predict(v, p, c[\"activation\"]) for v in grid])"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "ai-preliminary-02"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2. Inputs and main / 参数与主程序\n",
    "\n",
    "`hidden`: width (3H+1 parameters); `samples`: even training count;\n",
    "`noise`: Gaussian training-label standard deviation; `lr`: learning rate;\n",
    "`epochs`: full-batch updates; `seed`: data/initialization repeatability.\n",
    "Targets: `sin`, `sin2`, `cubic`. Activations: `tanh`, `relu`, `sigmoid`, `linear`.\n",
    "Change one setting at a time. `main` copies inputs, trains, checks status,\n",
    "prints metrics, and returns the complete answer for the figures."
   ],
   "id": "ai-preliminary-03"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "case = dict(DEFAULTS)\n",
    "# case.update(hidden=32, target=\"sin2\", lr=0.03, epochs=2500)\n",
    "\n",
    "def main():\n",
    "    parameters = dict(case)  # Keep the experiment input separate from results.\n",
    "    answer = train(parameters)\n",
    "    if not answer[\"ok\"]:\n",
    "        raise RuntimeError(f\"Numerical divergence at epoch {answer['diverged_epoch']}; reduce lr\")\n",
    "    print(\"Completed updates:\", answer[\"completed_epochs\"])\n",
    "    print(\"Parameters:\", answer[\"parameter_count\"])\n",
    "    print(\"Training MSE:\", answer[\"train_mse\"])\n",
    "    print(\"Validation MSE (clean):\", answer[\"validation_mse\"])\n",
    "    print(\"Linear validation MSE:\", answer[\"linear_validation_mse\"])\n",
    "    return answer\n",
    "\n",
    "result = main()"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "ai-preliminary-04"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3. Inspect the fit and learning curve / 拟合与误差\n",
    "\n",
    "The shaded regions are extrapolation, excluded from validation metrics.\n",
    "Both the line and MLP use the same training observations. Metrics are evaluated\n",
    "after the recorded update, including epoch 0 and the final epoch."
   ],
   "id": "ai-preliminary-05"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import matplotlib.pyplot as plt\n",
    "\n",
    "fig, axes = plt.subplots(1, 2, figsize=(12, 4))\n",
    "grid = result[\"grid\"]\n",
    "axes[0].plot(grid, result[\"target\"], \"k--\", label=\"true target\")\n",
    "axes[0].scatter(result[\"train\"][\"x\"], result[\"train\"][\"y\"], s=12, alpha=0.5, label=\"training labels\")\n",
    "axes[0].plot(grid, [result[\"linear\"][\"slope\"]*x+result[\"linear\"][\"intercept\"] for x in grid], label=\"least-squares line\")\n",
    "axes[0].plot(grid, result[\"prediction\"], label=\"trained MLP\")\n",
    "for a, b in ((grid[0], -math.pi), (math.pi, grid[-1])):\n",
    "    axes[0].axvspan(a, b, color=\"gray\", alpha=0.12)\n",
    "axes[0].set(xlabel=\"x\", ylabel=\"y\", title=\"Fit and extrapolation\")\n",
    "axes[0].legend()\n",
    "for key, label in ((\"train_mse\", \"training\"), (\"validation_mse\", \"validation: clean target\")):\n",
    "    axes[1].semilogy([f[\"epoch\"] for f in result[\"frames\"]],\n",
    "                     [max(1e-12, f[key]) for f in result[\"frames\"]], label=label)\n",
    "axes[1].set(xlabel=\"epoch\", ylabel=\"MSE (log scale)\", title=\"Full-batch gradient descent\")\n",
    "axes[1].legend()\n",
    "fig.tight_layout()\n",
    "plt.show()"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "ai-preliminary-06"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4. Replay and reconstruct the output / 回放与特征叠加\n",
    "\n",
    "Choose a saved `frame_index` (0 is the initial network). Rank features by RMS\n",
    "weighted contribution inside the training interval, rather than output weight\n",
    "alone. Include the remaining terms and bias; their sum must equal the output."
   ],
   "id": "ai-preliminary-07"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "frame_index = len(result[\"frames\"])-1\n",
    "frame = result[\"frames\"][frame_index]\n",
    "p = frame[\"params\"]\n",
    "name = result[\"case\"][\"activation\"]\n",
    "parts = [[p[\"w2\"][j]*activation(p[\"w1\"][j]*x+p[\"b1\"][j], name) for x in grid]\n",
    "         for j in range(len(p[\"w1\"]))]\n",
    "inside = [i for i, x in enumerate(grid) if abs(x) <= math.pi]\n",
    "order = sorted(range(len(parts)),\n",
    "               key=lambda j: sum(parts[j][i]**2 for i in inside)/len(inside), reverse=True)[:3]\n",
    "other = [p[\"b2\"]+sum(part[i] for j, part in enumerate(parts) if j not in order)\n",
    "         for i in range(len(grid))]\n",
    "for j in order:\n",
    "    plt.plot(grid, parts[j], label=f\"weighted unit {j+1}\")\n",
    "plt.plot(grid, other, \"--\", label=\"other terms + bias\")\n",
    "plt.title(f\"Contributions at epoch {frame['epoch']}\")\n",
    "plt.xlabel(\"x\"); plt.legend(); plt.show()\n",
    "error = max(abs(sum(parts[j][i] for j in order)+other[i]-predict(x, p, name))\n",
    "            for i, x in enumerate(grid))\n",
    "print(\"Pointwise reconstruction error:\", error)\n",
    "assert error < 1e-10"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "ai-preliminary-08"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 5. Check backpropagation / 用数值差分核对梯度\n",
    "\n",
    "For every parameter, compare the analytic gradient with the central difference\n",
    "[L(θ+ε)−L(θ−ε)]/(2ε). This uses a small smooth tanh network; at a ReLU kink\n",
    "the derivative is undefined and this comparison needs separate treatment."
   ],
   "id": "ai-preliminary-09"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "small = settings(dict(hidden=3, samples=16, epochs=0))\n",
    "x, y, _, _ = dataset(small)\n",
    "p = initialize(small)\n",
    "g = gradient(x, y, p, \"tanh\")\n",
    "epsilon, errors = 1e-6, []\n",
    "for key in (\"w1\", \"b1\", \"w2\", \"b2\"):\n",
    "    indices = range(len(p[key])) if key != \"b2\" else [None]\n",
    "    for j in indices:\n",
    "        plus, minus = copy_params(p), copy_params(p)\n",
    "        if j is None:\n",
    "            plus[key] += epsilon; minus[key] -= epsilon\n",
    "            analytic = g[key]\n",
    "        else:\n",
    "            plus[key][j] += epsilon; minus[key][j] -= epsilon\n",
    "            analytic = g[key][j]\n",
    "        numeric = (mse(x, y, plus, \"tanh\")-mse(x, y, minus, \"tanh\"))/(2*epsilon)\n",
    "        errors.append(abs(analytic-numeric))\n",
    "print(\"Maximum gradient error:\", max(errors))\n",
    "assert max(errors) < 1e-6"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "ai-preliminary-10"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 6. Experiments and the grid-data bridge / 练习与电网衔接\n",
    "\n",
    "1. Replace tanh with linear activation; increase width. Why is the result affine?\n",
    "2. Try lr = 0.001, 0.03, 1. Distinguish slow progress from numerical failure.\n",
    "3. Change the target to sin2; compare widths with a fixed seed and epoch budget.\n",
    "4. Set samples=16, noise=0.3. Explain why training and clean-validation MSE\n",
    "   are not measured against identical label distributions.\n",
    "5. Separate interpolation from extrapolation; a good in-range fit need not\n",
    "   extrapolate. Keep a final test set untouched in a real project.\n",
    "6. For power-flow learning, define input/target units, topology/status fields,\n",
    "   convergence treatment, split groups, and the actual security criterion.\n",
    "\n",
    "潮流生成数据 → 审核状态与单位 → 按场景划分 → 训练基线 → 检查物理任务指标。\n",
    "An MLP or GNN does not automatically satisfy AC equations. Neural ODEs instead\n",
    "parameterize a state derivative and introduce an ODE solver; that is an optional\n",
    "dynamics extension, not something established by this regression example.\n",
    "\n",
    "References: [D2L MLPs](https://d2l.ai/chapter_multilayer-perceptrons/mlp.html),\n",
    "[PyTorch autograd](https://docs.pytorch.org/tutorials/beginner/basics/autogradqs_tutorial.html),\n",
    "[Google dataset splits](https://developers.google.com/machine-learning/crash-course/overfitting/dividing-datasets)."
   ],
   "id": "ai-preliminary-11"
  }
 ]
}
