{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "5256d7ab",
   "metadata": {},
   "source": [
    "# KNN for marketing: find junk leads before sales does\n",
    "\n",
    "Companion notebook to the guide at https://martinguzman.ca/blog/knn-junk-lead-detection\n",
    "\n",
    "Put `northpine_leads.csv` in the same folder as this notebook (download it from https://martinguzman.ca/guides/ml/northpine_leads.csv). Northpine Software is a made-up company; the data is synthetic."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "da1e74a3",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:51:56.772565Z",
     "iopub.status.busy": "2026-12-05T03:51:56.772489Z",
     "iopub.status.idle": "2026-12-05T03:51:57.561056Z",
     "shell.execute_reply": "2026-12-05T03:51:57.560662Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(4000, 9)\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>lead_id</th>\n",
       "      <th>seconds_on_site</th>\n",
       "      <th>pages_viewed</th>\n",
       "      <th>form_fill_seconds</th>\n",
       "      <th>message_chars</th>\n",
       "      <th>links_in_message</th>\n",
       "      <th>free_email_domain</th>\n",
       "      <th>submissions_same_ip_24h</th>\n",
       "      <th>is_junk</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>NL-00001</td>\n",
       "      <td>86</td>\n",
       "      <td>5</td>\n",
       "      <td>24.5</td>\n",
       "      <td>178</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>NL-00002</td>\n",
       "      <td>384</td>\n",
       "      <td>8</td>\n",
       "      <td>35.7</td>\n",
       "      <td>60</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>NL-00003</td>\n",
       "      <td>124</td>\n",
       "      <td>3</td>\n",
       "      <td>4.4</td>\n",
       "      <td>101</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>NL-00004</td>\n",
       "      <td>320</td>\n",
       "      <td>4</td>\n",
       "      <td>5.8</td>\n",
       "      <td>78</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>NL-00005</td>\n",
       "      <td>97</td>\n",
       "      <td>5</td>\n",
       "      <td>64.6</td>\n",
       "      <td>123</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "    lead_id  seconds_on_site  pages_viewed  form_fill_seconds  message_chars  \\\n",
       "0  NL-00001               86             5               24.5            178   \n",
       "1  NL-00002              384             8               35.7             60   \n",
       "2  NL-00003              124             3                4.4            101   \n",
       "3  NL-00004              320             4                5.8             78   \n",
       "4  NL-00005               97             5               64.6            123   \n",
       "\n",
       "   links_in_message  free_email_domain  submissions_same_ip_24h  is_junk  \n",
       "0                 0                  0                        1        0  \n",
       "1                 0                  0                        1        0  \n",
       "2                 1                  1                        1        0  \n",
       "3                 0                  1                        1        0  \n",
       "4                 0                  0                        1        0  "
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "from sklearn.metrics import roc_auc_score\n",
    "from sklearn.neighbors import LocalOutlierFactor, NearestNeighbors\n",
    "from sklearn.preprocessing import StandardScaler\n",
    "\n",
    "leads = pd.read_csv(\"northpine_leads.csv\")\n",
    "print(leads.shape)\n",
    "leads.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "c9673537",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:51:57.562371Z",
     "iopub.status.busy": "2026-12-05T03:51:57.562290Z",
     "iopub.status.idle": "2026-12-05T03:51:57.564475Z",
     "shell.execute_reply": "2026-12-05T03:51:57.564084Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "120 junk leads out of 4,000 (3.0%)\n"
     ]
    }
   ],
   "source": [
    "answer = leads.pop(\"is_junk\")   # found on review by sales ops; the model never sees it\n",
    "print(f\"{answer.sum()} junk leads out of {len(leads):,} ({answer.mean():.1%})\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "ece52070",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:51:57.565556Z",
     "iopub.status.busy": "2026-12-05T03:51:57.565488Z",
     "iopub.status.idle": "2026-12-05T03:51:57.572432Z",
     "shell.execute_reply": "2026-12-05T03:51:57.572105Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>mean</th>\n",
       "      <th>50%</th>\n",
       "      <th>min</th>\n",
       "      <th>max</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>seconds_on_site</th>\n",
       "      <td>248.6</td>\n",
       "      <td>194.0</td>\n",
       "      <td>2.0</td>\n",
       "      <td>2216.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>pages_viewed</th>\n",
       "      <td>5.4</td>\n",
       "      <td>5.0</td>\n",
       "      <td>1.0</td>\n",
       "      <td>15.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>form_fill_seconds</th>\n",
       "      <td>37.6</td>\n",
       "      <td>35.6</td>\n",
       "      <td>1.1</td>\n",
       "      <td>182.7</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>message_chars</th>\n",
       "      <td>105.9</td>\n",
       "      <td>75.5</td>\n",
       "      <td>0.0</td>\n",
       "      <td>1729.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>links_in_message</th>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>1.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>free_email_domain</th>\n",
       "      <td>0.1</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>1.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>submissions_same_ip_24h</th>\n",
       "      <td>1.2</td>\n",
       "      <td>1.0</td>\n",
       "      <td>1.0</td>\n",
       "      <td>14.0</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                          mean    50%  min     max\n",
       "seconds_on_site          248.6  194.0  2.0  2216.0\n",
       "pages_viewed               5.4    5.0  1.0    15.0\n",
       "form_fill_seconds         37.6   35.6  1.1   182.7\n",
       "message_chars            105.9   75.5  0.0  1729.0\n",
       "links_in_message           0.0    0.0  0.0     1.0\n",
       "free_email_domain          0.1    0.0  0.0     1.0\n",
       "submissions_same_ip_24h    1.2    1.0  1.0    14.0"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "columns = [\"seconds_on_site\", \"pages_viewed\", \"form_fill_seconds\", \"message_chars\",\n",
    "           \"links_in_message\", \"free_email_domain\", \"submissions_same_ip_24h\"]\n",
    "leads[columns].describe().round(1).T[[\"mean\", \"50%\", \"min\", \"max\"]]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "bca4cb28",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:51:57.573621Z",
     "iopub.status.busy": "2026-12-05T03:51:57.573549Z",
     "iopub.status.idle": "2026-12-05T03:51:57.581926Z",
     "shell.execute_reply": "2026-12-05T03:51:57.581529Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(4000, 7) [ 0.  0.  0.  0.  0. -0. -0.] [1. 1. 1. 1. 1. 1. 1.]\n"
     ]
    }
   ],
   "source": [
    "X = leads[columns].astype(float)\n",
    "skewed = [\"seconds_on_site\", \"form_fill_seconds\", \"message_chars\", \"submissions_same_ip_24h\"]\n",
    "X[skewed] = np.log1p(X[skewed])   # 10 -> 2.4, 100 -> 4.6, 1,000 -> 6.9\n",
    "\n",
    "Z = StandardScaler().fit_transform(X)\n",
    "print(Z.shape, Z.mean(axis=0).round(2), Z.std(axis=0).round(2))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "aa90ed8e",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:51:57.582903Z",
     "iopub.status.busy": "2026-12-05T03:51:57.582836Z",
     "iopub.status.idle": "2026-12-05T03:51:57.643420Z",
     "shell.execute_reply": "2026-12-05T03:51:57.643024Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "count    4000.00\n",
       "mean        0.73\n",
       "std         0.50\n",
       "min         0.28\n",
       "50%         0.58\n",
       "90%         1.18\n",
       "97%         2.16\n",
       "99%         3.07\n",
       "max         4.29\n",
       "Name: oddness, dtype: float64"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "k = 20\n",
    "distance, index = NearestNeighbors(n_neighbors=k + 1).fit(Z).kneighbors(Z)   # each lead's first neighbour is itself, at distance 0\n",
    "\n",
    "leads[\"oddness\"] = distance[:, 1:].mean(axis=1).round(3)\n",
    "leads[\"oddness\"].describe(percentiles=[0.5, 0.9, 0.97, 0.99]).round(2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "9ebc61e0",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:51:57.644418Z",
     "iopub.status.busy": "2026-12-05T03:51:57.644339Z",
     "iopub.status.idle": "2026-12-05T03:51:57.649130Z",
     "shell.execute_reply": "2026-12-05T03:51:57.648729Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "junk in the queue: 88 of 120 (precision 73.3%)\n",
      "share of all junk caught: 73.3% (recall)\n",
      "AUC over all 4,000 leads: 0.991\n"
     ]
    }
   ],
   "source": [
    "budget = 120\n",
    "queue = leads.sort_values(\"oddness\", ascending=False, kind=\"stable\").head(budget)\n",
    "found = answer[queue.index].sum()\n",
    "\n",
    "print(f\"junk in the queue: {found} of {budget} (precision {found / budget:.1%})\")\n",
    "print(f\"share of all junk caught: {found / answer.sum():.1%} (recall)\")\n",
    "print(f\"AUC over all {len(leads):,} leads: {roc_auc_score(answer, leads['oddness']):.3f}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "a6ed4ac0",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:51:57.650139Z",
     "iopub.status.busy": "2026-12-05T03:51:57.650077Z",
     "iopub.status.idle": "2026-12-05T03:51:57.653533Z",
     "shell.execute_reply": "2026-12-05T03:51:57.653235Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>lead_id</th>\n",
       "      <th>seconds_on_site</th>\n",
       "      <th>pages_viewed</th>\n",
       "      <th>form_fill_seconds</th>\n",
       "      <th>message_chars</th>\n",
       "      <th>links_in_message</th>\n",
       "      <th>free_email_domain</th>\n",
       "      <th>submissions_same_ip_24h</th>\n",
       "      <th>oddness</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>3531</th>\n",
       "      <td>NL-03532</td>\n",
       "      <td>14</td>\n",
       "      <td>2</td>\n",
       "      <td>3.8</td>\n",
       "      <td>40</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>13</td>\n",
       "      <td>4.286</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>621</th>\n",
       "      <td>NL-00622</td>\n",
       "      <td>7</td>\n",
       "      <td>2</td>\n",
       "      <td>2.1</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>2</td>\n",
       "      <td>4.231</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2682</th>\n",
       "      <td>NL-02683</td>\n",
       "      <td>9</td>\n",
       "      <td>1</td>\n",
       "      <td>4.3</td>\n",
       "      <td>40</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>11</td>\n",
       "      <td>4.026</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2038</th>\n",
       "      <td>NL-02039</td>\n",
       "      <td>10</td>\n",
       "      <td>1</td>\n",
       "      <td>2.5</td>\n",
       "      <td>40</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>11</td>\n",
       "      <td>4.012</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1420</th>\n",
       "      <td>NL-01421</td>\n",
       "      <td>3</td>\n",
       "      <td>1</td>\n",
       "      <td>2.4</td>\n",
       "      <td>12</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>2</td>\n",
       "      <td>3.984</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2787</th>\n",
       "      <td>NL-02788</td>\n",
       "      <td>8</td>\n",
       "      <td>2</td>\n",
       "      <td>3.5</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>3</td>\n",
       "      <td>3.970</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "       lead_id  seconds_on_site  pages_viewed  form_fill_seconds  \\\n",
       "3531  NL-03532               14             2                3.8   \n",
       "621   NL-00622                7             2                2.1   \n",
       "2682  NL-02683                9             1                4.3   \n",
       "2038  NL-02039               10             1                2.5   \n",
       "1420  NL-01421                3             1                2.4   \n",
       "2787  NL-02788                8             2                3.5   \n",
       "\n",
       "      message_chars  links_in_message  free_email_domain  \\\n",
       "3531             40                 1                  1   \n",
       "621               0                 0                  1   \n",
       "2682             40                 1                  1   \n",
       "2038             40                 1                  1   \n",
       "1420             12                 0                  1   \n",
       "2787              0                 0                  0   \n",
       "\n",
       "      submissions_same_ip_24h  oddness  \n",
       "3531                       13    4.286  \n",
       "621                         2    4.231  \n",
       "2682                       11    4.026  \n",
       "2038                       11    4.012  \n",
       "1420                        2    3.984  \n",
       "2787                        3    3.970  "
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "queue[[\"lead_id\"] + columns + [\"oddness\"]].head(6)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "40fcc5ab",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:51:57.654529Z",
     "iopub.status.busy": "2026-12-05T03:51:57.654459Z",
     "iopub.status.idle": "2026-12-05T03:51:57.659725Z",
     "shell.execute_reply": "2026-12-05T03:51:57.659413Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>this lead</th>\n",
       "      <th>typical lead</th>\n",
       "      <th>its neighbours</th>\n",
       "      <th>z_score</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>seconds_on_site</th>\n",
       "      <td>14</td>\n",
       "      <td>194.0</td>\n",
       "      <td>13.00</td>\n",
       "      <td>-3.2</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>pages_viewed</th>\n",
       "      <td>2</td>\n",
       "      <td>5.0</td>\n",
       "      <td>1.00</td>\n",
       "      <td>-1.6</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>form_fill_seconds</th>\n",
       "      <td>3.8</td>\n",
       "      <td>35.6</td>\n",
       "      <td>2.65</td>\n",
       "      <td>-2.1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>message_chars</th>\n",
       "      <td>40</td>\n",
       "      <td>75.5</td>\n",
       "      <td>40.00</td>\n",
       "      <td>-0.5</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>links_in_message</th>\n",
       "      <td>1</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.00</td>\n",
       "      <td>4.8</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>free_email_domain</th>\n",
       "      <td>1</td>\n",
       "      <td>0.0</td>\n",
       "      <td>1.00</td>\n",
       "      <td>2.5</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>submissions_same_ip_24h</th>\n",
       "      <td>13</td>\n",
       "      <td>1.0</td>\n",
       "      <td>10.50</td>\n",
       "      <td>8.6</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                        this lead  typical lead  its neighbours  z_score\n",
       "seconds_on_site                14         194.0           13.00     -3.2\n",
       "pages_viewed                    2           5.0            1.00     -1.6\n",
       "form_fill_seconds             3.8          35.6            2.65     -2.1\n",
       "message_chars                  40          75.5           40.00     -0.5\n",
       "links_in_message                1           0.0            0.00      4.8\n",
       "free_email_domain               1           0.0            1.00      2.5\n",
       "submissions_same_ip_24h        13           1.0           10.50      8.6"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def explain(lead_id):\n",
    "    i = leads.index[leads[\"lead_id\"] == lead_id][0]\n",
    "    return pd.DataFrame({\n",
    "        \"this lead\": leads.loc[i, columns],\n",
    "        \"typical lead\": leads[columns].median(),\n",
    "        \"its neighbours\": leads.loc[index[i, 1:], columns].median(),\n",
    "        \"z_score\": Z[i].round(1),\n",
    "    })\n",
    "\n",
    "explain(queue[\"lead_id\"].iloc[0])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "59bed85c",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:51:57.660699Z",
     "iopub.status.busy": "2026-12-05T03:51:57.660631Z",
     "iopub.status.idle": "2026-12-05T03:51:57.664481Z",
     "shell.execute_reply": "2026-12-05T03:51:57.664153Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "32 real leads in the queue\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>lead_id</th>\n",
       "      <th>seconds_on_site</th>\n",
       "      <th>pages_viewed</th>\n",
       "      <th>form_fill_seconds</th>\n",
       "      <th>message_chars</th>\n",
       "      <th>links_in_message</th>\n",
       "      <th>free_email_domain</th>\n",
       "      <th>submissions_same_ip_24h</th>\n",
       "      <th>oddness</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>2570</th>\n",
       "      <td>NL-02571</td>\n",
       "      <td>998</td>\n",
       "      <td>6</td>\n",
       "      <td>49.0</td>\n",
       "      <td>14</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>3.295</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1258</th>\n",
       "      <td>NL-01259</td>\n",
       "      <td>36</td>\n",
       "      <td>6</td>\n",
       "      <td>73.1</td>\n",
       "      <td>5</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>2</td>\n",
       "      <td>3.223</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>218</th>\n",
       "      <td>NL-00219</td>\n",
       "      <td>275</td>\n",
       "      <td>4</td>\n",
       "      <td>67.6</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>3.152</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>201</th>\n",
       "      <td>NL-00202</td>\n",
       "      <td>36</td>\n",
       "      <td>5</td>\n",
       "      <td>9.0</td>\n",
       "      <td>47</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>3.108</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3361</th>\n",
       "      <td>NL-03362</td>\n",
       "      <td>373</td>\n",
       "      <td>15</td>\n",
       "      <td>14.2</td>\n",
       "      <td>3</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>3.064</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2501</th>\n",
       "      <td>NL-02502</td>\n",
       "      <td>369</td>\n",
       "      <td>5</td>\n",
       "      <td>75.5</td>\n",
       "      <td>102</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>2</td>\n",
       "      <td>3.032</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "       lead_id  seconds_on_site  pages_viewed  form_fill_seconds  \\\n",
       "2570  NL-02571              998             6               49.0   \n",
       "1258  NL-01259               36             6               73.1   \n",
       "218   NL-00219              275             4               67.6   \n",
       "201   NL-00202               36             5                9.0   \n",
       "3361  NL-03362              373            15               14.2   \n",
       "2501  NL-02502              369             5               75.5   \n",
       "\n",
       "      message_chars  links_in_message  free_email_domain  \\\n",
       "2570             14                 1                  1   \n",
       "1258              5                 1                  0   \n",
       "218               1                 1                  0   \n",
       "201              47                 1                  1   \n",
       "3361              3                 0                  0   \n",
       "2501            102                 1                  1   \n",
       "\n",
       "      submissions_same_ip_24h  oddness  \n",
       "2570                        1    3.295  \n",
       "1258                        2    3.223  \n",
       "218                         1    3.152  \n",
       "201                         1    3.108  \n",
       "3361                        1    3.064  \n",
       "2501                        2    3.032  "
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "false_alarms = queue[answer[queue.index] == 0]\n",
    "print(f\"{len(false_alarms)} real leads in the queue\")\n",
    "false_alarms[[\"lead_id\"] + columns + [\"oddness\"]].head(6)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "50afa71c",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:51:57.665569Z",
     "iopub.status.busy": "2026-12-05T03:51:57.665493Z",
     "iopub.status.idle": "2026-12-05T03:51:57.672125Z",
     "shell.execute_reply": "2026-12-05T03:51:57.671631Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "32 junk leads not in the queue\n",
      "junk leads with a message over 500 characters: 49, of which in the queue: 18\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>caught</th>\n",
       "      <th>missed</th>\n",
       "      <th>real leads</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>seconds_on_site</th>\n",
       "      <td>14.5</td>\n",
       "      <td>67.5</td>\n",
       "      <td>198.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>pages_viewed</th>\n",
       "      <td>1.0</td>\n",
       "      <td>2.0</td>\n",
       "      <td>5.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>form_fill_seconds</th>\n",
       "      <td>3.9</td>\n",
       "      <td>15.1</td>\n",
       "      <td>36.2</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>message_chars</th>\n",
       "      <td>40.0</td>\n",
       "      <td>1010.0</td>\n",
       "      <td>75.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>links_in_message</th>\n",
       "      <td>0.0</td>\n",
       "      <td>1.0</td>\n",
       "      <td>0.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>free_email_domain</th>\n",
       "      <td>0.0</td>\n",
       "      <td>1.0</td>\n",
       "      <td>0.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>submissions_same_ip_24h</th>\n",
       "      <td>5.5</td>\n",
       "      <td>3.0</td>\n",
       "      <td>1.0</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                         caught  missed  real leads\n",
       "seconds_on_site            14.5    67.5       198.0\n",
       "pages_viewed                1.0     2.0         5.0\n",
       "form_fill_seconds           3.9    15.1        36.2\n",
       "message_chars              40.0  1010.0        75.0\n",
       "links_in_message            0.0     1.0         0.0\n",
       "free_email_domain           0.0     1.0         0.0\n",
       "submissions_same_ip_24h     5.5     3.0         1.0"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "missed = leads[(answer == 1) & ~leads.index.isin(queue.index)]\n",
    "print(f\"{len(missed)} junk leads not in the queue\")\n",
    "long_spam = (answer == 1) & (leads[\"message_chars\"] > 500)\n",
    "print(f\"junk leads with a message over 500 characters: {long_spam.sum()}, \"\n",
    "      f\"of which in the queue: {long_spam[queue.index].sum()}\")\n",
    "pd.DataFrame({\"caught\": queue.loc[answer[queue.index] == 1, columns].median(),\n",
    "              \"missed\": missed[columns].median(),\n",
    "              \"real leads\": leads.loc[answer == 0, columns].median()})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "2113eee8",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:51:57.673239Z",
     "iopub.status.busy": "2026-12-05T03:51:57.673162Z",
     "iopub.status.idle": "2026-12-05T03:51:58.117942Z",
     "shell.execute_reply": "2026-12-05T03:51:58.117423Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "106 junk leads in the first 3,500, queue of 105\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>same_as_k20</th>\n",
       "      <th>junk_in_queue</th>\n",
       "      <th>auc</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>k</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>75</td>\n",
       "      <td>55</td>\n",
       "      <td>0.935</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>75</td>\n",
       "      <td>55</td>\n",
       "      <td>0.969</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>83</td>\n",
       "      <td>63</td>\n",
       "      <td>0.983</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>10</th>\n",
       "      <td>99</td>\n",
       "      <td>73</td>\n",
       "      <td>0.990</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>20</th>\n",
       "      <td>105</td>\n",
       "      <td>78</td>\n",
       "      <td>0.994</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>40</th>\n",
       "      <td>97</td>\n",
       "      <td>86</td>\n",
       "      <td>0.998</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>80</th>\n",
       "      <td>86</td>\n",
       "      <td>92</td>\n",
       "      <td>0.999</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>160</th>\n",
       "      <td>80</td>\n",
       "      <td>94</td>\n",
       "      <td>0.998</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "     same_as_k20  junk_in_queue    auc\n",
       "k                                     \n",
       "1             75             55  0.935\n",
       "2             75             55  0.969\n",
       "5             83             63  0.983\n",
       "10            99             73  0.990\n",
       "20           105             78  0.994\n",
       "40            97             86  0.998\n",
       "80            86             92  0.999\n",
       "160           80             94  0.998"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "tune = X.iloc[:3500]   # choose k on the first 3,500 leads; step 11 tests it on the last 500\n",
    "Z_tune = StandardScaler().fit_transform(tune)\n",
    "budget_tune = round(budget * len(tune) / len(leads))   # the same 3 percent: 105 leads\n",
    "print(f\"{answer[tune.index].sum()} junk leads in the first {len(tune):,}, queue of {budget_tune}\")\n",
    "\n",
    "check, tops = [], {}\n",
    "for k_ in [1, 2, 5, 10, 20, 40, 80, 160]:\n",
    "    d, _ = NearestNeighbors(n_neighbors=k_ + 1).fit(Z_tune).kneighbors(Z_tune)\n",
    "    score = pd.Series(d[:, 1:].mean(axis=1), index=tune.index)\n",
    "    tops[k_] = score.sort_values(ascending=False, kind=\"stable\").head(budget_tune).index\n",
    "    check.append({\"k\": k_, \"junk_in_queue\": int(answer[tops[k_]].sum()),\n",
    "                  \"auc\": round(roc_auc_score(answer[tune.index], score), 3)})\n",
    "check = pd.DataFrame(check).set_index(\"k\")\n",
    "check.insert(0, \"same_as_k20\", [len(tops[k_].intersection(tops[20])) for k_ in check.index])\n",
    "check"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "833b99e4",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:51:58.119078Z",
     "iopub.status.busy": "2026-12-05T03:51:58.119003Z",
     "iopub.status.idle": "2026-12-05T03:51:58.236418Z",
     "shell.execute_reply": "2026-12-05T03:51:58.235950Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "k = 80: junk in the queue: 106 of 120, AUC 0.999\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>lead_id</th>\n",
       "      <th>form_fill_seconds</th>\n",
       "      <th>message_chars</th>\n",
       "      <th>links_in_message</th>\n",
       "      <th>submissions_same_ip_24h</th>\n",
       "      <th>oddness</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>3531</th>\n",
       "      <td>NL-03532</td>\n",
       "      <td>3.8</td>\n",
       "      <td>40</td>\n",
       "      <td>1</td>\n",
       "      <td>13</td>\n",
       "      <td>6.257</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3669</th>\n",
       "      <td>NL-03670</td>\n",
       "      <td>2.4</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>14</td>\n",
       "      <td>6.023</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>326</th>\n",
       "      <td>NL-00327</td>\n",
       "      <td>1.1</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>13</td>\n",
       "      <td>6.020</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2038</th>\n",
       "      <td>NL-02039</td>\n",
       "      <td>2.5</td>\n",
       "      <td>40</td>\n",
       "      <td>1</td>\n",
       "      <td>11</td>\n",
       "      <td>6.000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2682</th>\n",
       "      <td>NL-02683</td>\n",
       "      <td>4.3</td>\n",
       "      <td>40</td>\n",
       "      <td>1</td>\n",
       "      <td>11</td>\n",
       "      <td>5.984</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "       lead_id  form_fill_seconds  message_chars  links_in_message  \\\n",
       "3531  NL-03532                3.8             40                 1   \n",
       "3669  NL-03670                2.4              0                 0   \n",
       "326   NL-00327                1.1              0                 0   \n",
       "2038  NL-02039                2.5             40                 1   \n",
       "2682  NL-02683                4.3             40                 1   \n",
       "\n",
       "      submissions_same_ip_24h  oddness  \n",
       "3531                       13    6.257  \n",
       "3669                       14    6.023  \n",
       "326                        13    6.020  \n",
       "2038                       11    6.000  \n",
       "2682                       11    5.984  "
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "k = 80\n",
    "distance, index = NearestNeighbors(n_neighbors=k + 1).fit(Z).kneighbors(Z)\n",
    "leads[\"oddness\"] = distance[:, 1:].mean(axis=1).round(3)\n",
    "\n",
    "queue = leads.sort_values(\"oddness\", ascending=False, kind=\"stable\").head(budget)\n",
    "found = answer[queue.index].sum()\n",
    "print(f\"k = {k}: junk in the queue: {found} of {budget}, AUC {roc_auc_score(answer, leads['oddness']):.3f}\")\n",
    "queue[[\"lead_id\", \"form_fill_seconds\", \"message_chars\", \"links_in_message\",\n",
    "       \"submissions_same_ip_24h\", \"oddness\"]].head(5)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "69718a33",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:51:58.237438Z",
     "iopub.status.busy": "2026-12-05T03:51:58.237361Z",
     "iopub.status.idle": "2026-12-05T03:51:58.240033Z",
     "shell.execute_reply": "2026-12-05T03:51:58.239686Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "junk leads in a row at the top of the queue: 66\n",
      "leads to review to find all 120 junk leads: 196, of which real: 76\n"
     ]
    }
   ],
   "source": [
    "ranked = answer[leads.sort_values(\"oddness\", ascending=False, kind=\"stable\").index].to_numpy()\n",
    "reviews_for_all = int(np.argmax(ranked.cumsum() == answer.sum())) + 1\n",
    "print(f\"junk leads in a row at the top of the queue: {int(np.argmin(ranked))}\")\n",
    "print(f\"leads to review to find all {answer.sum()} junk leads: {reviews_for_all}, \"\n",
    "      f\"of which real: {reviews_for_all - answer.sum()}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "d19dc40f",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:51:58.241129Z",
     "iopub.status.busy": "2026-12-05T03:51:58.241055Z",
     "iopub.status.idle": "2026-12-05T03:51:58.359661Z",
     "shell.execute_reply": "2026-12-05T03:51:58.359303Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>flagged</th>\n",
       "      <th>junk_caught</th>\n",
       "      <th>precision</th>\n",
       "      <th>recall</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>rule</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>Form filled in under 5 seconds</th>\n",
       "      <td>297</td>\n",
       "      <td>60</td>\n",
       "      <td>0.202</td>\n",
       "      <td>0.500</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3 or more submissions from one IP</th>\n",
       "      <td>86</td>\n",
       "      <td>84</td>\n",
       "      <td>0.977</td>\n",
       "      <td>0.700</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Link in the message</th>\n",
       "      <td>164</td>\n",
       "      <td>60</td>\n",
       "      <td>0.366</td>\n",
       "      <td>0.500</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Any of the three</th>\n",
       "      <td>456</td>\n",
       "      <td>118</td>\n",
       "      <td>0.259</td>\n",
       "      <td>0.983</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>KNN oddness, top 120</th>\n",
       "      <td>120</td>\n",
       "      <td>106</td>\n",
       "      <td>0.883</td>\n",
       "      <td>0.883</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Local outlier factor, top 120</th>\n",
       "      <td>120</td>\n",
       "      <td>47</td>\n",
       "      <td>0.392</td>\n",
       "      <td>0.392</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>IP rule, then KNN, top 120</th>\n",
       "      <td>120</td>\n",
       "      <td>105</td>\n",
       "      <td>0.875</td>\n",
       "      <td>0.875</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                                   flagged  junk_caught  precision  recall\n",
       "rule                                                                      \n",
       "Form filled in under 5 seconds         297           60      0.202   0.500\n",
       "3 or more submissions from one IP       86           84      0.977   0.700\n",
       "Link in the message                    164           60      0.366   0.500\n",
       "Any of the three                       456          118      0.259   0.983\n",
       "KNN oddness, top 120                   120          106      0.883   0.883\n",
       "Local outlier factor, top 120          120           47      0.392   0.392\n",
       "IP rule, then KNN, top 120             120          105      0.875   0.875"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "rules = {\n",
    "    \"Form filled in under 5 seconds\": leads[\"form_fill_seconds\"] < 5,\n",
    "    \"3 or more submissions from one IP\": leads[\"submissions_same_ip_24h\"] >= 3,\n",
    "    \"Link in the message\": leads[\"links_in_message\"] == 1,\n",
    "}\n",
    "rules[\"Any of the three\"] = pd.concat(rules.values(), axis=1).any(axis=1)\n",
    "rules[f\"KNN oddness, top {budget}\"] = leads.index.isin(queue.index)\n",
    "\n",
    "lof = LocalOutlierFactor(n_neighbors=k).fit(Z)\n",
    "lof_score = pd.Series(-lof.negative_outlier_factor_, index=leads.index)\n",
    "rules[f\"Local outlier factor, top {budget}\"] = leads.index.isin(\n",
    "    lof_score.sort_values(ascending=False, kind=\"stable\").head(budget).index)\n",
    "\n",
    "ip_first = leads.assign(ip=rules[\"3 or more submissions from one IP\"]).sort_values(\n",
    "    [\"ip\", \"oddness\"], ascending=False, kind=\"stable\")\n",
    "rules[f\"IP rule, then KNN, top {budget}\"] = leads.index.isin(ip_first.head(budget).index)\n",
    "\n",
    "comparison = pd.DataFrame([\n",
    "    {\"rule\": name, \"flagged\": int(flag.sum()), \"junk_caught\": int(answer[flag].sum()),\n",
    "     \"precision\": round(answer[flag].mean(), 3), \"recall\": round(answer[flag].sum() / answer.sum(), 3)}\n",
    "    for name, flag in rules.items()\n",
    "]).set_index(\"rule\")\n",
    "comparison"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "95c45a1f",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:51:58.360820Z",
     "iopub.status.busy": "2026-12-05T03:51:58.360739Z",
     "iopub.status.idle": "2026-12-05T03:51:58.466317Z",
     "shell.execute_reply": "2026-12-05T03:51:58.465818Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "cut-off: 3.50\n",
      "this week: 12 of 500 leads flagged, 12 of them junk\n",
      "junk this week: 14\n"
     ]
    }
   ],
   "source": [
    "history, new = X.iloc[:3500], X.iloc[3500:]   # the leads k was chosen on, and the most recent 500\n",
    "\n",
    "scaler = StandardScaler().fit(history)\n",
    "nn_history = NearestNeighbors(n_neighbors=k + 1).fit(scaler.transform(history))\n",
    "\n",
    "d, _ = nn_history.kneighbors(scaler.transform(history))\n",
    "cutoff = np.quantile(d[:, 1:].mean(axis=1), 0.97)   # odder than 97% of last quarter's leads\n",
    "\n",
    "d, _ = nn_history.kneighbors(scaler.transform(new), n_neighbors=k)   # new leads are not in the history\n",
    "flagged = new.index[d.mean(axis=1) > cutoff]\n",
    "\n",
    "print(f\"cut-off: {cutoff:.2f}\")\n",
    "print(f\"this week: {len(flagged)} of {len(new)} leads flagged, {answer[flagged].sum()} of them junk\")\n",
    "print(f\"junk this week: {answer[new.index].sum()}\")\n",
    "leads.loc[flagged, [\"lead_id\"]].assign(flag=\"review\").to_csv(\"junk_review_queue.csv\", index=False)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "59656690",
   "metadata": {},
   "source": [
    "## Appendix: the numbers behind the charts\n",
    "\n",
    "The guide's interactive charts are drawn from the numbers computed below. Run these cells after the ones above; the last cell saves everything to `knn_junk_charts.json`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "4847c849",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:51:58.467402Z",
     "iopub.status.busy": "2026-12-05T03:51:58.467335Z",
     "iopub.status.idle": "2026-12-05T03:51:58.866051Z",
     "shell.execute_reply": "2026-12-05T03:51:58.865543Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>k</th>\n",
       "      <th>junk_in_queue</th>\n",
       "      <th>auc</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>5</td>\n",
       "      <td>9</td>\n",
       "      <td>0.501</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>10</td>\n",
       "      <td>13</td>\n",
       "      <td>0.523</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>20</td>\n",
       "      <td>17</td>\n",
       "      <td>0.564</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>40</td>\n",
       "      <td>22</td>\n",
       "      <td>0.722</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>80</td>\n",
       "      <td>52</td>\n",
       "      <td>0.873</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>160</td>\n",
       "      <td>49</td>\n",
       "      <td>0.956</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "     k  junk_in_queue    auc\n",
       "0    5              9  0.501\n",
       "1   10             13  0.523\n",
       "2   20             17  0.564\n",
       "3   40             22  0.722\n",
       "4   80             52  0.873\n",
       "5  160             49  0.956"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import json\n",
    "\n",
    "# Every lead's oddness and whether it was junk: the queue chart and the\n",
    "# score distributions are computed from these two lists in the browser.\n",
    "charts = {\"scores\": [float(s) for s in leads[\"oddness\"]],\n",
    "          \"labels\": [int(v) for v in answer],\n",
    "          \"budget\": budget, \"k\": k, \"spam_crowd\": int(long_spam.sum())}\n",
    "\n",
    "# The rules against the KNN queue (step 10) and the effect of k (step 9)\n",
    "charts[\"rules\"] = comparison.reset_index().to_dict(\"records\")\n",
    "# the k check uses the first 3,500 leads only, as in step 9\n",
    "charts[\"k_check\"] = check.reset_index().to_dict(\"records\")\n",
    "charts[\"budget_tune\"] = budget_tune\n",
    "charts[\"junk_tune\"] = int(answer[tune.index].sum())\n",
    "lof_check = []\n",
    "for k_ in [5, 10, 20, 40, 80, 160]:\n",
    "    s = -LocalOutlierFactor(n_neighbors=k_).fit(Z_tune).negative_outlier_factor_\n",
    "    t = pd.Series(s, index=tune.index).sort_values(ascending=False, kind=\"stable\").head(budget_tune).index\n",
    "    lof_check.append({\"k\": k_, \"junk_in_queue\": int(answer[t].sum()),\n",
    "                      \"auc\": round(roc_auc_score(answer[tune.index], s), 3)})\n",
    "charts[\"lof_check\"] = lof_check\n",
    "pd.DataFrame(lof_check)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "5c20c67c",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:51:58.867144Z",
     "iopub.status.busy": "2026-12-05T03:51:58.867068Z",
     "iopub.status.idle": "2026-12-05T03:51:58.874283Z",
     "shell.execute_reply": "2026-12-05T03:51:58.873850Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>label</th>\n",
       "      <th>id</th>\n",
       "      <th>oddness</th>\n",
       "      <th>junk</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>The oddest lead</td>\n",
       "      <td>NL-03532</td>\n",
       "      <td>6.257</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>A spam message</td>\n",
       "      <td>NL-03697</td>\n",
       "      <td>3.365</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>A real lead in the queue</td>\n",
       "      <td>NL-00219</td>\n",
       "      <td>4.034</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                      label        id  oddness  junk\n",
       "0           The oddest lead  NL-03532    6.257     1\n",
       "1            A spam message  NL-03697    3.365     1\n",
       "2  A real lead in the queue  NL-00219    4.034     0"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Why a lead was flagged: z-scores of the lead and the median of its 80 nearest neighbours,\n",
    "# for the top lead, the oddest spam message, and the oddest real lead in the queue\n",
    "caught = queue[answer[queue.index] == 1]\n",
    "false_alarms = queue[answer[queue.index] == 0]\n",
    "examples = {\n",
    "    \"The oddest lead\": queue[\"lead_id\"].iloc[0],\n",
    "    \"A spam message\": caught.loc[caught[\"links_in_message\"] == 1].sort_values(\n",
    "        \"message_chars\", ascending=False, kind=\"stable\")[\"lead_id\"].iloc[0],\n",
    "    \"A real lead in the queue\": false_alarms[\"lead_id\"].iloc[0],\n",
    "}\n",
    "why = []\n",
    "for label, lead_id in examples.items():\n",
    "    i = leads.index[leads[\"lead_id\"] == lead_id][0]\n",
    "    why.append({\"label\": label, \"id\": lead_id, \"oddness\": float(leads.loc[i, \"oddness\"]),\n",
    "                \"junk\": int(answer[i]),\n",
    "                \"rows\": [{\"col\": c, \"value\": float(leads.loc[i, c]), \"typical\": float(leads[c].median()),\n",
    "                          \"z\": round(float(Z[i, j]), 2),\n",
    "                          \"nz\": round(float(np.median(Z[index[i, 1:], j])), 2)}\n",
    "                         for j, c in enumerate(columns)]})\n",
    "charts[\"why\"] = why\n",
    "pd.DataFrame([{\"label\": w[\"label\"], \"id\": w[\"id\"], \"oddness\": w[\"oddness\"], \"junk\": w[\"junk\"]} for w in why])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "ae4e8da9",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:51:58.875279Z",
     "iopub.status.busy": "2026-12-05T03:51:58.875211Z",
     "iopub.status.idle": "2026-12-05T03:51:58.887380Z",
     "shell.execute_reply": "2026-12-05T03:51:58.887035Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "600 points, 120 junk\n"
     ]
    }
   ],
   "source": [
    "# Playground: two columns only, so it can be drawn. All 120 junk leads and a\n",
    "# sample of 480 real ones; the browser computes distances on these two columns.\n",
    "pick = pd.concat([leads[answer == 1], leads[answer == 0].sample(480, random_state=42)]).sort_index()\n",
    "two = np.log1p(leads[[\"form_fill_seconds\", \"message_chars\"]])\n",
    "charts[\"playground\"] = {\n",
    "    \"mean\": two.mean().round(4).tolist(), \"sd\": two.std(ddof=0).round(4).tolist(),\n",
    "    \"points\": [{\"id\": r.lead_id, \"f\": float(r.form_fill_seconds), \"m\": int(r.message_chars),\n",
    "                \"j\": int(answer[i])} for i, r in pick.iterrows()],\n",
    "}\n",
    "print(len(charts[\"playground\"][\"points\"]), \"points,\", int(answer[pick.index].sum()), \"junk\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "8c4952dd",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:51:58.888536Z",
     "iopub.status.busy": "2026-12-05T03:51:58.888468Z",
     "iopub.status.idle": "2026-12-05T03:51:58.894207Z",
     "shell.execute_reply": "2026-12-05T03:51:58.893871Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "saved 12 chart datasets\n"
     ]
    }
   ],
   "source": [
    "with open(\"knn_junk_charts.json\", \"w\") as f:\n",
    "    json.dump(charts, f, default=lambda o: o.item() if hasattr(o, \"item\") else str(o))\n",
    "print(\"saved\", len(charts), \"chart datasets\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "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.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
