{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "# Lesson 10: Probabilistic Forecasting and Quantiles\n",
        "\n",
        "**CS230 inspiration:** Custom losses, model outputs, and decision-focused evaluation.\n",
        "\n",
        "**Demand forecasting focus:** Forecast demand quantiles for inventory decisions instead of only point forecasts.\n",
        "\n",
        "**Learning objectives**\n",
        "\n",
        "- Train a model with pinball loss.\n",
        "- Evaluate calibration with interval coverage.\n",
        "- Connect quantile choice to service level and stockout risk.\n",
        "\n",
        "**Senior-readiness checkpoint:** You can explain why a good mean forecast can still be a poor inventory forecast.\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 torch import nn\n",
        "from torch.utils.data import DataLoader, TensorDataset\n",
        "from demand_forecasting_curriculum.modeling import Standardizer, set_seed\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Code Cell 2 Explanation\n",
        "\n",
        "**What this cell does:** This cell advances **Probabilistic Forecasting and Quantiles** by working on synthetic demand generation, time-based splitting, supervised feature construction. It creates or updates `quantiles`, `df`, `supervised`, `train`, `valid`, `_` 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: Forecast demand quantiles for inventory decisions instead of only point forecasts. 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; batches examples for neural-network training; packages tensors into a PyTorch dataset\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",
        "quantiles = torch.tensor([0.1, 0.5, 0.9]).float()\n",
        "\n",
        "df = generate_daily_demand(n_stores=4, n_items=6, periods=520, seed=SEED)\n",
        "supervised = make_supervised_table(df, horizon=7)\n",
        "train, valid, _ = time_series_split(supervised, valid_days=60, test_days=60)\n",
        "feature_cols = [\"store_id\", \"item_id\", *DEFAULT_FEATURE_COLUMNS]\n",
        "\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",
        "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",
        "\n",
        "train_loader = DataLoader(TensorDataset(torch.tensor(X_train), torch.tensor(y_train)), batch_size=256, shuffle=True)\n",
        "valid_tensor = torch.tensor(X_valid)\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Code Cell 3 Explanation\n",
        "\n",
        "**What this cell does:** This cell advances **Probabilistic Forecasting and Quantiles** by working on model training, model definition. It creates or updates `model`, `optimizer` 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: Forecast demand quantiles for inventory decisions instead of only point forecasts. Each object is kept inspectable so the learner can connect code, assumptions, and modeling consequences.\n",
        "\n",
        "**Key operations to notice:** updates model weights after backpropagation; computes gradients for model parameters\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": [
        "class QuantileMLP(nn.Module):\n",
        "    def __init__(self, n_features, n_quantiles):\n",
        "        super().__init__()\n",
        "        self.net = nn.Sequential(\n",
        "            nn.Linear(n_features, 96),\n",
        "            nn.ReLU(),\n",
        "            nn.Linear(96, 48),\n",
        "            nn.ReLU(),\n",
        "            nn.Linear(48, n_quantiles),\n",
        "        )\n",
        "\n",
        "    def forward(self, x):\n",
        "        return self.net(x)\n",
        "\n",
        "def quantile_loss(prediction, target, qs):\n",
        "    error = target.unsqueeze(1) - prediction\n",
        "    return torch.maximum(qs * error, (qs - 1) * error).mean()\n",
        "\n",
        "model = QuantileMLP(X_train.shape[1], len(quantiles))\n",
        "optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3, weight_decay=1e-4)\n",
        "\n",
        "for epoch in range(6):\n",
        "    model.train()\n",
        "    for xb, yb in train_loader:\n",
        "        optimizer.zero_grad(set_to_none=True)\n",
        "        loss = quantile_loss(model(xb), yb, quantiles)\n",
        "        loss.backward()\n",
        "        optimizer.step()\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Code Cell 4 Explanation\n",
        "\n",
        "**What this cell does:** This cell advances **Probabilistic Forecasting and Quantiles** by working on forecast metrics. It creates or updates `pred_quantiles`, `actual`, `q10`, `q50`, `q90` 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: Forecast demand quantiles for inventory decisions instead of only point forecasts. 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 quantile forecast quality; checks whether prediction intervals contain actual demand; runs inference without tracking gradients\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": [
        "model.eval()\n",
        "with torch.no_grad():\n",
        "    pred_log_quantiles = model(valid_tensor).numpy()\n",
        "\n",
        "pred_quantiles = np.expm1(pred_log_quantiles)\n",
        "actual = valid[\"y\"].to_numpy()\n",
        "q10, q50, q90 = pred_quantiles.T\n",
        "\n",
        "{\n",
        "    \"q50_wmape\": wmape(actual, q50),\n",
        "    \"p10_pinball\": pinball_loss(actual, q10, 0.1),\n",
        "    \"p50_pinball\": pinball_loss(actual, q50, 0.5),\n",
        "    \"p90_pinball\": pinball_loss(actual, q90, 0.9),\n",
        "    \"p10_p90_coverage\": interval_coverage(actual, q10, q90),\n",
        "    \"mean_interval_width\": float(np.mean(q90 - q10)),\n",
        "}\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Lesson Recap\n",
        "\n",
        "In this lesson, we used 4 runnable code cells to work through **Probabilistic Forecasting and Quantiles**. The practical focus was: Forecast demand quantiles for inventory decisions instead of only point forecasts.\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",
        "- Train a model with pinball loss.\n",
        "- Evaluate calibration with interval coverage.\n",
        "- Connect quantile choice to service level and stockout risk.\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 explain why a good mean forecast can still be a poor inventory forecast.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Exercises\n",
        "\n",
        "- Train quantiles 0.05, 0.50, and 0.95 and compare coverage.\n",
        "- Find segments where intervals are too narrow.\n",
        "- Write an inventory rule that uses the p90 forecast instead of the median.\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
}
