{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e2d8f433",
   "metadata": {
    "deletable": false,
    "editable": false
   },
   "outputs": [],
   "source": [
    "# Initialize Otter\n",
    "import otter\n",
    "grader = otter.Notebook(\"practice11.ipynb\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "p11-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": "p11-002",
   "metadata": {},
   "source": [
    "# Practice 11 — Black Cats at the Shelter: Fairness and Interpretability\n",
    "\n",
    "Every cat that arrived at the Austin Animal Center, the city shelter of Austin, Texas, from 2021 to 2024, and left by adoption, transfer, euthanasia or death: **20,582 cats**. The same source as Reading 11's dogs, with the same question: **was the cat adopted within 30 days of arriving?**\n",
    "\n",
    "* **Part 1:** black cats have a reputation for bad luck. Are they adopted more slowly, and does a model treat them differently?\n",
    "* **Part 2:** a random forest predicts quick adoptions. Which columns does it rely on, and why does it give one black cat, Lola, a low chance?\n",
    "\n",
    "Four short tasks, 2 points each.\n",
    "\n",
    "| SLO | Description |\n",
    "|-----|-------------|\n",
    "| **14A** | Apply fairness metrics to compare model performance across demographic subgroups and articulate trade-offs between competing fairness criteria |\n",
    "| **14B** | Use interpretability techniques — feature importance, partial dependence plots, and LIME — to explain model predictions |"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "p11-003",
   "metadata": {},
   "source": [
    "### Setup (given — just run it)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "p11-004",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "from sklearn.model_selection import train_test_split\n",
    "from sklearn.pipeline import make_pipeline\n",
    "from sklearn.compose import make_column_transformer\n",
    "from sklearn.preprocessing import StandardScaler, OneHotEncoder\n",
    "from sklearn.linear_model import LogisticRegression\n",
    "from sklearn.ensemble import RandomForestClassifier\n",
    "from sklearn.inspection import permutation_importance"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "p11-005",
   "metadata": {},
   "source": [
    "---\n",
    "## Part 1 — Is There a Black-Cat Bias? (SLO 14A)\n",
    "\n",
    "| Column | What it holds |\n",
    "|---|---|\n",
    "| `name` | the cat's name (blank if none) |\n",
    "| `intake_date`, `days`, `outcome` | the day it arrived, days until it left, and how: adoption, transfer, euthanasia, died |\n",
    "| `intake_type`, `intake_condition` | stray, owner surrender…; normal, injured, sick, neonatal (newborn), nursing… |\n",
    "| `sex`, `fixed`, `age_years` | female or male; spayed/neutered on arrival; age on arrival, in years |\n",
    "| `coat` | the first color on its record: `Black` for \"Black\" or \"Black/White\", `Brown Tabby`… |\n",
    "\n",
    "The label is `quick`: adopted within 30 days. The sensitive attribute is `black`: the cat's first color is black."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "p11-006",
   "metadata": {},
   "outputs": [],
   "source": [
    "cats = pd.read_csv(\"https://cs.calvin.edu/courses/data/202/26fa/datasets/cats.csv\")\n",
    "cats[\"quick\"] = (cats[\"outcome\"] == \"adoption\") & (cats[\"days\"] <= 30)      # adopted within 30 days\n",
    "cats[\"black\"] = cats[\"coat\"] == \"Black\"                                    # mostly black\n",
    "cats[\"month\"] = pd.to_datetime(cats[\"intake_date\"]).dt.month               # for Part 2\n",
    "print(f\"{len(cats)} cats | adopted within 30 days: {cats['quick'].mean():.1%} | black: {cats['black'].mean():.1%}\")\n",
    "cats.groupby(\"black\")[\"quick\"].mean()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "p11-007",
   "metadata": {},
   "source": [
    "Black cats were adopted within 30 days **35.9%** of the time, other cats **38.1%**: a gap of 2 points. Small, but real data is noisy; does a model make it bigger?\n",
    "\n",
    "As in Reading 11, imagine the shelter has room on its adoption floor for about half of its cats, and gives the spots to the cats a model rates most likely to be adopted soon. The model (given) never sees the coat. A chance of **0.4** or more earns a spot:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "p11-008",
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = [\"age_years\"]\n",
    "words = [\"sex\", \"fixed\", \"intake_type\", \"intake_condition\"]          # no coat\n",
    "train, test = train_test_split(cats, test_size=0.25, random_state=1, stratify=cats[\"quick\"])\n",
    "\n",
    "blind = make_pipeline(make_column_transformer((StandardScaler(), numbers), (OneHotEncoder(handle_unknown=\"ignore\"), words)),\n",
    "                      LogisticRegression(max_iter=5000))\n",
    "blind.fit(train[numbers + words], train[\"quick\"])\n",
    "test = test.copy()\n",
    "test[\"pick\"] = blind.predict_proba(test[numbers + words])[:, 1] >= 0.4       # a spot on the adoption floor\n",
    "print(f\"{len(test)} test cats, {test['black'].sum()} black | share picked: {test['pick'].mean():.3f}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "p11-010",
   "metadata": {
    "deletable": false,
    "editable": false
   },
   "source": [
    "### Task 14A.1 — Audit by Group *(2 pts)*\n",
    "\n",
    "Compute two measures **for each group** of test cats (`black` False and True):\n",
    "\n",
    "1. `picked`: the share of each group given a spot. *Hint:* `test.groupby(\"black\")[\"pick\"].mean()`.\n",
    "2. `passed_over`: among the cats that **were** adopted within 30 days (`test[test[\"quick\"]]`), the share of each group **not** given a spot. *Hint:* one minus the share picked, in that subset.\n",
    "\n",
    "The printout is given."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "p11-012",
   "metadata": {
    "tags": [
     "otter_answer_cell"
    ]
   },
   "outputs": [],
   "source": [
    "picked = ...\n",
    "passed_over = ...\n",
    "\n",
    "pd.DataFrame({\"share picked\": picked, \"passed over\": passed_over}).round(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0f91a32d",
   "metadata": {
    "deletable": false,
    "editable": false
   },
   "outputs": [],
   "source": [
    "grader.check(\"14A.1\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "p11-019",
   "metadata": {},
   "source": [
    "The blind model gives a spot to **45.5%** of the other cats and **46.0%** of the black cats, and passes over 37.5% and 36.1% of the cats that were adopted quickly. On every measure the two groups are within 1.5 points, black cats slightly *ahead*. Unlike Reading 11's pit-labeled dogs, black cats have no coat-colored proxy pulling them down here: the model's columns (age, sex, condition…) don't differ much by coat."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "p11-020",
   "metadata": {},
   "source": [
    "---\n",
    "### A Model That Sees the Coat\n",
    "\n",
    "What if the shelter gave the model the `black` column (strategy 1, \"use it\")? Given:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "p11-021",
   "metadata": {},
   "outputs": [],
   "source": [
    "aware = make_pipeline(make_column_transformer((StandardScaler(), numbers), (OneHotEncoder(handle_unknown=\"ignore\"), words + [\"black\"])),\n",
    "                      LogisticRegression(max_iter=5000))\n",
    "aware.fit(train[numbers + words + [\"black\"]], train[\"quick\"])\n",
    "black_test = test[test[\"black\"]]                                       # the black test cats"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "p11-023",
   "metadata": {
    "deletable": false,
    "editable": false
   },
   "source": [
    "### Task 14A.2 — Flip the Coat *(2 pts)*\n",
    "\n",
    "1. `as_is`: the share of the black test cats (`black_test`) that the aware model picks, with a chance of 0.4 or more. *Hint:* `(aware.predict_proba(black_test[numbers + words + [\"black\"]])[:, 1] >= 0.4).mean()`.\n",
    "2. `flipped`: the same, for the same cats with `black` set to `False`, everything else kept: `.assign(black=False)` before `predict_proba`.\n",
    "\n",
    "The printout is given."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "p11-025",
   "metadata": {
    "tags": [
     "otter_answer_cell"
    ]
   },
   "outputs": [],
   "source": [
    "as_is = ...\n",
    "flipped = ...\n",
    "\n",
    "others = (aware.predict_proba(test.loc[~test[\"black\"], numbers + words + [\"black\"]])[:, 1] >= 0.4).mean()\n",
    "print(f\"black cats picked: {as_is:.3f} | the same cats, not black: {flipped:.3f} | other cats: {others:.3f}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d6c629d3",
   "metadata": {
    "deletable": false,
    "editable": false
   },
   "outputs": [],
   "source": [
    "grader.check(\"14A.2\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "p11-032",
   "metadata": {},
   "source": [
    "Told the coat, the model picks **43.8%** of the black cats; told the same cats aren't black, **46.0%**. The model learned a small penalty for black coats (odds × 0.92), copying the 2-point gap in the past adoptions. For Reading 11's dogs, the same flip moved pit-labeled dogs from 3.6% to 58%.\n",
    "\n",
    "So: a small difference in the data, and no difference at all from the blind model. Auditing is how you find out which situation you're in, before you choose a fix. And even 2 points is a choice: the narrow view would leave the coat out (the blind model, nearly equal here); the middle view might add a small correction; the broad view would work on what adopters see, like better photos of black cats, which are hard to photograph well."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "p11-033",
   "metadata": {},
   "source": [
    "---\n",
    "## Part 2 — Explaining a Forest (SLO 14B)\n",
    "\n",
    "A random forest, with the coat and the month the cat arrived (given). Its built-in importances come with it:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "p11-034",
   "metadata": {},
   "outputs": [],
   "source": [
    "features = [\"age_years\", \"month\", \"sex\", \"fixed\", \"intake_type\", \"intake_condition\", \"coat\"]\n",
    "forest = make_pipeline(make_column_transformer((OneHotEncoder(handle_unknown=\"ignore\"), [\"sex\", \"fixed\", \"intake_type\", \"intake_condition\", \"coat\"]),\n",
    "                                               remainder=\"passthrough\"),\n",
    "                       RandomForestClassifier(min_samples_leaf=10, random_state=1, n_jobs=-1))\n",
    "forest.fit(train[features], train[\"quick\"])\n",
    "print(f\"forest: test {forest.score(test[features], test['quick']):.3f} | training {forest.score(train[features], train['quick']):.3f}\")\n",
    "\n",
    "names = forest[0].get_feature_names_out()                                   # e.g. \"onehotencoder__coat_Black\"\n",
    "built_in = pd.Series(forest[-1].feature_importances_, index=[n.split(\"__\")[1] for n in names])\n",
    "built_in = pd.Series({f: built_in[[i == f or i.startswith(f + \"_\") for i in built_in.index]].sum() for f in features})\n",
    "built_in.round(3)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "p11-036",
   "metadata": {
    "deletable": false,
    "editable": false
   },
   "source": [
    "### Task 14B.1 — Which Columns, and How? *(2 pts)*\n",
    "\n",
    "1. `perm`: the forest's **permutation importance on the test set**, as a Series with one value per feature: `pd.Series(permutation_importance(forest, test[features], test[\"quick\"], n_repeats=5, random_state=1).importances_mean, index=features)`.\n",
    "2. Two points of the **partial dependence** of age, by hand: `kitten`, the forest's average chance with **every** test cat's `age_years` set to 0.25 (3 months); `adult`, the same with 3 years. *Hint:* `forest.predict_proba(test[features].assign(age_years=0.25))[:, 1].mean()`.\n",
    "\n",
    "The printout is given."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "p11-038",
   "metadata": {
    "tags": [
     "otter_answer_cell"
    ]
   },
   "outputs": [],
   "source": [
    "perm = ...\n",
    "kitten = ...\n",
    "adult = ...\n",
    "\n",
    "print(f\"average chance: as 3-month-old kittens {kitten:.3f} | as 3-year-olds {adult:.3f}\")\n",
    "pd.DataFrame({\"built-in (training)\": built_in, \"permutation (test)\": perm}).round(4).sort_values(\"permutation (test)\", ascending=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "08251237",
   "metadata": {
    "deletable": false,
    "editable": false
   },
   "outputs": [],
   "source": [
    "grader.check(\"14B.1\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "p11-045",
   "metadata": {},
   "source": [
    "* **Age** comes first by both measures: shuffling it costs 0.135 of accuracy. As the partial dependence shows, the forest gives a 3-month-old kitten an average chance of **0.59**, a 3-year-old **0.40**.\n",
    "* **The coat comes last**, with 0.001: shuffling the coat on new cats barely hurts. The forest has the coat and hardly uses it, as Part 1 suggested.\n",
    "* **The month** looks bigger in built-in importance (0.070, fourth) than on new cats (0.011): built-in importance is measured on the training data, where the forest's month splits fit noise. The forest scores 79.2% on its training cats and 77.7% on new ones."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "p11-046",
   "metadata": {},
   "source": [
    "---\n",
    "### Lola\n",
    "\n",
    "Lola (animal A878407) arrived as a stray in April 2023: a 2-year-old female, not yet spayed, black. She was adopted after **76 days**."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "p11-047",
   "metadata": {},
   "outputs": [],
   "source": [
    "lola = cats[cats[\"animal_id\"] == \"A878407\"]\n",
    "lola[[\"name\", \"intake_date\", \"days\", \"outcome\", \"intake_type\", \"sex\", \"fixed\", \"age_years\", \"color\", \"coat\"]]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "p11-049",
   "metadata": {
    "deletable": false,
    "editable": false
   },
   "source": [
    "### Task 14B.2 — Why Was Lola Waiting? *(2 pts)*\n",
    "\n",
    "A **counterfactual** changes one thing about Lola and asks the forest again.\n",
    "\n",
    "1. `chance`: the forest's chance that Lola is adopted within 30 days: `forest.predict_proba(lola[features])[:, 1][0]`.\n",
    "2. `as_kitten`: the same, with her `age_years` set to 0.25.\n",
    "3. `other_coat`: the same, with her `coat` set to `\"Brown Tabby\"`.\n",
    "\n",
    "The printout (with one more counterfactual) is given."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "p11-051",
   "metadata": {
    "tags": [
     "otter_answer_cell"
    ]
   },
   "outputs": [],
   "source": [
    "chance = ...\n",
    "as_kitten = ...\n",
    "other_coat = ...\n",
    "\n",
    "spayed = forest.predict_proba(lola[features].assign(fixed=\"yes\"))[:, 1][0]\n",
    "print(f\"Lola: {chance:.2f} | as a 3-month-old kitten: {as_kitten:.2f} | as a brown tabby: {other_coat:.2f} | arrived spayed: {spayed:.2f}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4de5bce0",
   "metadata": {
    "deletable": false,
    "editable": false
   },
   "outputs": [],
   "source": [
    "grader.check(\"14B.2\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "p11-058",
   "metadata": {},
   "source": [
    "Lola's chance is **0.31**. As a kitten: **0.65**, over the line; as a brown tabby: **0.31**, the same; had she arrived spayed: 0.49, almost.\n",
    "\n",
    "So the forest's \"why\" for Lola is her **age**, not her color. That counterfactual is true and useless: nobody can make Lola younger. The one change in reach, spaying, almost flips her, and shelters usually spay cats before adoption anyway. A good explanation for Lola's adopters wouldn't be a number at all: it would be a photo that shows her well, and a few words about who she is."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "p11-059",
   "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": "practice11",
   "tests": {
    "14A.1": {
     "name": "14A.1",
     "points": 2,
     "suites": [
      {
       "cases": [
        {
         "code": ">>> assert list(picked.index) == [False, True], 'group test by the black column'\n>>> assert list(passed_over.index) == [False, True], 'group the quick cats by the black column'\n>>> assert all(0 < picked) and all(picked < 1) and all(0 < passed_over) and all(passed_over < 1), 'shares between 0 and 1'\n>>> assert passed_over[True] < 0.5, 'passed over = 1 - (share picked among the quick cats)'\n",
         "hidden": false,
         "locked": false
        }
       ],
       "scored": true,
       "setup": "",
       "teardown": "",
       "type": "doctest"
      }
     ]
    },
    "14A.2": {
     "name": "14A.2",
     "points": 2,
     "suites": [
      {
       "cases": [
        {
         "code": ">>> assert 0 < as_is < 1 and 0 < flipped < 1, 'shares of black_test picked at 0.4'\n>>> assert flipped > as_is, 'flipped: the same cats with .assign(black=False)'\n",
         "hidden": false,
         "locked": false
        }
       ],
       "scored": true,
       "setup": "",
       "teardown": "",
       "type": "doctest"
      }
     ]
    },
    "14B.1": {
     "name": "14B.1",
     "points": 2,
     "suites": [
      {
       "cases": [
        {
         "code": ">>> assert list(perm.index) == features, 'index=features'\n>>> assert perm.idxmax() == 'age_years', \"permutation_importance(forest, test[features], test['quick'], n_repeats=5, random_state=1)\"\n>>> assert 0 < adult < kitten < 1, 'set age_years for every test cat with .assign, then average predict_proba[:, 1]'\n",
         "hidden": false,
         "locked": false
        }
       ],
       "scored": true,
       "setup": "",
       "teardown": "",
       "type": "doctest"
      }
     ]
    },
    "14B.2": {
     "name": "14B.2",
     "points": 2,
     "suites": [
      {
       "cases": [
        {
         "code": ">>> assert 0 < chance < 0.5, 'forest.predict_proba(lola[features])[:, 1][0]'\n>>> assert as_kitten > 0.5, 'lola[features].assign(age_years=0.25)'\n>>> assert 0 < other_coat < 1, \"lola[features].assign(coat='Brown Tabby')\"\n",
         "hidden": false,
         "locked": false
        }
       ],
       "scored": true,
       "setup": "",
       "teardown": "",
       "type": "doctest"
      }
     ]
    }
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
