{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "# Lesson 03: Neural Network Basics From Scratch\n",
        "\n",
        "**CS230 inspiration:** Logistic regression mindset, shallow neural networks, forward propagation, loss, and backpropagation.\n",
        "\n",
        "**Demand forecasting focus:** Implement a small MLP with NumPy to forecast log demand from engineered features.\n",
        "\n",
        "**Learning objectives**\n",
        "\n",
        "- Trace a forward pass through dense layers and ReLU.\n",
        "- Compute gradients for a one-hidden-layer network.\n",
        "- Connect feature scaling and target scaling to stable optimization.\n",
        "\n",
        "**Senior-readiness checkpoint:** You can debug a training loop by inspecting shapes, scales, loss movement, and gradients.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Code Cell 1 Explanation\n",
        "\n",
        "**What this cell does:** This setup cell imports the shared scientific Python stack and the curriculum helpers used by later cells. It also establishes the deterministic seed convention so repeated runs are comparable.\n",
        "\n",
        "**Why it matters:** A restart-and-run notebook should make its dependencies explicit before any modeling work begins. For forecasting, reproducibility is especially important because small data or seed changes can change validation conclusions.\n",
        "\n",
        "**Key operations to notice:** confirm that shared helper imports match the lesson's code path; check that `SEED` is defined before any generated data or model training\n",
        "\n",
        "**What to inspect:** Check that imports are grouped by purpose: general analysis packages, forecasting data helpers, metrics, plotting utilities, and any lesson-specific libraries.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "import matplotlib.pyplot as plt\n",
        "import numpy as np\n",
        "import pandas as pd\n",
        "\n",
        "from demand_forecasting_curriculum.data import (\n",
        "    DEFAULT_FEATURE_COLUMNS,\n",
        "    generate_daily_demand,\n",
        "    make_sequence_dataset,\n",
        "    make_supervised_table,\n",
        "    time_series_split,\n",
        ")\n",
        "from demand_forecasting_curriculum.metrics import (\n",
        "    interval_coverage,\n",
        "    mase,\n",
        "    pinball_loss,\n",
        "    smape,\n",
        "    wmape,\n",
        ")\n",
        "from demand_forecasting_curriculum.plotting import plot_predictions, plot_series\n",
        "\n",
        "SEED = 42\n",
        "np.random.seed(SEED)\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Code Cell 2 Explanation\n",
        "\n",
        "**What this cell does:** This cell advances **Neural Network Basics From Scratch** by working on synthetic demand generation, time-based splitting, supervised feature construction. It creates or updates `df`, `supervised`, `train`, `valid`, `_`, `feature_cols` and prepares evidence that later cells use rather than hiding state in prose.\n",
        "\n",
        "**Why it matters:** The goal is tied to this lesson's forecasting focus: Implement a small MLP with NumPy to forecast log demand from engineered features. Each object is kept inspectable so the learner can connect code, assumptions, and modeling consequences.\n",
        "\n",
        "**Key operations to notice:** creates a synthetic retail panel with known demand drivers; turns time series rows into forecast-origin training examples; keeps train, validation, and test windows ordered by date\n",
        "\n",
        "**What to inspect:** Before moving on, inspect shapes, date ranges, metric values, segment behavior, or generated tables. If a value looks surprisingly good, surprisingly bad, or unavailable at forecast time, treat that as a modeling clue.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "df = generate_daily_demand(n_stores=3, n_items=5, periods=420, seed=SEED)\n",
        "supervised = make_supervised_table(df, horizon=7)\n",
        "train, valid, _ = time_series_split(supervised, valid_days=45, test_days=45)\n",
        "\n",
        "feature_cols = [\"store_id\", \"item_id\", *DEFAULT_FEATURE_COLUMNS]\n",
        "X_train = train[feature_cols].to_numpy(dtype=float)\n",
        "X_valid = valid[feature_cols].to_numpy(dtype=float)\n",
        "y_train = np.log1p(train[\"y\"].to_numpy(dtype=float)).reshape(-1, 1)\n",
        "y_valid = np.log1p(valid[\"y\"].to_numpy(dtype=float)).reshape(-1, 1)\n",
        "\n",
        "x_mean, x_std = X_train.mean(axis=0), X_train.std(axis=0)\n",
        "x_std = np.where(x_std == 0, 1, x_std)\n",
        "X_train = (X_train - x_mean) / x_std\n",
        "X_valid = (X_valid - x_mean) / x_std\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Code Cell 3 Explanation\n",
        "\n",
        "**What this cell does:** This cell advances **Neural Network Basics From Scratch** by working on the lesson workflow. It creates or updates `n_features`, `hidden`, `rng`, `W1`, `b1`, `W2` and prepares evidence that later cells use rather than hiding state in prose.\n",
        "\n",
        "**Why it matters:** The goal is tied to this lesson's forecasting focus: Implement a small MLP with NumPy to forecast log demand from engineered features. Each object is kept inspectable so the learner can connect code, assumptions, and modeling consequences.\n",
        "\n",
        "**Key operations to notice:** follow the assignments, final displayed object, and any checks in the cell because those are the evidence the next cell depends on\n",
        "\n",
        "**What to inspect:** Before moving on, inspect shapes, date ranges, metric values, segment behavior, or generated tables. If a value looks surprisingly good, surprisingly bad, or unavailable at forecast time, treat that as a modeling clue.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "n_features = X_train.shape[1]\n",
        "hidden = 32\n",
        "rng = np.random.default_rng(SEED)\n",
        "\n",
        "W1 = rng.normal(0, np.sqrt(2 / n_features), size=(n_features, hidden))\n",
        "b1 = np.zeros((1, hidden))\n",
        "W2 = rng.normal(0, np.sqrt(2 / hidden), size=(hidden, 1))\n",
        "b2 = np.zeros((1, 1))\n",
        "\n",
        "def relu(x):\n",
        "    return np.maximum(x, 0)\n",
        "\n",
        "def relu_grad(x):\n",
        "    return (x > 0).astype(float)\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Code Cell 4 Explanation\n",
        "\n",
        "**What this cell does:** This cell advances **Neural Network Basics From Scratch** by working on visualization. It creates or updates `lr`, `batch_size`, `losses` and prepares evidence that later cells use rather than hiding state in prose.\n",
        "\n",
        "**Why it matters:** The goal is tied to this lesson's forecasting focus: Implement a small MLP with NumPy to forecast log demand from engineered features. Each object is kept inspectable so the learner can connect code, assumptions, and modeling consequences.\n",
        "\n",
        "**Key operations to notice:** visualizes model behavior or data quality\n",
        "\n",
        "**What to inspect:** Before moving on, inspect shapes, date ranges, metric values, segment behavior, or generated tables. If a value looks surprisingly good, surprisingly bad, or unavailable at forecast time, treat that as a modeling clue.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "lr = 0.02\n",
        "batch_size = 256\n",
        "losses = []\n",
        "\n",
        "for step in range(400):\n",
        "    batch_idx = rng.choice(len(X_train), size=batch_size, replace=False)\n",
        "    xb, yb = X_train[batch_idx], y_train[batch_idx]\n",
        "\n",
        "    z1 = xb @ W1 + b1\n",
        "    h1 = relu(z1)\n",
        "    pred = h1 @ W2 + b2\n",
        "    error = pred - yb\n",
        "    loss = np.mean(error**2)\n",
        "\n",
        "    grad_pred = 2 * error / len(xb)\n",
        "    grad_W2 = h1.T @ grad_pred\n",
        "    grad_b2 = grad_pred.sum(axis=0, keepdims=True)\n",
        "    grad_h1 = grad_pred @ W2.T\n",
        "    grad_z1 = grad_h1 * relu_grad(z1)\n",
        "    grad_W1 = xb.T @ grad_z1\n",
        "    grad_b1 = grad_z1.sum(axis=0, keepdims=True)\n",
        "\n",
        "    W2 -= lr * grad_W2\n",
        "    b2 -= lr * grad_b2\n",
        "    W1 -= lr * grad_W1\n",
        "    b1 -= lr * grad_b1\n",
        "    losses.append(loss)\n",
        "\n",
        "pd.Series(losses, name=\"mse\").rolling(20).mean().plot(figsize=(8, 3), title=\"Training loss\")\n",
        "plt.show()\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Code Cell 5 Explanation\n",
        "\n",
        "**What this cell does:** This cell advances **Neural Network Basics From Scratch** by working on forecast metrics. It creates or updates `valid_pred_log`, `valid_pred`, `valid_actual` and prepares evidence that later cells use rather than hiding state in prose.\n",
        "\n",
        "**Why it matters:** The goal is tied to this lesson's forecasting focus: Implement a small MLP with NumPy to forecast log demand from engineered features. Each object is kept inspectable so the learner can connect code, assumptions, and modeling consequences.\n",
        "\n",
        "**Key operations to notice:** evaluates scale-weighted forecast error; evaluates symmetric percentage forecast error\n",
        "\n",
        "**What to inspect:** Before moving on, inspect shapes, date ranges, metric values, segment behavior, or generated tables. If a value looks surprisingly good, surprisingly bad, or unavailable at forecast time, treat that as a modeling clue.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "valid_pred_log = relu(X_valid @ W1 + b1) @ W2 + b2\n",
        "valid_pred = np.expm1(valid_pred_log.ravel())\n",
        "valid_actual = np.expm1(y_valid.ravel())\n",
        "\n",
        "{\"valid_wmape\": wmape(valid_actual, valid_pred), \"valid_smape\": smape(valid_actual, valid_pred)}\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Lesson Recap\n",
        "\n",
        "In this lesson, we used 5 runnable code cells to work through **Neural Network Basics From Scratch**. The practical focus was: Implement a small MLP with NumPy to forecast log demand from engineered features.\n",
        "\n",
        "We did this because deep learning for demand forecasting is not only about choosing an architecture. The learner needs to understand the data contract, the target and horizon, the validation path, the metric, and the operational decision supported by the forecast.\n",
        "\n",
        "The core takeaways were:\n",
        "\n",
        "- Trace a forward pass through dense layers and ReLU.\n",
        "- Compute gradients for a one-hidden-layer network.\n",
        "- Connect feature scaling and target scaling to stable optimization.\n",
        "\n",
        "By the end, you should be able to explain not just what the code produced, but why each step was necessary and what could go wrong if the same step were skipped or performed with leakage.\n",
        "\n",
        "**Senior-readiness reminder:** You can debug a training loop by inspecting shapes, scales, loss movement, and gradients.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Exercises\n",
        "\n",
        "- Print the shape of every intermediate tensor in the forward pass.\n",
        "- Change the hidden width from 32 to 8 and then 128. What changes?\n",
        "- Try training without feature standardization and explain the result.\n"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python (deep-learning-demand)",
      "language": "python",
      "name": "deep-learning-demand"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.12"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 5
}
