{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "# Lesson 15: Robustness, Drift, and Monitoring\n",
        "\n",
        "**CS230 inspiration:** Robustness, adversarial thinking, ML strategy, and deployment-aware evaluation.\n",
        "\n",
        "**Demand forecasting focus:** Simulate distribution shift and build monitoring metrics for forecast quality and feature drift.\n",
        "\n",
        "**Learning objectives**\n",
        "\n",
        "- Distinguish data drift, concept drift, and performance drift.\n",
        "- Compute rolling forecast metrics.\n",
        "- Build feature drift checks that are simple enough to operationalize.\n",
        "\n",
        "**Senior-readiness checkpoint:** You can design a monitoring plan with thresholds, owners, and retraining triggers.\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",
        "from sklearn.ensemble import HistGradientBoostingRegressor\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Code Cell 2 Explanation\n",
        "\n",
        "**What this cell does:** This cell advances **Robustness, Drift, and Monitoring** by working on synthetic demand generation, time-based splitting, supervised feature construction, forecast metrics. It creates or updates `df`, `supervised`, `train`, `valid`, `test`, `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: Simulate distribution shift and build monitoring metrics for forecast quality and feature drift. 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; trains a strong tabular baseline; evaluates scale-weighted 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": [
        "df = generate_daily_demand(n_stores=4, n_items=6, periods=620, seed=SEED)\n",
        "supervised = make_supervised_table(df, horizon=7)\n",
        "train, valid, test = time_series_split(supervised, valid_days=75, test_days=90)\n",
        "feature_cols = [\"store_id\", \"item_id\", *DEFAULT_FEATURE_COLUMNS]\n",
        "\n",
        "model = HistGradientBoostingRegressor(max_iter=120, learning_rate=0.04, random_state=SEED)\n",
        "model.fit(train[feature_cols], train[\"y\"])\n",
        "scored = test.assign(prediction=model.predict(test[feature_cols]))\n",
        "wmape(scored[\"y\"], scored[\"prediction\"])\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Code Cell 3 Explanation\n",
        "\n",
        "**What this cell does:** This cell advances **Robustness, Drift, and Monitoring** by working on forecast metrics, visualization. It creates or updates `daily`, `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: Simulate distribution shift and build monitoring metrics for forecast quality and feature drift. 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": [
        "daily = (\n",
        "    scored.groupby(\"date\")\n",
        "    .apply(lambda part: wmape(part[\"y\"], part[\"prediction\"]), include_groups=False)\n",
        "    .reset_index(name=\"daily_wmape\")\n",
        "    .sort_values(\"date\")\n",
        ")\n",
        "daily[\"rolling_14d_wmape\"] = daily[\"daily_wmape\"].rolling(14, min_periods=3).mean()\n",
        "\n",
        "ax = daily.plot(x=\"date\", y=\"rolling_14d_wmape\", figsize=(9, 3), legend=False)\n",
        "ax.set_ylabel(\"Rolling WMAPE\")\n",
        "ax.set_title(\"Forecast performance monitoring\")\n",
        "plt.show()\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Code Cell 4 Explanation\n",
        "\n",
        "**What this cell does:** This cell advances **Robustness, Drift, and Monitoring** by working on the lesson workflow. It creates or updates `drift` 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: Simulate distribution shift and build monitoring metrics for forecast quality and feature drift. Each object is kept inspectable so the learner can connect code, assumptions, and modeling consequences.\n",
        "\n",
        "**Key operations to notice:** 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": [
        "def population_stability_index(reference, current, bins=10):\n",
        "    edges = np.quantile(reference, np.linspace(0, 1, bins + 1))\n",
        "    edges = np.unique(edges)\n",
        "    ref_counts, _ = np.histogram(reference, bins=edges)\n",
        "    cur_counts, _ = np.histogram(current, bins=edges)\n",
        "    ref_pct = np.clip(ref_counts / max(ref_counts.sum(), 1), 1e-6, 1)\n",
        "    cur_pct = np.clip(cur_counts / max(cur_counts.sum(), 1), 1e-6, 1)\n",
        "    return float(np.sum((cur_pct - ref_pct) * np.log(cur_pct / ref_pct)))\n",
        "\n",
        "drift = pd.DataFrame(\n",
        "    [\n",
        "        {\n",
        "            \"feature\": col,\n",
        "            \"psi\": population_stability_index(train[col].to_numpy(), test[col].to_numpy()),\n",
        "        }\n",
        "        for col in [\"price\", \"promo\", \"lag_7\", \"rolling_mean_28\"]\n",
        "    ]\n",
        ").sort_values(\"psi\", ascending=False)\n",
        "drift\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Lesson Recap\n",
        "\n",
        "In this lesson, we used 4 runnable code cells to work through **Robustness, Drift, and Monitoring**. The practical focus was: Simulate distribution shift and build monitoring metrics for forecast quality and feature drift.\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",
        "- Distinguish data drift, concept drift, and performance drift.\n",
        "- Compute rolling forecast metrics.\n",
        "- Build feature drift checks that are simple enough to operationalize.\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 design a monitoring plan with thresholds, owners, and retraining triggers.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Exercises\n",
        "\n",
        "- Create a threshold policy for rolling WMAPE alerts.\n",
        "- Add a synthetic demand shock to the test set and inspect monitoring behavior.\n",
        "- Define who owns feature drift, model drift, and business KPI drift.\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
}
