{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "77e5a6b1",
   "metadata": {
    "deletable": false,
    "editable": false
   },
   "outputs": [],
   "source": [
    "# Initialize Otter\n",
    "import otter\n",
    "grader = otter.Notebook(\"practice10.ipynb\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "p10-001",
   "metadata": {},
   "source": [
    "**Student names and e-mails:**\n",
    "\n",
    "_YOUR NAME — your@calvin.edu_\n",
    "\n",
    "_YOUR NAME — your@calvin.edu_"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "p10-002",
   "metadata": {},
   "source": [
    "# Practice 10 — Rare Legends and Daily Births: Imbalanced and Time-Series Data\n",
    "\n",
    "Two datasets this time, one for each of this week's classes:\n",
    "\n",
    "* **Part 1:** 721 Pokémon, of which only 46 are *legendary*. Can a model find the rare ones, and what does \"accurate\" mean when they are rare?\n",
    "* **Part 2:** every day's number of births in the United States, 2000 to 2014. How do we forecast a day we haven't seen yet, and test the forecast honestly?\n",
    "\n",
    "| SLO | Description |\n",
    "|-----|-------------|\n",
    "| **12A** | Identify class imbalance in a dataset and apply techniques such as resampling or adjusted decision thresholds to address it |\n",
    "| **12B** | Engineer features for time-series data (lag features, rolling statistics) and use time-aware train-test splits to avoid data leakage |"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "p10-003",
   "metadata": {},
   "source": [
    "### Setup (given — just run it)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "p10-004",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "import plotly.express as px\n",
    "from sklearn.model_selection import train_test_split, cross_val_predict, cross_validate, cross_val_score, KFold, TimeSeriesSplit\n",
    "from sklearn.pipeline import make_pipeline\n",
    "from sklearn.preprocessing import StandardScaler\n",
    "from sklearn.linear_model import LogisticRegression, LinearRegression\n",
    "from sklearn.neighbors import KNeighborsClassifier\n",
    "from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor\n",
    "from sklearn.metrics import accuracy_score, recall_score, precision_score, mean_absolute_error\n",
    "\n",
    "# imbalanced-learn (imblearn) comes with Colab; elsewhere: pip install imbalanced-learn\n",
    "from imblearn.over_sampling import SMOTE, RandomOverSampler\n",
    "from imblearn.under_sampling import RandomUnderSampler\n",
    "from imblearn.pipeline import make_pipeline as make_imb_pipeline\n",
    "from imblearn.ensemble import BalancedRandomForestClassifier"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "p10-005",
   "metadata": {},
   "source": [
    "---\n",
    "## Part 1 — Legendary Pokémon (SLO 12A)\n",
    "\n",
    "In the Pokémon games, a few creatures are **legendary**: rare, powerful, usually one of a kind. This dataset has the first six generations of Pokémon (the games from 1996 to 2013), one row per species, with the six **base stats** the games use in battle.\n",
    "\n",
    "| Column | What it holds |\n",
    "|---|---|\n",
    "| `name` | the Pokémon |\n",
    "| `type1`, `type2` | its type(s), like Fire or Water (`type2` is blank for single-type Pokémon) |\n",
    "| `generation` | the game generation that introduced it, 1 to 6 |\n",
    "| `hp` | hit points: how much damage it can take |\n",
    "| `attack`, `defense` | strength of its physical moves, and resistance to them |\n",
    "| `sp_attack`, `sp_defense` | the same for special moves (like fire or psychic attacks) |\n",
    "| `speed` | who moves first in a battle |\n",
    "| `legendary` | **the label**: 1 = legendary, 0 = not |\n",
    "\n",
    "<sub>Data: A. Barradas, \"Pokemon with Stats\" (Kaggle, 2016), CC0, one row per species (Mega Evolutions and other alternate forms removed). Pokémon and Pokémon names are trademarks of Nintendo, Creatures and Game Freak.</sub>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "p10-006",
   "metadata": {},
   "outputs": [],
   "source": [
    "pokemon = pd.read_csv(\"https://cs.calvin.edu/courses/data/202/26fa/datasets/pokemon.csv\")\n",
    "print(pokemon[\"legendary\"].value_counts())\n",
    "print(f\"share of legendary Pokémon: {pokemon['legendary'].mean():.1%}\")\n",
    "pokemon.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "p10-007",
   "metadata": {},
   "source": [
    "46 of 721: **6.4%**. This is **imbalanced data**: the majority class (ordinary Pokémon) outnumbers the minority (legendary) about 15 to 1.\n",
    "\n",
    "The features are the six stats. The split is given. `stratify=y` keeps the share of legendaries the same in the training and the test set: with only 46 of them, a plain random split could put 8 or 16 in the test set just by luck."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "p10-008",
   "metadata": {},
   "outputs": [],
   "source": [
    "stats = [\"hp\", \"attack\", \"defense\", \"sp_attack\", \"sp_defense\", \"speed\"]\n",
    "X = pokemon[stats]\n",
    "y = pokemon[\"legendary\"]\n",
    "\n",
    "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=1, stratify=y)\n",
    "print(f\"training: {len(y_train)} Pokémon, {y_train.sum()} legendary | test: {len(y_test)} Pokémon, {y_test.sum()} legendary\")\n",
    "\n",
    "lazy = np.zeros(len(y_test))          # a lazy \"model\": nobody is legendary\n",
    "print(f\"lazy model | accuracy {accuracy_score(y_test, lazy):.3f} | recall {recall_score(y_test, lazy):.3f}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "p10-009",
   "metadata": {},
   "source": [
    "The lazy model is **93.4%** accurate and finds **none** of the 12 test legendaries. Accuracy rewards guessing the majority, so from now on we watch **recall** (of the real legendaries, the share the model finds) and **precision** (of the Pokémon it calls legendary, the share that really are)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "p10-011",
   "metadata": {
    "deletable": false,
    "editable": false
   },
   "source": [
    "### Task 12A.1 — Accurate, but Is It Finding Them? *(2 pts)*\n",
    "\n",
    "1. Build a pipeline that scales the stats, then runs logistic regression: `make_pipeline(StandardScaler(), LogisticRegression())`. Store it in `model` and fit it on the training Pokémon.\n",
    "2. Store its predictions for the test Pokémon in `y_pred`.\n",
    "3. Store its test **accuracy**, **recall** and **precision** in `acc`, `rec` and `prec`. (*Hint:* `accuracy_score(y_test, y_pred)`, and the same for `recall_score` and `precision_score`.)\n",
    "\n",
    "The printout is given."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "p10-013",
   "metadata": {
    "tags": [
     "otter_answer_cell"
    ]
   },
   "outputs": [],
   "source": [
    "model = ...\n",
    "...\n",
    "y_pred = ...\n",
    "acc = ...\n",
    "rec = ...\n",
    "prec = ...\n",
    "\n",
    "print(f\"logistic regression | accuracy {acc:.3f} | recall {rec:.3f} | precision {prec:.3f} | called legendary: {y_pred.sum()}\")\n",
    "test_pokemon = pokemon.loc[X_test.index].assign(total=X_test.sum(axis=1), called=y_pred)\n",
    "test_pokemon[test_pokemon[\"legendary\"] + test_pokemon[\"called\"] > 0][[\"name\", \"total\", \"legendary\", \"called\"]].sort_values(\"total\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f3241414",
   "metadata": {
    "deletable": false,
    "editable": false
   },
   "outputs": [],
   "source": [
    "grader.check(\"12A.1\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "p10-020",
   "metadata": {},
   "source": [
    "**93.9%** accurate, half a point above the lazy model, and it finds only **4 of the 12** legendaries (recall 0.33).\n",
    "\n",
    "The table (given) shows each test Pokémon that is legendary or was called legendary, with its **total**, the sum of its six stats. The four it catches are giants: Giratina, Reshiram, Xerneas and Yveltal, each with a total of 680. The eight it misses (Articuno, Raikou, Regirock, Regice, Uxie, Mesprit, Azelf, Terrakion) all have 580, close to the strongest ordinary Pokémon: Hydreigon (600), Manaphy (600) and Slaking (670) are its three false alarms.\n",
    "\n",
    "That's the lean toward the majority. The eight missed legendaries get probabilities between **0.23 and 0.48**: far above the 6% of legendaries overall, but not \"more likely than not\". Logistic regression learned from 506 ordinary Pokémon and only 34 legendary ones, and it keeps its mistakes, counted over all of them, as few as it can. With 15 ordinary Pokémon for every legendary, every probability gets pulled toward \"not legendary\". Uxie (0.476) and Raikou (0.474) miss the 0.5 cut by less than 0.03."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "p10-021",
   "metadata": {},
   "source": [
    "---\n",
    "### Moving the Threshold\n",
    "\n",
    "`predict` says \"legendary\" when the probability is at least **0.5**. That threshold is a knob, so we choose it with cross-validation on the **training** Pokémon, never by peeking at the test set. `cross_val_predict` gives each training Pokémon a probability from a model that didn't learn from it."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "p10-023",
   "metadata": {
    "deletable": false,
    "editable": false
   },
   "source": [
    "### Task 12A.2 — Choose a Threshold *(2 pts)*\n",
    "\n",
    "1. Store each training Pokémon's cross-validated probability of being legendary in `p_train`: `cross_val_predict(model, X_train, y_train, cv=5, method=\"predict_proba\")[:, 1]`. (Column `1` is the probability of class 1, legendary.) The table of thresholds is given.\n",
    "2. The table shows that **0.2** catches almost every legendary at about the same precision. Use it on the test set: the model is already fit, so store `model.predict_proba(X_test)[:, 1] >= 0.2` in `called`, then the test recall and precision of `called` in `rec_02` and `prec_02`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "p10-025",
   "metadata": {
    "tags": [
     "otter_answer_cell"
    ]
   },
   "outputs": [],
   "source": [
    "p_train = ...\n",
    "\n",
    "rows = []\n",
    "for t in [0.5, 0.4, 0.3, 0.2, 0.1, 0.05]:\n",
    "    flagged = p_train >= t\n",
    "    rows.append({\"threshold\": t, \"called legendary\": flagged.sum(),\n",
    "                 \"recall\": recall_score(y_train, flagged), \"precision\": precision_score(y_train, flagged)})\n",
    "print(pd.DataFrame(rows).round(3).to_string(index=False))\n",
    "\n",
    "called = ...\n",
    "rec_02 = ...\n",
    "prec_02 = ...\n",
    "print(f\"\\ntest set, threshold 0.2 | recall {rec_02:.3f} | precision {prec_02:.3f} | called legendary: {called.sum()}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "764b625b",
   "metadata": {
    "deletable": false,
    "editable": false
   },
   "outputs": [],
   "source": [
    "grader.check(\"12A.2\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "p10-032",
   "metadata": {},
   "source": [
    "In cross-validation, lowering the threshold from 0.5 to **0.2** raises recall from 0.65 to **0.97**, and precision barely moves (0.73 to 0.70). The legendaries' stats do stand out; the 0.5 line was just in the wrong place. Below 0.2, precision drops fast: at 0.05, more than half of the Pokémon called legendary are not.\n",
    "\n",
    "On the test set, 0.2 finds **all 12** legendaries, with 4 false alarms out of 16 (precision 0.75): Hydreigon, Manaphy, Slaking and Volcarona.\n",
    "\n",
    "> 📌 **One split:** 12 test legendaries. One legendary is more than 8 points of recall."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "p10-033",
   "metadata": {},
   "source": [
    "---\n",
    "### Rebalancing, for a Model Without Weights\n",
    "\n",
    "kNN (Week 6) has no `class_weight` option, and with 15 ordinary Pokémon for every legendary, most of a legendary's nearest neighbors are ordinary (given):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "p10-034",
   "metadata": {},
   "outputs": [],
   "source": [
    "knn = make_pipeline(StandardScaler(), KNeighborsClassifier())\n",
    "knn_scores = cross_validate(knn, X_train, y_train, cv=5, scoring=[\"recall\", \"precision\"])\n",
    "print(f\"kNN, k = 5 | recall {knn_scores['test_recall'].mean():.3f} | precision {knn_scores['test_precision'].mean():.3f}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "p10-035",
   "metadata": {},
   "source": [
    "Recall **0.52**: kNN misses about half the legendaries. SMOTE can help: it makes new, synthetic legendaries on the line between a real legendary and one of its nearest legendary neighbors, until both classes are the same size."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "p10-037",
   "metadata": {
    "deletable": false,
    "editable": false
   },
   "source": [
    "### Task 12A.3 — SMOTE for kNN *(2 pts)*\n",
    "\n",
    "1. Build an **imblearn** pipeline that scales, applies SMOTE, then runs kNN: `make_imb_pipeline(StandardScaler(), SMOTE(random_state=1), KNeighborsClassifier())`. Store it in `knn_smote`.\n",
    "2. Score it with `cross_validate` on the training Pokémon, with `cv=5` and `scoring=[\"recall\", \"precision\"]`. Store the result in `knn_smote_scores`.\n",
    "\n",
    "The printout is given."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "p10-039",
   "metadata": {
    "tags": [
     "otter_answer_cell"
    ]
   },
   "outputs": [],
   "source": [
    "knn_smote = ...\n",
    "knn_smote_scores = ...\n",
    "\n",
    "print(f\"kNN + SMOTE | recall {knn_smote_scores['test_recall'].mean():.3f} | precision {knn_smote_scores['test_precision'].mean():.3f}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "934c5422",
   "metadata": {
    "deletable": false,
    "editable": false
   },
   "outputs": [],
   "source": [
    "grader.check(\"12A.3\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "p10-046",
   "metadata": {},
   "source": [
    "Recall **0.52 → 0.97**, precision 0.90 → 0.63: SMOTE turned kNN from careful into thorough.\n",
    "\n",
    "Why `make_imb_pipeline` and not scikit-learn's `make_pipeline`? In imblearn's pipeline, a sampler runs only when the pipeline **learns** (`fit`), never when it predicts. So in each round of cross-validation, synthetic legendaries are made from the four folds it learns from, and the held-out fold keeps the real 6% of legendaries. SMOTE-ing all the data first would put synthetic copies of held-out legendaries into the training folds: a leak.\n",
    "\n",
    "The whole toolbox from class, on the same folds (given — about 15 seconds):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "p10-047",
   "metadata": {},
   "outputs": [],
   "source": [
    "options = {\n",
    "    \"logistic, nothing\": make_pipeline(StandardScaler(), LogisticRegression()),\n",
    "    \"logistic, class weights\": make_pipeline(StandardScaler(), LogisticRegression(class_weight=\"balanced\")),\n",
    "    \"logistic, oversample\": make_imb_pipeline(StandardScaler(), RandomOverSampler(random_state=1), LogisticRegression()),\n",
    "    \"logistic, undersample\": make_imb_pipeline(StandardScaler(), RandomUnderSampler(random_state=1), LogisticRegression()),\n",
    "    \"logistic, SMOTE\": make_imb_pipeline(StandardScaler(), SMOTE(random_state=1), LogisticRegression()),\n",
    "    \"kNN, nothing\": knn,\n",
    "    \"kNN, SMOTE\": knn_smote,\n",
    "    \"forest, nothing\": RandomForestClassifier(random_state=1),\n",
    "    \"forest, class weights\": RandomForestClassifier(class_weight=\"balanced\", random_state=1),\n",
    "    # imblearn's newer defaults, written out so every version builds the same forest\n",
    "    \"balanced forest\": BalancedRandomForestClassifier(sampling_strategy=\"all\", replacement=True, bootstrap=False, random_state=1),\n",
    "}\n",
    "rows = []\n",
    "for name, option in options.items():\n",
    "    scores = cross_validate(option, X_train, y_train, cv=5, scoring=[\"recall\", \"precision\"])\n",
    "    rows.append({\"option\": name, \"recall\": scores[\"test_recall\"].mean(), \"precision\": scores[\"test_precision\"].mean()})\n",
    "pd.DataFrame(rows).round(3)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "p10-048",
   "metadata": {},
   "source": [
    "Read it against the class toolbox:\n",
    "\n",
    "* **Logistic regression:** class weights, oversampling and SMOTE all land near recall 0.94–0.97 and precision 0.66–0.69, about where the threshold 0.2 put us. For logistic regression, rebalancing mostly slides the line, like moving the threshold.\n",
    "* **Undersampling** reaches the same recall, but precision falls to **0.47**. With 34 training legendaries, it keeps only 34 ordinary Pokémon too: 68 Pokémon to learn from. Undersampling is for a huge majority, not for small data.\n",
    "* **Forest, class weights:** 0.59 recall, the same as with nothing. A fully grown tree ends in pure leaves, so weighting the rows barely changes its votes. The **balanced forest**, where each tree learns from its own balanced sample, does move: recall 0.82.\n",
    "\n",
    "A fix that helps one model can do nothing for another: compare them with cross-validation.\n",
    "\n",
    "### Who Decides What \"Legendary\" Means?\n",
    "\n",
    "The label comes from the original file, and it doesn't follow a single rule. The games have a separate category, **mythical** Pokémon, usually given out at special events. In this file, Mew, Celebi and Manaphy (mythical) are labeled **not** legendary, while Jirachi, Arceus and Darkrai (also mythical) are labeled **legendary**. So one of the model's \"false alarms\", Manaphy, is a Pokémon that some fans, and some files, would call legendary. Before trusting a recall or precision, ask what the rare class really is, and who decided."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "p10-049",
   "metadata": {},
   "source": [
    "---\n",
    "## Part 2 — Daily Births (SLO 12B)\n",
    "\n",
    "How many babies will be born in the United States next Tuesday? Hospitals plan staff and beds around questions like that. The U.S. Social Security Administration counts the births of every day, and FiveThirtyEight shared the counts for 2000 to 2014, for a story on whether fewer babies are born on Friday the 13th.\n",
    "\n",
    "* `date`: the day\n",
    "* `births`: babies born in the United States that day\n",
    "\n",
    "<sub>Data: FiveThirtyEight, \"U.S. Births\" (US_births_2000-2014_SSA.csv), counts from the Social Security Administration, CC BY 4.0.</sub>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "p10-050",
   "metadata": {},
   "outputs": [],
   "source": [
    "births = pd.read_csv(\"https://cs.calvin.edu/courses/data/202/26fa/datasets/births.csv\", parse_dates=[\"date\"])\n",
    "births[\"day_of_week\"] = births[\"date\"].dt.dayofweek       # 0 = Monday ... 6 = Sunday\n",
    "births[\"day_of_year\"] = births[\"date\"].dt.dayofyear\n",
    "births[\"month\"] = births[\"date\"].dt.month\n",
    "births[\"year\"] = births[\"date\"].dt.year\n",
    "\n",
    "px.line(births, x=\"date\", y=\"births\", title=\"Births per Day in the United States, 2000–2014\",\n",
    "        labels={\"date\": \"\", \"births\": \"births per day\"}).show()\n",
    "births.groupby(\"day_of_week\")[\"births\"].mean().round().rename(index=dict(enumerate([\"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\", \"Sun\"])))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "p10-051",
   "metadata": {},
   "source": [
    "The line looks like two bands, because the days of the week differ so much: from about **11,900** (Monday) to **13,100** (Tuesday) births on an average weekday, but **8,563** on an average Saturday and **7,518** on a Sunday. Many births are scheduled (inductions and planned C-sections), and doctors schedule them on weekdays. The lowest days of all are Christmas Days. And, yes: an average Friday the 13th had 11,950 births, 6% fewer than the Fridays a week before and after it.\n",
    "\n",
    "Across the years, births per day rose to a peak in **2007** (12,002 on average) and then fell (10,931 in 2012)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "p10-053",
   "metadata": {
    "deletable": false,
    "editable": false
   },
   "source": [
    "### Task 12B.1 — Lag Features and a Naive Forecast *(2 pts)*\n",
    "\n",
    "A **lag feature** moves a past value of the label down into the current row, with `shift`.\n",
    "\n",
    "1. Add four columns to `births`:\n",
    "   * `births_1d_ago`: the births of the day before, `births[\"births\"].shift(1)`\n",
    "   * `births_7d_ago`: the same weekday one week before, `shift(7)`\n",
    "   * `births_364d_ago`: the same weekday one year (52 weeks) before, `shift(364)`\n",
    "   * `mean_last_7`: the average of the 7 days before this one, `births[\"births\"].shift(1).rolling(7).mean()`\n",
    "2. (given) Drop the rows whose lags reach before 2000, and split by date: **learn from 2000–2009, forecast 2010–2014**.\n",
    "3. A **naive forecast** copies the past, with no model. Store the test MAE of \"the same as one week ago\" in `naive_mae`: `mean_absolute_error(y[test], births.loc[test, \"births_7d_ago\"])`.\n",
    "\n",
    "The comparison of all the naive forecasts is given."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "p10-055",
   "metadata": {
    "tags": [
     "otter_answer_cell"
    ]
   },
   "outputs": [],
   "source": [
    "births[\"births_1d_ago\"] = ...\n",
    "births[\"births_7d_ago\"] = ...\n",
    "births[\"births_364d_ago\"] = ...\n",
    "births[\"mean_last_7\"] = ...\n",
    "\n",
    "births = births.dropna().reset_index(drop=True)     # the first 364 days have no lag from a year before\n",
    "y = births[\"births\"]\n",
    "learn = births[\"date\"] < \"2010-01-01\"               # learn from the past...\n",
    "test = ~learn                                       # ...forecast 2010-2014\n",
    "print(f\"learn: {learn.sum()} days | test: {test.sum()} days\")\n",
    "\n",
    "naive_mae = ...\n",
    "\n",
    "for lag in [\"births_1d_ago\", \"births_7d_ago\", \"births_364d_ago\", \"mean_last_7\"]:\n",
    "    print(f\"naive forecast, copy {lag:16} | test MAE: {mean_absolute_error(y[test], births.loc[test, lag]):.0f} births\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4eb22e1c",
   "metadata": {
    "deletable": false,
    "editable": false
   },
   "outputs": [],
   "source": [
    "grader.check(\"12B.1\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "p10-062",
   "metadata": {},
   "source": [
    "* **The day before: 1,698.** A Monday copies a Sunday, a Saturday copies a Friday. The nearest past isn't always the most useful.\n",
    "* **A week before: 452.** The same weekday: the weekly cycle lines up.\n",
    "* **The same weekday a year before: 378,** the best of the four. It lines up the week **and** the season.\n",
    "* **The average of the last 7 days: 2,004.** It smooths away the weekday pattern, the most important thing here.\n",
    "\n",
    "Pick lags at the data's cycles. And a model that can't beat 378 isn't worth running."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "p10-064",
   "metadata": {
    "deletable": false,
    "editable": false
   },
   "source": [
    "### Task 12B.2 — Calendar Only, or Calendar and Lags? *(2 pts)*\n",
    "\n",
    "1. Fit a `RandomForestRegressor(random_state=1)` on the training days with the `calendar` columns only (given list), and store its test MAE in `mae_calendar`.\n",
    "2. Fit the same forest with `calendar + lags`, and store its test MAE in `mae_lags`.\n",
    "\n",
    "(*Hint:* `forest.fit(births.loc[learn, columns], y[learn])`, then `mean_absolute_error(y[test], forest.predict(births.loc[test, columns]))`.) The plot is given."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "p10-066",
   "metadata": {
    "tags": [
     "otter_answer_cell"
    ]
   },
   "outputs": [],
   "source": [
    "calendar = [\"day_of_week\", \"day_of_year\", \"month\"]\n",
    "lags = [\"births_1d_ago\", \"births_7d_ago\", \"births_364d_ago\", \"mean_last_7\"]\n",
    "forest = RandomForestRegressor(random_state=1)\n",
    "\n",
    "...\n",
    "calendar_pred = forest.predict(births.loc[test, calendar])\n",
    "mae_calendar = ...\n",
    "\n",
    "...\n",
    "lags_pred = forest.predict(births.loc[test, calendar + lags])\n",
    "mae_lags = ...\n",
    "\n",
    "print(f\"forest, calendar only   | test MAE: {mae_calendar:.0f} | too high by {(calendar_pred - y[test]).mean():.0f} births a day, on average\")\n",
    "print(f\"forest, calendar + lags | test MAE: {mae_lags:.0f} | too high by {(lags_pred - y[test]).mean():.0f} births a day, on average\")\n",
    "weekly = births.loc[test, [\"date\", \"births\"]].assign(**{\"calendar only\": calendar_pred, \"calendar + lags\": lags_pred})\n",
    "px.line(weekly.resample(\"W\", on=\"date\").mean(), y=[\"births\", \"calendar only\", \"calendar + lags\"],\n",
    "        title=\"2010–2014, Averaged by Week: What Happened and the Two Forecasts\",\n",
    "        labels={\"value\": \"births per day\", \"date\": \"\", \"variable\": \"\"}).show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2a31fc07",
   "metadata": {
    "deletable": false,
    "editable": false
   },
   "outputs": [],
   "source": [
    "grader.check(\"12B.2\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "p10-073",
   "metadata": {},
   "source": [
    "**Calendar only: 626**, and too high by **595** births a day on average. For each date, the forest predicts about the average of 2000–2009 for that kind of day, 11,556 births a day, but 2010–2014 averaged 10,979. Births had been falling since 2007, and a forest can't forecast a level it has never seen.\n",
    "\n",
    "**Calendar and lags: 299**, better than the best naive forecast (378). The lags carry the current **level** into each row: if births have been lower lately, the forecast is lower. It still runs a little high (+112), because the decline kept going.\n",
    "\n",
    "On the days it learned from, the lag forest misses by only 103: the usual gap between memorized rows and new ones. Only the test number tells how it forecasts.\n",
    "\n",
    "> 📌 **One split:** one stretch of five years. Another stretch would give other numbers."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "p10-074",
   "metadata": {},
   "source": [
    "### The Week on a Circle? (given)\n",
    "\n",
    "In class, the hour went on a circle so that 11 pm sat next to midnight. Should the **day of the week** go on a circle, so that Sunday sits next to Monday? Three versions of the same linear regression, with the day of the week as a plain number, on a circle, and as categories (one column per day, Week 9's one-hot):\n",
    "\n",
    "> 🎯 **Predict First:** Which will forecast best?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "p10-075",
   "metadata": {},
   "outputs": [],
   "source": [
    "births[\"dow_sin\"] = np.sin(2 * np.pi * births[\"day_of_week\"] / 7)      # a full turn = 7 days\n",
    "births[\"dow_cos\"] = np.cos(2 * np.pi * births[\"day_of_week\"] / 7)\n",
    "versions = {\"a number\": births[[\"day_of_week\"]],\n",
    "            \"a circle\": births[[\"dow_sin\", \"dow_cos\"]],\n",
    "            \"categories\": pd.get_dummies(births[\"day_of_week\"], prefix=\"day\", drop_first=True)}\n",
    "table = {\"actual, 2010-2014\": y[test].groupby(births.loc[test, \"day_of_week\"]).mean()}\n",
    "for name, columns in versions.items():\n",
    "    line = LinearRegression().fit(columns[learn], y[learn])\n",
    "    predicted = pd.Series(line.predict(columns[test]), index=columns[test].index)\n",
    "    print(f\"day of week as {name:10} | test MAE: {mean_absolute_error(y[test], predicted):.0f}\")\n",
    "    table[name] = predicted.groupby(births.loc[test, \"day_of_week\"]).mean()\n",
    "pd.DataFrame(table).round().rename(index=dict(enumerate([\"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\", \"Sun\"])))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "p10-076",
   "metadata": {},
   "source": [
    "* **A number (1,386):** a straight line, falling from Monday (14,009) to Sunday (9,102). Monday is too high, the weekend not low enough.\n",
    "* **A circle (1,250):** barely better. On the circle, Sunday is Monday's neighbor, so the wave drags Monday down toward Sunday (10,664 against 11,709 actual) and puts the peak on Wednesday.\n",
    "* **Categories (689):** each day gets its own level, and the weekend drop is right where it belongs.\n",
    "\n",
    "A circle says \"neighbors on the cycle behave alike\". That's true for hours of the day and days of the year; for births, it isn't true of Sunday and Monday. Ask before you use it. (For a forest, plain numbers are fine: a tree can split off the weekend with one question, \"day of week ≥ 5?\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "p10-077",
   "metadata": {},
   "source": [
    "---\n",
    "### Testing in Time Order\n",
    "\n",
    "To choose features and knobs we need cross-validation on 2000–2009, and it must not touch 2010–2014. `KFold(shuffle=True)` deals the days into five folds at random. `TimeSeriesSplit` **replays the past** instead: learn from everything before a date, check the stretch right after it, move the date forward.\n",
    "\n",
    "Here is a forest that knows only the **date**: day of week, day of year, month and **year**.\n",
    "\n",
    "> 🎯 **Predict First:** Which cross-validation will promise the smaller error: shuffled or in time order?"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "p10-079",
   "metadata": {
    "deletable": false,
    "editable": false
   },
   "source": [
    "### Task 12B.3 — Shuffled Folds or Rolling Folds? *(2 pts)*\n",
    "\n",
    "`X_dev` and `y_dev` (given) are the training days, 2000–2009.\n",
    "\n",
    "1. Store the five fold MAEs of `RandomForestRegressor(random_state=1)` on `X_dev[date_only]` with **shuffled** folds in `shuffled_mae`: `-cross_val_score(..., cv=KFold(n_splits=5, shuffle=True, random_state=1), scoring=\"neg_mean_absolute_error\")`. (scikit-learn maximizes scores, so it reports the MAE as a negative number; the minus sign turns it back.)\n",
    "2. Do the same with `cv=TimeSeriesSplit(n_splits=5)`, and store the result in `rolling_mae`.\n",
    "\n",
    "The fold dates, the printout and the real test are given."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "p10-081",
   "metadata": {
    "tags": [
     "otter_answer_cell"
    ]
   },
   "outputs": [],
   "source": [
    "X_dev, y_dev = births.loc[learn], y[learn]\n",
    "date_only = [\"day_of_week\", \"day_of_year\", \"month\", \"year\"]\n",
    "for fold, (learn_rows, check_rows) in enumerate(TimeSeriesSplit(n_splits=5).split(X_dev)):\n",
    "    print(f\"rolling fold {fold + 1}: learn {X_dev['date'].iloc[learn_rows[0]]:%b %Y} to {X_dev['date'].iloc[learn_rows[-1]]:%b %Y}\"\n",
    "          f\" | check {X_dev['date'].iloc[check_rows[0]]:%b %Y} to {X_dev['date'].iloc[check_rows[-1]]:%b %Y}\")\n",
    "\n",
    "shuffled_mae = ...\n",
    "rolling_mae = ...\n",
    "\n",
    "print(\"\\nshuffled folds:\", shuffled_mae.round(), f\"| mean {shuffled_mae.mean():.0f}\")\n",
    "print(\"rolling folds: \", rolling_mae.round(), f\"| mean {rolling_mae.mean():.0f}\")\n",
    "date_forest = RandomForestRegressor(random_state=1).fit(X_dev[date_only], y_dev)\n",
    "print(f\"the real test, 2010-2014: {mean_absolute_error(y[test], date_forest.predict(births.loc[test, date_only])):.0f}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bcb5a41d",
   "metadata": {
    "deletable": false,
    "editable": false
   },
   "outputs": [],
   "source": [
    "grader.check(\"12B.3\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "p10-088",
   "metadata": {},
   "source": [
    "* **Shuffled folds: 277**, steady in every fold (238 to 323). That would make the date forest better than the forest with lags (299)! It isn't. With shuffled folds, every checked day has its neighbors among the days the forest learned from: the day before and after, the same weekday a week earlier and later, all in the same year. With `year` and `day_of_year`, the forest finds them and copies their births. It isn't forecasting; it's **peeking**, like scoring a model on rows it learned from (Week 6).\n",
    "* **Rolling folds: 410**, from 306 to 586. Each checked stretch comes after everything the forest learned from, as in real use. Fold 5 checked July 2008 to 2009, the start of the decline, and missed by **586**.\n",
    "* **The real test: 595.** The future did what fold 5 warned about. The year column didn't help: a tree can't forecast a year it has never seen, so it treats 2010–2014 like 2009.\n",
    "\n",
    "For a time series, use `TimeSeriesSplit` in `cross_val_score` and in `GridSearchCV`, and report the folds' **range**, not one number. For the forest with lags (given):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "p10-089",
   "metadata": {},
   "outputs": [],
   "source": [
    "features = calendar + lags\n",
    "rolling = -cross_val_score(RandomForestRegressor(random_state=1), X_dev[features], y_dev, cv=TimeSeriesSplit(n_splits=5), scoring=\"neg_mean_absolute_error\")\n",
    "print(\"forest with lags, rolling folds:\", rolling.round(), f\"| range {rolling.min():.0f} to {rolling.max():.0f} | real test: {mae_lags:.0f}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "p10-090",
   "metadata": {},
   "source": [
    "Rolling folds: **280 to 386**. The real test, 299, landed inside that range: an honest promise.\n",
    "\n",
    "### The Days the Lags Get Wrong (given)\n",
    "\n",
    "Where does the lag forest miss most?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "p10-091",
   "metadata": {},
   "outputs": [],
   "source": [
    "misses = births.loc[test, [\"date\", \"births\"]].assign(forecast=lags_pred.round(), miss=(lags_pred - y[test]).abs().round())\n",
    "misses[\"day\"] = misses[\"date\"].dt.strftime(\"%a %b %d, %Y\")\n",
    "misses.nlargest(10, \"miss\")[[\"day\", \"births\", \"forecast\", \"miss\"]]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "p10-092",
   "metadata": {},
   "source": [
    "Nine of the ten are **holidays**: Memorial Day, Christmas, Thanksgiving, the Fourth of July (and July 5, 2010, when it was observed). Scheduled births move away from them. The tenth is **Monday, July 2, 2012**: the forecast was about 2,700 too low, because \"the same weekday a year before\", 364 days earlier, was Monday, July 4, 2011, a holiday. Holidays move around the calendar, so a 364-day lag carries last year's holiday onto an ordinary day. A `holiday` column would teach the forest what the calendar alone can't.\n",
    "\n",
    "Those dips are people's choices, not biology: births are scheduled around weekends, holidays and even Friday the 13th. Like Stone's Fitbit wearers, the parents and doctors behind these numbers are people who think and plan, and the time series records their calendars as much as nature's."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "p10-093",
   "metadata": {},
   "source": [
    "---\n",
    "## Submission\n",
    "\n",
    "Save your notebook, then upload the **`.ipynb` file** directly to our Moodle assignment page. Don't export, zip, or submit anything else — just the notebook."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  },
  "otter": {
   "OK_FORMAT": true,
   "assignment_name": "practice10",
   "tests": {
    "12A.1": {
     "name": "12A.1",
     "points": 2,
     "suites": [
      {
       "cases": [
        {
         "code": ">>> assert hasattr(model, 'steps') and isinstance(model[0], StandardScaler) and isinstance(model[-1], LogisticRegression), 'make_pipeline(StandardScaler(), LogisticRegression())'\n>>> assert len(y_pred) == len(y_test), 'predict on X_test'\n>>> assert 0.9 < acc < 1 and 0 < rec < 1 and (0 < prec < 1), 'use accuracy_score, recall_score and precision_score with (y_test, y_pred)'\n",
         "hidden": false,
         "locked": false
        }
       ],
       "scored": true,
       "setup": "",
       "teardown": "",
       "type": "doctest"
      }
     ]
    },
    "12A.2": {
     "name": "12A.2",
     "points": 2,
     "suites": [
      {
       "cases": [
        {
         "code": ">>> assert len(p_train) == len(y_train) and 0 <= p_train.min() and (p_train.max() <= 1), \"cross_val_predict(..., method='predict_proba')[:, 1] on X_train, y_train\"\n>>> assert len(called) == len(y_test), 'called should have one True/False per test Pokémon'\n>>> assert 0 < rec_02 <= 1 and 0 < prec_02 <= 1, 'recall_score and precision_score with (y_test, called)'\n",
         "hidden": false,
         "locked": false
        }
       ],
       "scored": true,
       "setup": "",
       "teardown": "",
       "type": "doctest"
      }
     ]
    },
    "12A.3": {
     "name": "12A.3",
     "points": 2,
     "suites": [
      {
       "cases": [
        {
         "code": ">>> assert any((isinstance(step, SMOTE) for step in knn_smote.named_steps.values())), 'the pipeline needs a SMOTE(random_state=1) step'\n>>> assert isinstance(knn_smote[-1], KNeighborsClassifier), \"the pipeline's last step should be KNeighborsClassifier()\"\n>>> assert 'test_recall' in knn_smote_scores and len(knn_smote_scores['test_recall']) == 5, \"cross_validate with cv=5 and scoring=['recall', 'precision']\"\n",
         "hidden": false,
         "locked": false
        }
       ],
       "scored": true,
       "setup": "",
       "teardown": "",
       "type": "doctest"
      }
     ]
    },
    "12B.1": {
     "name": "12B.1",
     "points": 2,
     "suites": [
      {
       "cases": [
        {
         "code": ">>> assert {'births_1d_ago', 'births_7d_ago', 'births_364d_ago', 'mean_last_7'} <= set(births.columns), 'add the four lag columns'\n>>> assert (births['births_7d_ago'].iloc[7:].to_numpy() == births['births'].shift(7).iloc[7:].to_numpy()).all(), \"births_7d_ago should be births['births'].shift(7): a past value, so a positive shift\"\n>>> assert len(births) == 5115 and learn.sum() == 3289, 'add the columns before the given dropna'\n>>> assert 300 < naive_mae < 600, \"mean_absolute_error(y[test], births.loc[test, 'births_7d_ago'])\"\n",
         "hidden": false,
         "locked": false
        }
       ],
       "scored": true,
       "setup": "",
       "teardown": "",
       "type": "doctest"
      }
     ]
    },
    "12B.2": {
     "name": "12B.2",
     "points": 2,
     "suites": [
      {
       "cases": [
        {
         "code": ">>> assert 300 < mae_calendar < 900 and 150 < mae_lags < 500, 'fit on births.loc[learn, ...] and y[learn]; score on births.loc[test, ...] and y[test]'\n>>> assert mae_lags < mae_calendar, 'the second forest should use calendar + lags'\n",
         "hidden": false,
         "locked": false
        }
       ],
       "scored": true,
       "setup": "",
       "teardown": "",
       "type": "doctest"
      }
     ]
    },
    "12B.3": {
     "name": "12B.3",
     "points": 2,
     "suites": [
      {
       "cases": [
        {
         "code": ">>> assert len(shuffled_mae) == 5 and len(rolling_mae) == 5, 'cross_val_score with 5 folds, twice'\n>>> assert (shuffled_mae > 0).all() and (rolling_mae > 0).all(), \"put a minus sign in front of cross_val_score(..., scoring='neg_mean_absolute_error')\"\n>>> assert rolling_mae.mean() > shuffled_mae.mean(), 'shuffled_mae uses KFold(n_splits=5, shuffle=True, random_state=1); rolling_mae uses TimeSeriesSplit(n_splits=5)'\n",
         "hidden": false,
         "locked": false
        }
       ],
       "scored": true,
       "setup": "",
       "teardown": "",
       "type": "doctest"
      }
     ]
    }
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
