{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "intro",
   "metadata": {},
   "source": [
    "# Lab 1: Is the new model really better?\n",
    "\n",
    "**A practical lab from [math4ml.co](https://math4ml.co/evals-lab-1).** Keep the lab page open next to this notebook. You do the work here and type each answer there. The page checks it and explains it.\n",
    "\n",
    "**The situation.** Your customer runs a help desk. An AI assistant (the old model) answers customer questions. Your team wants to replace it with a new model that costs more. The customer wrote 200 test questions with known right answers and ran both models on all of them. The old model got 75% right. The new one got 81%.\n",
    "\n",
    "The head of support asks you: *\"Six points better. Is that real, or did the new model just get lucky? Should we pay for it?\"*\n",
    "\n",
    "**The data are made up for this lab.** Nothing here comes from a real company.\n",
    "\n",
    "**How to use this notebook.** Run the two cells below first (press the play button on each). Then work through the six steps. Each step has an empty cell for your code. If you get stuck, open \"Stuck? Show one way to do it\" under the step. Nothing needs to be installed and no key is needed."
   ]
  },
  {
   "cell_type": "code",
   "id": "write-data",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "# Run this cell first. It writes the customer's test results to a file.\n",
    "# Made-up data for this lab: 200 help desk questions, 1 = right answer, 0 = wrong answer.\n",
    "OLD = (\"0000110110110111111111110011101110111111111111111100110100111101011111111111111111111111000111111101\"\n",
    "       \"1101111111111101011101111110100011101011111000011111101101011110100010111111111110110111110110010111\")\n",
    "NEW = (\"1101110111110111111111011011101110111111111111111101110110111101011111111111110111111111000111111101\"\n",
    "       \"1101111111111111011101111110100011101111110000111111101111010111110110111111111111110111110111011110\")\n",
    "with open(\"eval_results.csv\", \"w\") as f:\n",
    "    f.write(\"question,old_model,new_model\\n\")\n",
    "    for i, (o, w) in enumerate(zip(OLD, NEW), start=1):\n",
    "        f.write(f\"{i},{o},{w}\\n\")\n",
    "print(\"Wrote eval_results.csv with\", len(OLD), \"questions\")"
   ]
  },
  {
   "cell_type": "code",
   "id": "load-data",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "# Run this cell second. It reads the file into a list of pairs: (old model, new model).\n",
    "import csv\n",
    "with open(\"eval_results.csv\") as f:\n",
    "    rows = [(int(r[\"old_model\"]), int(r[\"new_model\"])) for r in csv.DictReader(f)]\n",
    "print(len(rows), \"questions loaded. The first five:\", rows[:5])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "step1",
   "metadata": {},
   "source": [
    "## Step 1: Score both models\n",
    "\n",
    "`rows` is a list of 200 pairs. The first number of a pair is the old model's result on a question, the second is the new model's (1 = right, 0 = wrong).\n",
    "\n",
    "Count how many questions each model got right and turn the counts into percentages.\n",
    "\n",
    "**Type on the lab page:** the new model's score, in percent.\n",
    "\n",
    "<details>\n",
    "<summary>Stuck? Show one way to do it</summary>\n",
    "\n",
    "```python\n",
    "n = len(rows)\n",
    "old_right = sum(o for o, w in rows)\n",
    "new_right = sum(w for o, w in rows)\n",
    "old_score = 100 * old_right / n\n",
    "new_score = 100 * new_right / n\n",
    "print(\"old:\", old_right, \"of\", n, \"=\", old_score, \"%\")\n",
    "print(\"new:\", new_right, \"of\", n, \"=\", new_score, \"%\")\n",
    "```\n",
    "\n",
    "</details>"
   ]
  },
  {
   "cell_type": "code",
   "id": "step1-code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "# Step 1: your code here\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "step2",
   "metadata": {},
   "source": [
    "## Step 2: How sure is each score?\n",
    "\n",
    "A score from 200 questions is an estimate. With 200 different questions it would have come out a little different. The **Wilson range** says where the true score probably lies (95 times in 100). It stays honest for small tests, where the textbook shortcut does not.\n",
    "\n",
    "For a model with `k` right answers out of `n`, and `z = 1.96`:\n",
    "\n",
    "```\n",
    "centre = (k + z*z/2) / (n + z*z)\n",
    "half   = z / (n + z*z) * sqrt( k*(n-k)/n + z*z/4 )\n",
    "range  = centre - half   to   centre + half\n",
    "```\n",
    "\n",
    "Write a function `wilson(k, n)` and print the range of both models, in percent.\n",
    "\n",
    "**Type on the lab page:** where the new model's range starts (its low end), in percent, with one decimal.\n",
    "\n",
    "<details>\n",
    "<summary>Stuck? Show one way to do it</summary>\n",
    "\n",
    "```python\n",
    "import math\n",
    "\n",
    "def wilson(k, n, z=1.96):\n",
    "    centre = (k + z * z / 2) / (n + z * z)\n",
    "    half = z / (n + z * z) * math.sqrt(k * (n - k) / n + z * z / 4)\n",
    "    return 100 * (centre - half), 100 * (centre + half)\n",
    "\n",
    "old_low, old_high = wilson(old_right, n)\n",
    "new_low, new_high = wilson(new_right, n)\n",
    "print(\"old model: %.1f%% to %.1f%%\" % (old_low, old_high))\n",
    "print(\"new model: %.1f%% to %.1f%%\" % (new_low, new_high))\n",
    "```\n",
    "\n",
    "</details>"
   ]
  },
  {
   "cell_type": "code",
   "id": "step2-code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "# Step 2: your code here\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "step3",
   "metadata": {},
   "source": [
    "## Step 3: Line the two models up, question by question\n",
    "\n",
    "The two ranges overlap, so they cannot settle it. But they ignore something you know: **both models answered the same 200 questions.** That lets you compare them one question at a time.\n",
    "\n",
    "Sort the questions into four groups:\n",
    "\n",
    "- both right\n",
    "- the new model **fixed** it (old wrong, new right)\n",
    "- the new model **broke** it (old right, new wrong)\n",
    "- both wrong\n",
    "\n",
    "**Type on the lab page:** how many questions the new model fixed.\n",
    "\n",
    "<details>\n",
    "<summary>Stuck? Show one way to do it</summary>\n",
    "\n",
    "```python\n",
    "both_right = sum(1 for o, w in rows if o == 1 and w == 1)\n",
    "fixed = sum(1 for o, w in rows if o == 0 and w == 1)\n",
    "broke = sum(1 for o, w in rows if o == 1 and w == 0)\n",
    "both_wrong = sum(1 for o, w in rows if o == 0 and w == 0)\n",
    "print(\"both right:\", both_right)\n",
    "print(\"fixed by the new model:\", fixed)\n",
    "print(\"broken by the new model:\", broke)\n",
    "print(\"both wrong:\", both_wrong)\n",
    "```\n",
    "\n",
    "</details>"
   ]
  },
  {
   "cell_type": "code",
   "id": "step3-code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "# Step 3: your code here\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "step4",
   "metadata": {},
   "source": [
    "## Step 4: Could that split be luck?\n",
    "\n",
    "Only the questions where the models disagree can tell them apart. Suppose the two models were really equally good. Then each disagreement would be a coin flip: the new model wins it or the old model wins it, with the same chance.\n",
    "\n",
    "So ask: with a fair coin and that many flips, how often is the split **at least this lopsided**? Count both directions, because the old model could have been the lucky one too.\n",
    "\n",
    "The chance of exactly `i` heads in `d` fair flips is `math.comb(d, i) / 2**d`.\n",
    "\n",
    "**Type on the lab page:** that probability, as a decimal (like 0.25), with four decimals.\n",
    "\n",
    "<details>\n",
    "<summary>Stuck? Show one way to do it</summary>\n",
    "\n",
    "```python\n",
    "import math\n",
    "\n",
    "d = fixed + broke\n",
    "small = min(fixed, broke)\n",
    "one_side = sum(math.comb(d, i) for i in range(small + 1)) / 2 ** d\n",
    "p_value = min(1.0, 2 * one_side)\n",
    "print(\"disagreements:\", d)\n",
    "print(\"chance of a split at least this lopsided:\", round(p_value, 4))\n",
    "```\n",
    "\n",
    "</details>"
   ]
  },
  {
   "cell_type": "code",
   "id": "step4-code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "# Step 4: your code here\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "step5",
   "metadata": {},
   "source": [
    "## Step 5: How big is the lead, realistically?\n",
    "\n",
    "\"Probably not luck\" does not say how much better the new model is. For that, replay the test many times: draw 200 questions **from your own 200, with repeats allowed**, and measure the new model's lead on each draw. Keep each question's two results together when you draw it. Do this 10,000 times. The middle 95% of the leads is a realistic range.\n",
    "\n",
    "Use `rng = random.Random(7)` so that your numbers can be checked.\n",
    "\n",
    "**Type on the lab page:** the low end of that range, in points (percentage points).\n",
    "\n",
    "<details>\n",
    "<summary>Stuck? Show one way to do it</summary>\n",
    "\n",
    "```python\n",
    "import random\n",
    "\n",
    "rng = random.Random(7)\n",
    "leads = []\n",
    "for _ in range(10000):\n",
    "    total = 0\n",
    "    for _ in range(n):\n",
    "        o, w = rows[rng.randrange(n)]\n",
    "        total += w - o\n",
    "    leads.append(100 * total / n)\n",
    "leads.sort()\n",
    "lead_low = leads[250]\n",
    "lead_high = leads[9749]\n",
    "print(\"the lead is probably between\", lead_low, \"and\", lead_high, \"points\")\n",
    "```\n",
    "\n",
    "</details>"
   ]
  },
  {
   "cell_type": "code",
   "id": "step5-code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "# Step 5: your code here\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "step6",
   "metadata": {},
   "source": [
    "## Step 6: Does the switch pay?\n",
    "\n",
    "The customer's numbers (made up for the lab):\n",
    "\n",
    "- the help desk gets **4,000 questions a week**\n",
    "- every wrong answer costs **$3** of staff time, because a person has to step in\n",
    "- the new model costs **$360 a week more** than the old one\n",
    "\n",
    "Each point of lead means 40 fewer wrong answers a week. Work out the lead at which the saving equals the extra cost. Then look at what the low end and the high end of your range from Step 5 would mean in dollars a week.\n",
    "\n",
    "**Type on the lab page:** the lead, in points, at which the new model pays for itself.\n",
    "\n",
    "<details>\n",
    "<summary>Stuck? Show one way to do it</summary>\n",
    "\n",
    "```python\n",
    "weekly_questions = 4000\n",
    "cost_per_wrong = 3\n",
    "extra_cost = 360\n",
    "\n",
    "break_even = 100 * extra_cost / (weekly_questions * cost_per_wrong)\n",
    "print(\"the new model pays for itself above\", break_even, \"points\")\n",
    "for name, lead in ((\"low end\", lead_low), (\"measured\", new_score - old_score), (\"high end\", lead_high)):\n",
    "    gain = weekly_questions * lead / 100 * cost_per_wrong - extra_cost\n",
    "    print(\"%s: a lead of %.1f points is worth %+.0f dollars a week\" % (name, lead, gain))\n",
    "```\n",
    "\n",
    "</details>"
   ]
  },
  {
   "cell_type": "code",
   "id": "step6-code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "# Step 6: your code here\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "report",
   "metadata": {},
   "source": [
    "## Your report\n",
    "\n",
    "Go back to the lab page. It has a short report for the customer, filled in with your numbers. Add your recommendation and keep a copy.\n",
    "\n",
    "**What you just did**, in the words you can use with a customer: you scored both models, showed how uncertain each score is, compared the models on the same questions, checked whether the lead could be luck, put a realistic range on the lead, and turned that range into money.\n",
    "\n",
    "Next labs on [math4ml.co](https://math4ml.co/evals): how many test questions you need, where to set a threshold when the two kinds of mistake cost different amounts, and whether a model that grades another model can be trusted."
   ]
  }
 ],
 "metadata": {
  "colab": {
   "name": "is-the-new-model-better.ipynb",
   "provenance": []
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
