{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "# Lesson 05: Optimization, Regularization, and Initialization\n",
        "\n",
        "**CS230 inspiration:** Practical aspects of deep learning, initialization, regularization, gradient checking, optimization algorithms, and batch normalization.\n",
        "\n",
        "**Demand forecasting focus:** Compare learning rates, dropout, weight decay, and initialization choices on the same demand task.\n",
        "\n",
        "**Learning objectives**\n",
        "\n",
        "- Recognize underfitting, overfitting, and unstable optimization signals.\n",
        "- Understand why regularization is a forecasting decision, not just a modeling trick.\n",
        "- Build a repeatable experiment table.\n",
        "\n",
        "**Senior-readiness checkpoint:** You can choose optimization settings based on validation behavior and operational risk, not vibes.\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",
        "\n",
        "import torch\n",
        "from demand_forecasting_curriculum.modeling import (\n",
        "    MLPRegressor,\n",
        "    Standardizer,\n",
        "    make_regression_loader,\n",
        "    predict_regression_model,\n",
        "    set_seed,\n",
        "    train_regression_model,\n",
        ")\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Code Cell 2 Explanation\n",
        "\n",
        "**What this cell does:** This cell advances **Optimization, Regularization, and Initialization** 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: Compare learning rates, dropout, weight decay, and initialization choices on the same demand task. 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; fits scaling parameters on training data only; wraps NumPy arrays in PyTorch DataLoaders\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": [
        "set_seed(SEED)\n",
        "df = generate_daily_demand(n_stores=4, n_items=6, periods=480, seed=SEED)\n",
        "supervised = make_supervised_table(df, horizon=7)\n",
        "train, valid, _ = time_series_split(supervised, valid_days=60, test_days=45)\n",
        "\n",
        "feature_cols = [\"store_id\", \"item_id\", *DEFAULT_FEATURE_COLUMNS]\n",
        "X_train_raw = train[feature_cols].to_numpy(dtype=np.float32)\n",
        "X_valid_raw = valid[feature_cols].to_numpy(dtype=np.float32)\n",
        "y_train = np.log1p(train[\"y\"].to_numpy(dtype=np.float32))\n",
        "y_valid = np.log1p(valid[\"y\"].to_numpy(dtype=np.float32))\n",
        "\n",
        "scaler = Standardizer.fit(X_train_raw)\n",
        "X_train = scaler.transform(X_train_raw).astype(np.float32)\n",
        "X_valid = scaler.transform(X_valid_raw).astype(np.float32)\n",
        "train_loader = make_regression_loader(X_train, y_train, batch_size=256, shuffle=True)\n",
        "valid_loader = make_regression_loader(X_valid, y_valid, batch_size=512, shuffle=False)\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Code Cell 3 Explanation\n",
        "\n",
        "**What this cell does:** This cell advances **Optimization, Regularization, and Initialization** by working on forecast metrics, model training, model definition. It creates or updates `configs`, `rows`, `results` 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: Compare learning rates, dropout, weight decay, and initialization choices on the same demand task. Each object is kept inspectable so the learner can connect code, assumptions, and modeling consequences.\n",
        "\n",
        "**Key operations to notice:** instantiates a feed-forward demand forecasting model; runs the shared PyTorch training loop; generates validation or test predictions from a trained model; evaluates scale-weighted forecast error; creates an inspectable table for assumptions, metrics, or decisions\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": [
        "configs = [\n",
        "    {\"name\": \"small_lr\", \"lr\": 3e-4, \"dropout\": 0.00, \"weight_decay\": 0.0},\n",
        "    {\"name\": \"baseline\", \"lr\": 1e-3, \"dropout\": 0.05, \"weight_decay\": 1e-4},\n",
        "    {\"name\": \"high_lr\", \"lr\": 5e-3, \"dropout\": 0.05, \"weight_decay\": 1e-4},\n",
        "    {\"name\": \"regularized\", \"lr\": 1e-3, \"dropout\": 0.20, \"weight_decay\": 1e-3},\n",
        "]\n",
        "\n",
        "rows = []\n",
        "for config in configs:\n",
        "    set_seed(SEED)\n",
        "    model = MLPRegressor(X_train.shape[1], hidden_sizes=(128, 64), dropout=config[\"dropout\"])\n",
        "    history = train_regression_model(\n",
        "        model,\n",
        "        train_loader,\n",
        "        valid_loader,\n",
        "        epochs=5,\n",
        "        learning_rate=config[\"lr\"],\n",
        "        weight_decay=config[\"weight_decay\"],\n",
        "    )\n",
        "    pred = np.expm1(predict_regression_model(model, X_valid))\n",
        "    actual = np.expm1(y_valid)\n",
        "    rows.append(\n",
        "        {\n",
        "            **config,\n",
        "            \"final_train_mae_log\": history[-1][\"train_mae\"],\n",
        "            \"final_valid_mae_log\": history[-1][\"valid_mae\"],\n",
        "            \"valid_wmape\": wmape(actual, pred),\n",
        "        }\n",
        "    )\n",
        "\n",
        "results = pd.DataFrame(rows).sort_values(\"valid_wmape\")\n",
        "results\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Code Cell 4 Explanation\n",
        "\n",
        "**What this cell does:** This cell advances **Optimization, Regularization, and Initialization** by working on forecast metrics, visualization. It creates or updates `ax` 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: Compare learning rates, dropout, weight decay, and initialization choices on the same demand task. 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; 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": [
        "ax = results.sort_values(\"name\").plot.bar(x=\"name\", y=\"valid_wmape\", legend=False, figsize=(8, 3))\n",
        "ax.set_ylabel(\"Validation WMAPE\")\n",
        "ax.set_title(\"Optimization and regularization comparison\")\n",
        "plt.show()\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Lesson Recap\n",
        "\n",
        "In this lesson, we used 4 runnable code cells to work through **Optimization, Regularization, and Initialization**. The practical focus was: Compare learning rates, dropout, weight decay, and initialization choices on the same demand task.\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",
        "- Recognize underfitting, overfitting, and unstable optimization signals.\n",
        "- Understand why regularization is a forecasting decision, not just a modeling trick.\n",
        "- Build a repeatable experiment table.\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 choose optimization settings based on validation behavior and operational risk, not vibes.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Exercises\n",
        "\n",
        "- Add a wider network and determine if it needs more regularization.\n",
        "- Run the same configs with a different seed and check whether the ranking is stable.\n",
        "- Describe what monitoring signal would reveal an overly aggressive learning rate in production retraining.\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
}
