{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "# Lesson 06: ML Strategy, Splits, and Error Analysis\n",
        "\n",
        "**CS230 inspiration:** Structuring machine learning projects, train/dev/test strategy, error analysis, and mismatch.\n",
        "\n",
        "**Demand forecasting focus:** Diagnose forecast errors by time, item, store, promotion, stockout, and volume segment.\n",
        "\n",
        "**Learning objectives**\n",
        "\n",
        "- Design split logic that matches deployment.\n",
        "- Quantify where a model fails instead of only reporting one global score.\n",
        "- Separate model error from data and process problems.\n",
        "\n",
        "**Senior-readiness checkpoint:** You can turn aggregate forecast failure into a ranked debugging agenda.\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 **ML Strategy, Splits, and Error Analysis** 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: Diagnose forecast errors by time, item, store, promotion, stockout, and volume segment. 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=5, n_items=8, periods=600, seed=SEED)\n",
        "supervised = make_supervised_table(df, horizon=14)\n",
        "train, valid, test = time_series_split(supervised, valid_days=75, test_days=75)\n",
        "\n",
        "feature_cols = [\"store_id\", \"item_id\", *DEFAULT_FEATURE_COLUMNS]\n",
        "model = HistGradientBoostingRegressor(max_iter=120, learning_rate=0.04, random_state=SEED)\n",
        "model.fit(train[feature_cols], train[\"y\"])\n",
        "valid_scored = valid.assign(prediction=model.predict(valid[feature_cols]))\n",
        "wmape(valid_scored[\"y\"], valid_scored[\"prediction\"])\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Code Cell 3 Explanation\n",
        "\n",
        "**What this cell does:** This cell advances **ML Strategy, Splits, and Error Analysis** by working on forecast metrics. It creates or updates `by_item`, `by_store`, `by_promo` 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: Diagnose forecast errors by time, item, store, promotion, stockout, and volume segment. 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\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 segment_wmape(frame, by):\n",
        "    return (\n",
        "        frame.groupby(by)\n",
        "        .apply(lambda part: wmape(part[\"y\"], part[\"prediction\"]), include_groups=False)\n",
        "        .reset_index(name=\"wmape\")\n",
        "        .sort_values(\"wmape\", ascending=False)\n",
        "    )\n",
        "\n",
        "by_item = segment_wmape(valid_scored, [\"item_id\"])\n",
        "by_store = segment_wmape(valid_scored, [\"store_id\"])\n",
        "by_promo = segment_wmape(valid_scored, [\"promo\"])\n",
        "\n",
        "by_item.head(), by_store.head(), by_promo\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Code Cell 4 Explanation\n",
        "\n",
        "**What this cell does:** This cell advances **ML Strategy, Splits, and Error Analysis** by working on forecast metrics. It creates or updates `valid_scored`, `diagnostics` 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: Diagnose forecast errors by time, item, store, promotion, stockout, and volume segment. 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\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_scored = valid_scored.assign(\n",
        "    abs_error=lambda x: (x[\"y\"] - x[\"prediction\"]).abs(),\n",
        "    volume_bucket=lambda x: pd.qcut(x[\"lag_28\"], q=4, labels=[\"low\", \"mid_low\", \"mid_high\", \"high\"]),\n",
        ")\n",
        "\n",
        "diagnostics = {\n",
        "    \"by_volume\": segment_wmape(valid_scored, [\"volume_bucket\"]),\n",
        "    \"by_stockout_at_origin\": segment_wmape(valid_scored, [\"stockout\"]),\n",
        "    \"worst_rows\": valid_scored.sort_values(\"abs_error\", ascending=False).head(10)[\n",
        "        [\"date\", \"store_id\", \"item_id\", \"y\", \"prediction\", \"promo\", \"stockout\"]\n",
        "    ],\n",
        "}\n",
        "diagnostics[\"by_volume\"]\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Code Cell 5 Explanation\n",
        "\n",
        "**What this cell does:** This cell advances **ML Strategy, Splits, and Error Analysis** by working on the lesson workflow. It creates or updates `worst` 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: Diagnose forecast errors by time, item, store, promotion, stockout, and volume segment. 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": [
        "worst = diagnostics[\"worst_rows\"]\n",
        "worst\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Lesson Recap\n",
        "\n",
        "In this lesson, we used 5 runnable code cells to work through **ML Strategy, Splits, and Error Analysis**. The practical focus was: Diagnose forecast errors by time, item, store, promotion, stockout, and volume segment.\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",
        "- Design split logic that matches deployment.\n",
        "- Quantify where a model fails instead of only reporting one global score.\n",
        "- Separate model error from data and process problems.\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 turn aggregate forecast failure into a ranked debugging agenda.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Exercises\n",
        "\n",
        "- Create an error slice for holiday vs non-holiday dates.\n",
        "- Rank the top three suspected root causes for the worst item segment.\n",
        "- Write one policy for when validation/test distributions no longer represent deployment.\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
}
