{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "35bee674",
   "metadata": {},
   "source": [
    "# KNN for marketing: build a lookalike audience\n",
    "\n",
    "Companion notebook to the guide at https://martinguzman.ca/blog/knn-lookalike-audiences\n",
    "\n",
    "Put `northpine_accounts.csv` in the same folder as this notebook (download it from https://martinguzman.ca/guides/ml/northpine_accounts.csv). Northpine Software is a made-up company; the data is synthetic."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "081c4dc0",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T02:40:29.756973Z",
     "iopub.status.busy": "2026-12-05T02:40:29.756747Z",
     "iopub.status.idle": "2026-12-05T02:40:30.615322Z",
     "shell.execute_reply": "2026-12-05T02:40:30.614867Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(5000, 14)\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>account_id</th>\n",
       "      <th>industry</th>\n",
       "      <th>region</th>\n",
       "      <th>employees</th>\n",
       "      <th>first_channel</th>\n",
       "      <th>web_visits_90d</th>\n",
       "      <th>pages_per_visit</th>\n",
       "      <th>content_downloads_90d</th>\n",
       "      <th>webinar_attended</th>\n",
       "      <th>email_clicks_90d</th>\n",
       "      <th>pricing_page_visits_90d</th>\n",
       "      <th>days_since_last_visit</th>\n",
       "      <th>became_opportunity</th>\n",
       "      <th>became_customer</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>NP-00001</td>\n",
       "      <td>Professional services</td>\n",
       "      <td>Alberta</td>\n",
       "      <td>41</td>\n",
       "      <td>Referral</td>\n",
       "      <td>9</td>\n",
       "      <td>2.0</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>10</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>NP-00002</td>\n",
       "      <td>Healthcare</td>\n",
       "      <td>Ontario</td>\n",
       "      <td>12</td>\n",
       "      <td>Organic search</td>\n",
       "      <td>3</td>\n",
       "      <td>4.1</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>2</td>\n",
       "      <td>1</td>\n",
       "      <td>18</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>NP-00003</td>\n",
       "      <td>Software</td>\n",
       "      <td>Ontario</td>\n",
       "      <td>146</td>\n",
       "      <td>Organic search</td>\n",
       "      <td>11</td>\n",
       "      <td>2.4</td>\n",
       "      <td>3</td>\n",
       "      <td>0</td>\n",
       "      <td>3</td>\n",
       "      <td>4</td>\n",
       "      <td>6</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>NP-00004</td>\n",
       "      <td>Software</td>\n",
       "      <td>Alberta</td>\n",
       "      <td>36</td>\n",
       "      <td>Organic search</td>\n",
       "      <td>3</td>\n",
       "      <td>1.0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>44</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>NP-00005</td>\n",
       "      <td>Professional services</td>\n",
       "      <td>Quebec</td>\n",
       "      <td>52</td>\n",
       "      <td>Organic search</td>\n",
       "      <td>1</td>\n",
       "      <td>2.1</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>26</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "  account_id               industry   region  employees   first_channel  \\\n",
       "0   NP-00001  Professional services  Alberta         41        Referral   \n",
       "1   NP-00002             Healthcare  Ontario         12  Organic search   \n",
       "2   NP-00003               Software  Ontario        146  Organic search   \n",
       "3   NP-00004               Software  Alberta         36  Organic search   \n",
       "4   NP-00005  Professional services   Quebec         52  Organic search   \n",
       "\n",
       "   web_visits_90d  pages_per_visit  content_downloads_90d  webinar_attended  \\\n",
       "0               9              2.0                      1                 0   \n",
       "1               3              4.1                      0                 0   \n",
       "2              11              2.4                      3                 0   \n",
       "3               3              1.0                      0                 0   \n",
       "4               1              2.1                      0                 0   \n",
       "\n",
       "   email_clicks_90d  pricing_page_visits_90d  days_since_last_visit  \\\n",
       "0                 1                        0                     10   \n",
       "1                 2                        1                     18   \n",
       "2                 3                        4                      6   \n",
       "3                 0                        0                     44   \n",
       "4                 0                        1                     26   \n",
       "\n",
       "   became_opportunity  became_customer  \n",
       "0                   0                0  \n",
       "1                   0                0  \n",
       "2                   1                1  \n",
       "3                   1                0  \n",
       "4                   0                0  "
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "from sklearn.compose import make_column_transformer\n",
    "from sklearn.linear_model import LogisticRegression\n",
    "from sklearn.metrics import roc_auc_score\n",
    "from sklearn.model_selection import (StratifiedKFold, cross_val_predict,\n",
    "                                     cross_val_score, train_test_split)\n",
    "from sklearn.neighbors import KNeighborsClassifier\n",
    "from sklearn.pipeline import make_pipeline\n",
    "from sklearn.preprocessing import OneHotEncoder, StandardScaler\n",
    "\n",
    "accounts = pd.read_csv(\"northpine_accounts.csv\")\n",
    "print(accounts.shape)\n",
    "accounts.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "3d2f6e96",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T02:40:30.616663Z",
     "iopub.status.busy": "2026-12-05T02:40:30.616550Z",
     "iopub.status.idle": "2026-12-05T02:40:30.619096Z",
     "shell.execute_reply": "2026-12-05T02:40:30.618755Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "became_customer\n",
       "0    4634\n",
       "1     366\n",
       "Name: count, dtype: int64"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "accounts[\"became_customer\"].value_counts()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "6e3edacb",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T02:40:30.620161Z",
     "iopub.status.busy": "2026-12-05T02:40:30.620055Z",
     "iopub.status.idle": "2026-12-05T02:40:30.622844Z",
     "shell.execute_reply": "2026-12-05T02:40:30.622443Z"
    }
   },
   "outputs": [],
   "source": [
    "numeric = [\"employees\", \"web_visits_90d\", \"pages_per_visit\",\n",
    "           \"content_downloads_90d\", \"webinar_attended\", \"email_clicks_90d\",\n",
    "           \"pricing_page_visits_90d\", \"days_since_last_visit\"]\n",
    "categorical = [\"industry\"]\n",
    "\n",
    "X = accounts[numeric + categorical].copy()\n",
    "X[\"employees\"] = np.log10(X[\"employees\"])   # 10 -> 1, 100 -> 2, 1,000 -> 3\n",
    "y = accounts[\"became_customer\"]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "c5253baa",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T02:40:30.624003Z",
     "iopub.status.busy": "2026-12-05T02:40:30.623915Z",
     "iopub.status.idle": "2026-12-05T02:40:30.634312Z",
     "shell.execute_reply": "2026-12-05T02:40:30.633916Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "train: 3,500 accounts, 256 customers\n",
      "test:  1,500 accounts, 110 customers\n"
     ]
    }
   ],
   "source": [
    "X_train, X_test, y_train, y_test = train_test_split(\n",
    "    X, y, test_size=0.3, stratify=y, random_state=42)\n",
    "\n",
    "print(f\"train: {len(X_train):,} accounts, {y_train.sum()} customers\")\n",
    "print(f\"test:  {len(X_test):,} accounts, {y_test.sum()} customers\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "29213a04",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T02:40:30.635277Z",
     "iopub.status.busy": "2026-12-05T02:40:30.635214Z",
     "iopub.status.idle": "2026-12-05T02:40:30.636947Z",
     "shell.execute_reply": "2026-12-05T02:40:30.636502Z"
    }
   },
   "outputs": [],
   "source": [
    "prep = make_column_transformer(\n",
    "    (StandardScaler(), numeric),\n",
    "    (OneHotEncoder(handle_unknown=\"ignore\"), categorical),\n",
    ")\n",
    "knn = make_pipeline(prep, KNeighborsClassifier(n_neighbors=25))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "825ab6e1",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T02:40:30.637881Z",
     "iopub.status.busy": "2026-12-05T02:40:30.637804Z",
     "iopub.status.idle": "2026-12-05T02:40:31.987608Z",
     "shell.execute_reply": "2026-12-05T02:40:31.987136Z"
    }
   },
   "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>cv_auc</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>1</td>\n",
       "      <td>0.580</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>5</td>\n",
       "      <td>0.680</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>10</td>\n",
       "      <td>0.729</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>20</td>\n",
       "      <td>0.783</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>40</td>\n",
       "      <td>0.815</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>60</td>\n",
       "      <td>0.820</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>80</td>\n",
       "      <td>0.824</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>120</td>\n",
       "      <td>0.827</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8</th>\n",
       "      <td>160</td>\n",
       "      <td>0.824</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>9</th>\n",
       "      <td>240</td>\n",
       "      <td>0.827</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "     k  cv_auc\n",
       "0    1   0.580\n",
       "1    5   0.680\n",
       "2   10   0.729\n",
       "3   20   0.783\n",
       "4   40   0.815\n",
       "5   60   0.820\n",
       "6   80   0.824\n",
       "7  120   0.827\n",
       "8  160   0.824\n",
       "9  240   0.827"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "folds = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n",
    "\n",
    "results = []\n",
    "for k in [1, 5, 10, 20, 40, 60, 80, 120, 160, 240]:\n",
    "    knn.set_params(kneighborsclassifier__n_neighbors=k)\n",
    "    auc = cross_val_score(knn, X_train, y_train, cv=folds, scoring=\"roc_auc\").mean()\n",
    "    results.append((k, round(auc, 3)))\n",
    "\n",
    "pd.DataFrame(results, columns=[\"k\", \"cv_auc\"])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "7a5a6c70",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T02:40:31.988711Z",
     "iopub.status.busy": "2026-12-05T02:40:31.988642Z",
     "iopub.status.idle": "2026-12-05T02:40:32.063444Z",
     "shell.execute_reply": "2026-12-05T02:40:32.062991Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "k = 120, test AUC = 0.840\n"
     ]
    }
   ],
   "source": [
    "best_k = max(results, key=lambda r: r[1])[0]\n",
    "knn.set_params(kneighborsclassifier__n_neighbors=best_k)\n",
    "knn.fit(X_train, y_train)\n",
    "\n",
    "test_scores = knn.predict_proba(X_test)[:, 1]\n",
    "print(f\"k = {best_k}, test AUC = {roc_auc_score(y_test, test_scores):.3f}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "b24a44db",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T02:40:32.064589Z",
     "iopub.status.busy": "2026-12-05T02:40:32.064507Z",
     "iopub.status.idle": "2026-12-05T02:40:32.069663Z",
     "shell.execute_reply": "2026-12-05T02:40:32.069316Z"
    }
   },
   "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>accounts</th>\n",
       "      <th>customers</th>\n",
       "      <th>rate</th>\n",
       "      <th>lift</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>decile</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>150</td>\n",
       "      <td>43</td>\n",
       "      <td>0.287</td>\n",
       "      <td>3.909</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>150</td>\n",
       "      <td>22</td>\n",
       "      <td>0.147</td>\n",
       "      <td>2.000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>150</td>\n",
       "      <td>19</td>\n",
       "      <td>0.127</td>\n",
       "      <td>1.727</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>150</td>\n",
       "      <td>14</td>\n",
       "      <td>0.093</td>\n",
       "      <td>1.273</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>150</td>\n",
       "      <td>6</td>\n",
       "      <td>0.040</td>\n",
       "      <td>0.545</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>150</td>\n",
       "      <td>5</td>\n",
       "      <td>0.033</td>\n",
       "      <td>0.455</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>150</td>\n",
       "      <td>0</td>\n",
       "      <td>0.000</td>\n",
       "      <td>0.000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8</th>\n",
       "      <td>150</td>\n",
       "      <td>1</td>\n",
       "      <td>0.007</td>\n",
       "      <td>0.091</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>9</th>\n",
       "      <td>150</td>\n",
       "      <td>0</td>\n",
       "      <td>0.000</td>\n",
       "      <td>0.000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>10</th>\n",
       "      <td>150</td>\n",
       "      <td>0</td>\n",
       "      <td>0.000</td>\n",
       "      <td>0.000</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "        accounts  customers   rate   lift\n",
       "decile                                   \n",
       "1            150         43  0.287  3.909\n",
       "2            150         22  0.147  2.000\n",
       "3            150         19  0.127  1.727\n",
       "4            150         14  0.093  1.273\n",
       "5            150          6  0.040  0.545\n",
       "6            150          5  0.033  0.455\n",
       "7            150          0  0.000  0.000\n",
       "8            150          1  0.007  0.091\n",
       "9            150          0  0.000  0.000\n",
       "10           150          0  0.000  0.000"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "ranked = pd.DataFrame({\"score\": test_scores, \"customer\": y_test.values})\n",
    "ranked = ranked.sort_values(\"score\", ascending=False, kind=\"stable\").reset_index(drop=True)\n",
    "ranked[\"decile\"] = ranked.index * 10 // len(ranked) + 1\n",
    "\n",
    "by_decile = ranked.groupby(\"decile\")[\"customer\"].agg(accounts=\"count\",\n",
    "                                                       customers=\"sum\",\n",
    "                                                       rate=\"mean\")\n",
    "by_decile[\"lift\"] = by_decile[\"rate\"] / ranked[\"customer\"].mean()\n",
    "by_decile.round(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "df90b7d3",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T02:40:32.070782Z",
     "iopub.status.busy": "2026-12-05T02:40:32.070703Z",
     "iopub.status.idle": "2026-12-05T02:40:32.076784Z",
     "shell.execute_reply": "2026-12-05T02:40:32.076360Z"
    }
   },
   "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>account_id</th>\n",
       "      <th>industry</th>\n",
       "      <th>employees</th>\n",
       "      <th>pricing_page_visits_90d</th>\n",
       "      <th>content_downloads_90d</th>\n",
       "      <th>webinar_attended</th>\n",
       "      <th>became_customer</th>\n",
       "      <th>distance</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>2539</th>\n",
       "      <td>NP-02540</td>\n",
       "      <td>Software</td>\n",
       "      <td>172</td>\n",
       "      <td>5</td>\n",
       "      <td>5</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>3.96</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2985</th>\n",
       "      <td>NP-02986</td>\n",
       "      <td>Software</td>\n",
       "      <td>178</td>\n",
       "      <td>5</td>\n",
       "      <td>2</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>4.21</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1611</th>\n",
       "      <td>NP-01612</td>\n",
       "      <td>Retail</td>\n",
       "      <td>194</td>\n",
       "      <td>6</td>\n",
       "      <td>3</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>4.31</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4096</th>\n",
       "      <td>NP-04097</td>\n",
       "      <td>Manufacturing</td>\n",
       "      <td>337</td>\n",
       "      <td>6</td>\n",
       "      <td>4</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>4.39</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2026</th>\n",
       "      <td>NP-02027</td>\n",
       "      <td>Software</td>\n",
       "      <td>172</td>\n",
       "      <td>9</td>\n",
       "      <td>3</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>4.93</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "     account_id       industry  employees  pricing_page_visits_90d  \\\n",
       "2539   NP-02540       Software        172                        5   \n",
       "2985   NP-02986       Software        178                        5   \n",
       "1611   NP-01612         Retail        194                        6   \n",
       "4096   NP-04097  Manufacturing        337                        6   \n",
       "2026   NP-02027       Software        172                        9   \n",
       "\n",
       "      content_downloads_90d  webinar_attended  became_customer  distance  \n",
       "2539                      5                 1                0      3.96  \n",
       "2985                      2                 1                1      4.21  \n",
       "1611                      3                 1                1      4.31  \n",
       "4096                      4                 1                1      4.39  \n",
       "2026                      3                 1                0      4.93  "
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "steps = knn.named_steps\n",
    "best = X_test.iloc[[np.argmax(test_scores)]]\n",
    "distance, index = steps[\"kneighborsclassifier\"].kneighbors(\n",
    "    steps[\"columntransformer\"].transform(best), n_neighbors=5)\n",
    "\n",
    "show = [\"account_id\", \"industry\", \"employees\", \"pricing_page_visits_90d\",\n",
    "        \"content_downloads_90d\", \"webinar_attended\", \"became_customer\"]\n",
    "neighbours = accounts.loc[X_train.index[index[0]], show]\n",
    "neighbours.assign(distance=distance[0].round(2))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "c97e0819",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T02:40:32.077785Z",
     "iopub.status.busy": "2026-12-05T02:40:32.077707Z",
     "iopub.status.idle": "2026-12-05T02:40:32.327396Z",
     "shell.execute_reply": "2026-12-05T02:40:32.327033Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "without scaling: 0.772   with scaling: 0.827\n"
     ]
    }
   ],
   "source": [
    "raw = make_pipeline(\n",
    "    make_column_transformer((\"passthrough\", numeric),\n",
    "                            (OneHotEncoder(handle_unknown=\"ignore\"), categorical)),\n",
    "    KNeighborsClassifier(n_neighbors=best_k))\n",
    "\n",
    "auc_raw = cross_val_score(raw, X_train, y_train, cv=folds, scoring=\"roc_auc\").mean()\n",
    "auc_scaled = cross_val_score(knn, X_train, y_train, cv=folds, scoring=\"roc_auc\").mean()\n",
    "print(f\"without scaling: {auc_raw:.3f}   with scaling: {auc_scaled:.3f}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "2c549d5f",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T02:40:32.328510Z",
     "iopub.status.busy": "2026-12-05T02:40:32.328439Z",
     "iopub.status.idle": "2026-12-05T02:40:32.627567Z",
     "shell.execute_reply": "2026-12-05T02:40:32.627126Z"
    }
   },
   "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>account_id</th>\n",
       "      <th>industry</th>\n",
       "      <th>employees</th>\n",
       "      <th>pricing_page_visits_90d</th>\n",
       "      <th>webinar_attended</th>\n",
       "      <th>lookalike_score</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>1616</th>\n",
       "      <td>NP-01617</td>\n",
       "      <td>Professional services</td>\n",
       "      <td>89</td>\n",
       "      <td>7</td>\n",
       "      <td>1</td>\n",
       "      <td>0.483</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2539</th>\n",
       "      <td>NP-02540</td>\n",
       "      <td>Software</td>\n",
       "      <td>172</td>\n",
       "      <td>5</td>\n",
       "      <td>1</td>\n",
       "      <td>0.450</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1444</th>\n",
       "      <td>NP-01445</td>\n",
       "      <td>Professional services</td>\n",
       "      <td>152</td>\n",
       "      <td>5</td>\n",
       "      <td>1</td>\n",
       "      <td>0.425</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1263</th>\n",
       "      <td>NP-01264</td>\n",
       "      <td>Healthcare</td>\n",
       "      <td>116</td>\n",
       "      <td>4</td>\n",
       "      <td>1</td>\n",
       "      <td>0.400</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>956</th>\n",
       "      <td>NP-00957</td>\n",
       "      <td>Software</td>\n",
       "      <td>161</td>\n",
       "      <td>3</td>\n",
       "      <td>1</td>\n",
       "      <td>0.358</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2349</th>\n",
       "      <td>NP-02350</td>\n",
       "      <td>Professional services</td>\n",
       "      <td>613</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>0.358</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3157</th>\n",
       "      <td>NP-03158</td>\n",
       "      <td>Education</td>\n",
       "      <td>46</td>\n",
       "      <td>5</td>\n",
       "      <td>1</td>\n",
       "      <td>0.350</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1046</th>\n",
       "      <td>NP-01047</td>\n",
       "      <td>Manufacturing</td>\n",
       "      <td>58</td>\n",
       "      <td>5</td>\n",
       "      <td>1</td>\n",
       "      <td>0.342</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2582</th>\n",
       "      <td>NP-02583</td>\n",
       "      <td>Software</td>\n",
       "      <td>439</td>\n",
       "      <td>3</td>\n",
       "      <td>0</td>\n",
       "      <td>0.333</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3250</th>\n",
       "      <td>NP-03251</td>\n",
       "      <td>Software</td>\n",
       "      <td>68</td>\n",
       "      <td>4</td>\n",
       "      <td>0</td>\n",
       "      <td>0.333</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "     account_id               industry  employees  pricing_page_visits_90d  \\\n",
       "1616   NP-01617  Professional services         89                        7   \n",
       "2539   NP-02540               Software        172                        5   \n",
       "1444   NP-01445  Professional services        152                        5   \n",
       "1263   NP-01264             Healthcare        116                        4   \n",
       "956    NP-00957               Software        161                        3   \n",
       "2349   NP-02350  Professional services        613                        1   \n",
       "3157   NP-03158              Education         46                        5   \n",
       "1046   NP-01047          Manufacturing         58                        5   \n",
       "2582   NP-02583               Software        439                        3   \n",
       "3250   NP-03251               Software         68                        4   \n",
       "\n",
       "      webinar_attended  lookalike_score  \n",
       "1616                 1            0.483  \n",
       "2539                 1            0.450  \n",
       "1444                 1            0.425  \n",
       "1263                 1            0.400  \n",
       "956                  1            0.358  \n",
       "2349                 1            0.358  \n",
       "3157                 1            0.350  \n",
       "1046                 1            0.342  \n",
       "2582                 0            0.333  \n",
       "3250                 0            0.333  "
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "scores = cross_val_predict(knn, X, y, cv=folds, method=\"predict_proba\")[:, 1]\n",
    "accounts[\"lookalike_score\"] = scores.round(3)\n",
    "\n",
    "prospects = accounts[accounts[\"became_opportunity\"] == 0]\n",
    "shortlist = prospects.sort_values(\"lookalike_score\", ascending=False).head(200)\n",
    "shortlist[[\"account_id\"]].to_csv(\"lookalike_shortlist.csv\", index=False)\n",
    "\n",
    "shortlist[[\"account_id\", \"industry\", \"employees\", \"pricing_page_visits_90d\",\n",
    "           \"webinar_attended\", \"lookalike_score\"]].head(10)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "e4815126",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T02:40:32.628828Z",
     "iopub.status.busy": "2026-12-05T02:40:32.628727Z",
     "iopub.status.idle": "2026-12-05T02:40:32.647495Z",
     "shell.execute_reply": "2026-12-05T02:40:32.646980Z"
    }
   },
   "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>top_10pct_customer_rate</th>\n",
       "      <th>auc</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>Most recent visit first</th>\n",
       "      <td>0.193</td>\n",
       "      <td>0.740</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Most pricing page visits first</th>\n",
       "      <td>0.267</td>\n",
       "      <td>0.719</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>KNN lookalike score</th>\n",
       "      <td>0.287</td>\n",
       "      <td>0.840</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Logistic regression</th>\n",
       "      <td>0.293</td>\n",
       "      <td>0.859</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                                top_10pct_customer_rate    auc\n",
       "Most recent visit first                           0.193  0.740\n",
       "Most pricing page visits first                    0.267  0.719\n",
       "KNN lookalike score                               0.287  0.840\n",
       "Logistic regression                               0.293  0.859"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "logit = make_pipeline(prep, LogisticRegression(max_iter=1000)).fit(X_train, y_train)\n",
    "\n",
    "def top_decile_rate(score):\n",
    "    order = pd.DataFrame({\"score\": score, \"customer\": y_test.values})\n",
    "    order = order.sort_values(\"score\", ascending=False, kind=\"stable\")\n",
    "    return order[\"customer\"].head(len(order) // 10).mean()\n",
    "\n",
    "rankings = {\n",
    "    \"Most recent visit first\": -X_test[\"days_since_last_visit\"],\n",
    "    \"Most pricing page visits first\": X_test[\"pricing_page_visits_90d\"],\n",
    "    \"KNN lookalike score\": test_scores,\n",
    "    \"Logistic regression\": logit.predict_proba(X_test)[:, 1],\n",
    "}\n",
    "pd.DataFrame({\n",
    "    \"top_10pct_customer_rate\": {n: round(top_decile_rate(s), 3) for n, s in rankings.items()},\n",
    "    \"auc\": {n: round(roc_auc_score(y_test, s), 3) for n, s in rankings.items()},\n",
    "})"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "956e345b",
   "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_charts.json`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "58a094c7",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T02:40:32.648770Z",
     "iopub.status.busy": "2026-12-05T02:40:32.648665Z",
     "iopub.status.idle": "2026-12-05T02:40:32.719615Z",
     "shell.execute_reply": "2026-12-05T02:40:32.719008Z"
    }
   },
   "outputs": [],
   "source": [
    "import json\n",
    "from sklearn.base import clone\n",
    "from sklearn.inspection import permutation_importance\n",
    "from sklearn.manifold import TSNE\n",
    "from sklearn.metrics import pairwise_distances\n",
    "\n",
    "# Test-set scores and outcomes: the ROC, precision-recall, score distribution\n",
    "# and cut-off charts are all computed from these two lists.\n",
    "charts = {\"test_scores\": [round(float(s), 4) for s in test_scores],\n",
    "          \"test_labels\": [int(v) for v in y_test]}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "9254cc0e",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T02:40:32.720928Z",
     "iopub.status.busy": "2026-12-05T02:40:32.720826Z",
     "iopub.status.idle": "2026-12-05T02:40:32.742010Z",
     "shell.execute_reply": "2026-12-05T02:40:32.741547Z"
    }
   },
   "outputs": [],
   "source": [
    "# Decision map: KNN on two features only (size and engagement), scored on a grid\n",
    "two = pd.DataFrame({\n",
    "    \"log_employees\": np.log10(accounts[\"employees\"]),\n",
    "    \"engagement\": accounts[\"content_downloads_90d\"] + accounts[\"pricing_page_visits_90d\"]\n",
    "                  + 2 * accounts[\"webinar_attended\"],\n",
    "})\n",
    "scaler2 = StandardScaler().fit(two)\n",
    "grid_x = np.round(np.linspace(0.7, 3.7, 41), 3)\n",
    "grid_y = np.arange(0, 17)\n",
    "gx, gy = np.meshgrid(grid_x, grid_y)\n",
    "cells = scaler2.transform(pd.DataFrame({\"log_employees\": gx.ravel(), \"engagement\": gy.ravel()}))\n",
    "\n",
    "decision = {}\n",
    "for k in [1, 5, 15, 40, 120]:\n",
    "    model2 = KNeighborsClassifier(n_neighbors=k).fit(scaler2.transform(two), y)\n",
    "    decision[k] = model2.predict_proba(cells)[:, 1].round(3).reshape(gy.shape).tolist()\n",
    "charts[\"decision_map\"] = {\"x\": grid_x.tolist(), \"y\": grid_y.tolist(), \"scores\": decision}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "f7cf0693",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T02:40:32.743257Z",
     "iopub.status.busy": "2026-12-05T02:40:32.743190Z",
     "iopub.status.idle": "2026-12-05T02:40:32.748784Z",
     "shell.execute_reply": "2026-12-05T02:40:32.748392Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "53 of 120 neighbours became customers\n"
     ]
    }
   ],
   "source": [
    "# One prospect's neighbourhood: the 120 accounts that vote on the top-scored test account\n",
    "top = X_test.iloc[[np.argmax(test_scores)]]\n",
    "dist, idx = steps[\"kneighborsclassifier\"].kneighbors(steps[\"columntransformer\"].transform(top))\n",
    "rows = accounts.loc[X_train.index[idx[0]]]\n",
    "p = accounts.loc[top.index[0]]\n",
    "charts[\"neighbourhood\"] = {\n",
    "    \"prospect\": {\"id\": p.account_id, \"ind\": p.industry, \"emp\": int(p.employees),\n",
    "                 \"pv\": int(p.pricing_page_visits_90d), \"web\": int(p.webinar_attended)},\n",
    "    \"neighbours\": [{\"id\": r.account_id, \"d\": round(float(d), 3), \"y\": int(r.became_customer),\n",
    "                    \"ind\": r.industry, \"emp\": int(r.employees),\n",
    "                    \"pv\": int(r.pricing_page_visits_90d), \"web\": int(r.webinar_attended)}\n",
    "                   for d, r in zip(dist[0], rows.itertuples())],\n",
    "}\n",
    "print(f\"{sum(n['y'] for n in charts['neighbourhood']['neighbours'])} of 120 neighbours became customers\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "a85dc74e",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T02:40:32.749812Z",
     "iopub.status.busy": "2026-12-05T02:40:32.749746Z",
     "iopub.status.idle": "2026-12-05T02:40:32.759597Z",
     "shell.execute_reply": "2026-12-05T02:40:32.759034Z"
    }
   },
   "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>predicted</th>\n",
       "      <th>actual</th>\n",
       "      <th>n</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>0.0000</td>\n",
       "      <td>0.000</td>\n",
       "      <td>500</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>0.0028</td>\n",
       "      <td>0.004</td>\n",
       "      <td>500</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>0.0113</td>\n",
       "      <td>0.010</td>\n",
       "      <td>500</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>0.0219</td>\n",
       "      <td>0.010</td>\n",
       "      <td>500</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>0.0365</td>\n",
       "      <td>0.034</td>\n",
       "      <td>500</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>0.0532</td>\n",
       "      <td>0.042</td>\n",
       "      <td>500</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>0.0751</td>\n",
       "      <td>0.068</td>\n",
       "      <td>500</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>0.1024</td>\n",
       "      <td>0.110</td>\n",
       "      <td>500</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8</th>\n",
       "      <td>0.1364</td>\n",
       "      <td>0.144</td>\n",
       "      <td>500</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>9</th>\n",
       "      <td>0.2298</td>\n",
       "      <td>0.310</td>\n",
       "      <td>500</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   predicted  actual    n\n",
       "0     0.0000   0.000  500\n",
       "1     0.0028   0.004  500\n",
       "2     0.0113   0.010  500\n",
       "3     0.0219   0.010  500\n",
       "4     0.0365   0.034  500\n",
       "5     0.0532   0.042  500\n",
       "6     0.0751   0.068  500\n",
       "7     0.1024   0.110  500\n",
       "8     0.1364   0.144  500\n",
       "9     0.2298   0.310  500"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Calibration: do accounts scored around 0.3 really buy about 30% of the time?\n",
    "# Uses the cross-validated scores from step 10, so no account scores itself.\n",
    "calibration = {}\n",
    "for bins in [5, 10]:\n",
    "    group = pd.qcut(accounts[\"lookalike_score\"].rank(method=\"first\"), bins, labels=False)\n",
    "    table = accounts.groupby(group).agg(predicted=(\"lookalike_score\", \"mean\"),\n",
    "                                        actual=(\"became_customer\", \"mean\"),\n",
    "                                        n=(\"became_customer\", \"size\"))\n",
    "    calibration[bins] = table.round(4).to_dict(\"records\")\n",
    "charts[\"calibration\"] = calibration\n",
    "pd.DataFrame(calibration[10])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "c9caec70",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T02:40:32.760897Z",
     "iopub.status.busy": "2026-12-05T02:40:32.760773Z",
     "iopub.status.idle": "2026-12-05T02:40:45.105754Z",
     "shell.execute_reply": "2026-12-05T02:40:45.105179Z"
    }
   },
   "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>feature</th>\n",
       "      <th>mean</th>\n",
       "      <th>std</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>employees</td>\n",
       "      <td>0.0483</td>\n",
       "      <td>0.0119</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>pricing_page_visits_90d</td>\n",
       "      <td>0.0183</td>\n",
       "      <td>0.0070</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>web_visits_90d</td>\n",
       "      <td>0.0159</td>\n",
       "      <td>0.0093</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>days_since_last_visit</td>\n",
       "      <td>0.0149</td>\n",
       "      <td>0.0107</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>industry</td>\n",
       "      <td>0.0140</td>\n",
       "      <td>0.0043</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>webinar_attended</td>\n",
       "      <td>0.0119</td>\n",
       "      <td>0.0056</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>email_clicks_90d</td>\n",
       "      <td>0.0090</td>\n",
       "      <td>0.0057</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>pages_per_visit</td>\n",
       "      <td>-0.0003</td>\n",
       "      <td>0.0049</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8</th>\n",
       "      <td>content_downloads_90d</td>\n",
       "      <td>-0.0008</td>\n",
       "      <td>0.0054</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                   feature    mean     std\n",
       "0                employees  0.0483  0.0119\n",
       "1  pricing_page_visits_90d  0.0183  0.0070\n",
       "2           web_visits_90d  0.0159  0.0093\n",
       "3    days_since_last_visit  0.0149  0.0107\n",
       "4                 industry  0.0140  0.0043\n",
       "5         webinar_attended  0.0119  0.0056\n",
       "6         email_clicks_90d  0.0090  0.0057\n",
       "7          pages_per_visit -0.0003  0.0049\n",
       "8    content_downloads_90d -0.0008  0.0054"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# What matters to the model: shuffle one column at a time and measure the drop in AUC\n",
    "imp = permutation_importance(knn, X_test, y_test, scoring=\"roc_auc\",\n",
    "                             n_repeats=20, random_state=42)\n",
    "charts[\"importance\"] = sorted(\n",
    "    [{\"feature\": c, \"mean\": round(float(m), 4), \"std\": round(float(s), 4),\n",
    "      \"runs\": [round(float(v), 4) for v in r]}\n",
    "     for c, m, s, r in zip(X_test.columns, imp.importances_mean, imp.importances_std, imp.importances)],\n",
    "    key=lambda d: -d[\"mean\"])\n",
    "pd.DataFrame(charts[\"importance\"])[[\"feature\", \"mean\", \"std\"]]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "53b7e7ec",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T02:40:45.106810Z",
     "iopub.status.busy": "2026-12-05T02:40:45.106737Z",
     "iopub.status.idle": "2026-12-05T02:40:47.210176Z",
     "shell.execute_reply": "2026-12-05T02:40:47.209570Z"
    }
   },
   "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>noise</th>\n",
       "      <th>auc</th>\n",
       "      <th>nearness</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>0</td>\n",
       "      <td>0.8271</td>\n",
       "      <td>0.503</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>2</td>\n",
       "      <td>0.8175</td>\n",
       "      <td>0.553</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>5</td>\n",
       "      <td>0.8146</td>\n",
       "      <td>0.609</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>10</td>\n",
       "      <td>0.8000</td>\n",
       "      <td>0.671</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>20</td>\n",
       "      <td>0.7820</td>\n",
       "      <td>0.737</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>40</td>\n",
       "      <td>0.7810</td>\n",
       "      <td>0.800</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   noise     auc  nearness\n",
       "0      0  0.8271     0.503\n",
       "1      2  0.8175     0.553\n",
       "2      5  0.8146     0.609\n",
       "3     10  0.8000     0.671\n",
       "4     20  0.7820     0.737\n",
       "5     40  0.7810     0.800"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# The curse of dimensionality: add columns of pure noise and watch AUC fall\n",
    "rng = np.random.default_rng(42)\n",
    "curse = []\n",
    "for n_noise in [0, 2, 5, 10, 20, 40]:\n",
    "    aucs, contrast = [], []\n",
    "    for repeat in range(3):\n",
    "        noise = pd.DataFrame(rng.normal(size=(len(X_train), n_noise)), index=X_train.index,\n",
    "                             columns=[f\"noise_{i}\" for i in range(n_noise)])\n",
    "        Xn = pd.concat([X_train, noise], axis=1)\n",
    "        pipe = make_pipeline(\n",
    "            make_column_transformer((StandardScaler(), numeric + list(noise.columns)),\n",
    "                                    (OneHotEncoder(handle_unknown=\"ignore\"), categorical)),\n",
    "            KNeighborsClassifier(n_neighbors=best_k))\n",
    "        aucs.append(cross_val_score(pipe, Xn, y_train, cv=folds, scoring=\"roc_auc\").mean())\n",
    "        Z = pipe[0].fit_transform(Xn)\n",
    "        Z = Z.toarray() if hasattr(Z, \"toarray\") else Z\n",
    "        d = np.sort(pairwise_distances(Z[rng.choice(len(Z), 300, replace=False)], Z), axis=1)[:, 1:]\n",
    "        # how far an account's 120 nearest neighbours are, as a share of how far a typical\n",
    "        # account is. Near 1 means the \"nearest\" accounts are hardly nearer than anyone else.\n",
    "        contrast.append(np.mean(d[:, :best_k].mean(1) / d.mean(1)))\n",
    "    curse.append({\"noise\": n_noise, \"auc\": round(float(np.mean(aucs)), 4),\n",
    "                  \"nearness\": round(float(np.mean(contrast)), 3)})\n",
    "charts[\"curse\"] = curse\n",
    "pd.DataFrame(curse)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "f75e8966",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T02:40:47.211940Z",
     "iopub.status.busy": "2026-12-05T02:40:47.211821Z",
     "iopub.status.idle": "2026-12-05T02:40:49.744849Z",
     "shell.execute_reply": "2026-12-05T02:40:49.744334Z"
    }
   },
   "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>uniform</th>\n",
       "      <th>distance</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>5</td>\n",
       "      <td>0.6804</td>\n",
       "      <td>0.6831</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>10</td>\n",
       "      <td>0.7292</td>\n",
       "      <td>0.7317</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>20</td>\n",
       "      <td>0.7832</td>\n",
       "      <td>0.7797</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>40</td>\n",
       "      <td>0.8155</td>\n",
       "      <td>0.8126</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>60</td>\n",
       "      <td>0.8200</td>\n",
       "      <td>0.8193</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>80</td>\n",
       "      <td>0.8237</td>\n",
       "      <td>0.8234</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>120</td>\n",
       "      <td>0.8271</td>\n",
       "      <td>0.8267</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>160</td>\n",
       "      <td>0.8242</td>\n",
       "      <td>0.8248</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8</th>\n",
       "      <td>240</td>\n",
       "      <td>0.8269</td>\n",
       "      <td>0.8276</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "     k  uniform  distance\n",
       "0    5   0.6804    0.6831\n",
       "1   10   0.7292    0.7317\n",
       "2   20   0.7832    0.7797\n",
       "3   40   0.8155    0.8126\n",
       "4   60   0.8200    0.8193\n",
       "5   80   0.8237    0.8234\n",
       "6  120   0.8271    0.8267\n",
       "7  160   0.8242    0.8248\n",
       "8  240   0.8269    0.8276"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Uniform votes against votes weighted by closeness\n",
    "weighting = []\n",
    "for k in [5, 10, 20, 40, 60, 80, 120, 160, 240]:\n",
    "    row = {\"k\": k}\n",
    "    for w in [\"uniform\", \"distance\"]:\n",
    "        m = make_pipeline(clone(prep), KNeighborsClassifier(n_neighbors=k, weights=w))\n",
    "        row[w] = round(float(cross_val_score(m, X_train, y_train, cv=folds, scoring=\"roc_auc\").mean()), 4)\n",
    "    weighting.append(row)\n",
    "charts[\"weighting\"] = weighting\n",
    "pd.DataFrame(weighting)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "25e36794",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T02:40:49.745966Z",
     "iopub.status.busy": "2026-12-05T02:40:49.745882Z",
     "iopub.status.idle": "2026-12-05T02:40:50.188212Z",
     "shell.execute_reply": "2026-12-05T02:40:50.187751Z"
    }
   },
   "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>n</th>\n",
       "      <th>k</th>\n",
       "      <th>auc</th>\n",
       "      <th>sd</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>250</td>\n",
       "      <td>11</td>\n",
       "      <td>0.7100</td>\n",
       "      <td>0.0159</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>500</td>\n",
       "      <td>21</td>\n",
       "      <td>0.7516</td>\n",
       "      <td>0.0208</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>1000</td>\n",
       "      <td>43</td>\n",
       "      <td>0.7792</td>\n",
       "      <td>0.0210</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>1750</td>\n",
       "      <td>75</td>\n",
       "      <td>0.8175</td>\n",
       "      <td>0.0151</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>2800</td>\n",
       "      <td>120</td>\n",
       "      <td>0.8271</td>\n",
       "      <td>0.0194</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "      n    k     auc      sd\n",
       "0   250   11  0.7100  0.0159\n",
       "1   500   21  0.7516  0.0208\n",
       "2  1000   43  0.7792  0.0210\n",
       "3  1750   75  0.8175  0.0151\n",
       "4  2800  120  0.8271  0.0194"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Learning curve: how good does the model get with more training accounts?\n",
    "# k grows with the data, keeping the same share of accounts in each vote as the final model.\n",
    "learning = []\n",
    "for n in [250, 500, 1000, 1750, 2800]:\n",
    "    k = max(5, round(n * best_k / 2800))\n",
    "    fold_aucs = []\n",
    "    for train_idx, valid_idx in folds.split(X_train, y_train):\n",
    "        sub = pd.Series(train_idx).sample(n=min(n, len(train_idx)), random_state=42).values\n",
    "        m = make_pipeline(clone(prep), KNeighborsClassifier(n_neighbors=k))\n",
    "        m.fit(X_train.iloc[sub], y_train.iloc[sub])\n",
    "        fold_aucs.append(roc_auc_score(y_train.iloc[valid_idx],\n",
    "                                       m.predict_proba(X_train.iloc[valid_idx])[:, 1]))\n",
    "    learning.append({\"n\": n, \"k\": k, \"auc\": round(float(np.mean(fold_aucs)), 4),\n",
    "                     \"sd\": round(float(np.std(fold_aucs)), 4)})\n",
    "charts[\"learning\"] = learning\n",
    "pd.DataFrame(learning)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "1a509f34",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T02:40:50.189316Z",
     "iopub.status.busy": "2026-12-05T02:40:50.189226Z",
     "iopub.status.idle": "2026-12-05T02:40:56.590748Z",
     "shell.execute_reply": "2026-12-05T02:40:56.590068Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "other        1849\n",
      "customer      366\n",
      "pipeline      358\n",
      "lookalike     200\n",
      "Name: count, dtype: int64\n"
     ]
    }
   ],
   "source": [
    "# Audience map: all 5,000 accounts squeezed onto two dimensions with t-SNE\n",
    "embedding = TSNE(n_components=2, perplexity=40, init=\"pca\", random_state=42).fit_transform(\n",
    "    clone(prep).fit_transform(X))\n",
    "group = np.select([accounts[\"became_customer\"] == 1,\n",
    "                   accounts[\"account_id\"].isin(shortlist[\"account_id\"]),\n",
    "                   accounts[\"became_opportunity\"] == 1],\n",
    "                  [\"customer\", \"lookalike\", \"pipeline\"], \"other\")\n",
    "keep = (group != \"other\") | (np.random.default_rng(42).random(len(group)) < 0.45)\n",
    "charts[\"tsne\"] = [{\"x\": round(float(e[0]), 1), \"y\": round(float(e[1]), 1), \"g\": str(g),\n",
    "                   \"s\": float(sc), \"id\": i}\n",
    "                  for e, g, sc, i, k_ in zip(embedding, group, accounts[\"lookalike_score\"],\n",
    "                                             accounts[\"account_id\"], keep) if k_]\n",
    "print(pd.Series(group[keep]).value_counts())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "dd132b38",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T02:40:56.591875Z",
     "iopub.status.busy": "2026-12-05T02:40:56.591776Z",
     "iopub.status.idle": "2026-12-05T02:40:56.605851Z",
     "shell.execute_reply": "2026-12-05T02:40:56.605362Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "saved 10 chart datasets\n"
     ]
    }
   ],
   "source": [
    "with open(\"knn_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
}
