{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "c9c574c7",
   "metadata": {},
   "source": [
    "# KNN for marketing: a churn early warning list\n",
    "\n",
    "Companion notebook to the guide at https://martinguzman.ca/blog/knn-churn-early-warning\n",
    "\n",
    "Put `northpine_customers.csv` in the same folder as this notebook (download it from https://martinguzman.ca/guides/ml/northpine_customers.csv). Northpine Software is a made-up company; the data is synthetic."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "62e85bcb",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:48:41.726510Z",
     "iopub.status.busy": "2026-12-05T03:48:41.726228Z",
     "iopub.status.idle": "2026-12-05T03:48:42.588658Z",
     "shell.execute_reply": "2026-12-05T03:48:42.588227Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(4000, 15)\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>customer_id</th>\n",
       "      <th>industry</th>\n",
       "      <th>region</th>\n",
       "      <th>employees</th>\n",
       "      <th>first_channel</th>\n",
       "      <th>plan</th>\n",
       "      <th>signup_discount_pct</th>\n",
       "      <th>tenure_months</th>\n",
       "      <th>onboarding_completed</th>\n",
       "      <th>integrations_connected</th>\n",
       "      <th>seats_used_pct</th>\n",
       "      <th>logins_per_week</th>\n",
       "      <th>support_tickets_90d</th>\n",
       "      <th>first_year_value</th>\n",
       "      <th>churned_next_90d</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>NC-00001</td>\n",
       "      <td>Education</td>\n",
       "      <td>Alberta</td>\n",
       "      <td>183</td>\n",
       "      <td>Referral</td>\n",
       "      <td>Growth</td>\n",
       "      <td>25</td>\n",
       "      <td>7</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>0.54</td>\n",
       "      <td>3.7</td>\n",
       "      <td>0</td>\n",
       "      <td>11210</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>NC-00002</td>\n",
       "      <td>Software</td>\n",
       "      <td>Quebec</td>\n",
       "      <td>2706</td>\n",
       "      <td>Paid search</td>\n",
       "      <td>Growth</td>\n",
       "      <td>0</td>\n",
       "      <td>17</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>0.63</td>\n",
       "      <td>7.1</td>\n",
       "      <td>1</td>\n",
       "      <td>28640</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>NC-00003</td>\n",
       "      <td>Education</td>\n",
       "      <td>Quebec</td>\n",
       "      <td>546</td>\n",
       "      <td>Paid search</td>\n",
       "      <td>Enterprise</td>\n",
       "      <td>15</td>\n",
       "      <td>17</td>\n",
       "      <td>1</td>\n",
       "      <td>3</td>\n",
       "      <td>0.83</td>\n",
       "      <td>12.7</td>\n",
       "      <td>2</td>\n",
       "      <td>37270</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>NC-00004</td>\n",
       "      <td>Healthcare</td>\n",
       "      <td>Atlantic</td>\n",
       "      <td>449</td>\n",
       "      <td>Content syndication</td>\n",
       "      <td>Growth</td>\n",
       "      <td>10</td>\n",
       "      <td>36</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>0.96</td>\n",
       "      <td>4.3</td>\n",
       "      <td>1</td>\n",
       "      <td>18150</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>NC-00005</td>\n",
       "      <td>Professional services</td>\n",
       "      <td>Ontario</td>\n",
       "      <td>36</td>\n",
       "      <td>Referral</td>\n",
       "      <td>Starter</td>\n",
       "      <td>0</td>\n",
       "      <td>30</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>0.41</td>\n",
       "      <td>9.4</td>\n",
       "      <td>2</td>\n",
       "      <td>8290</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "  customer_id               industry    region  employees  \\\n",
       "0    NC-00001              Education   Alberta        183   \n",
       "1    NC-00002               Software    Quebec       2706   \n",
       "2    NC-00003              Education    Quebec        546   \n",
       "3    NC-00004             Healthcare  Atlantic        449   \n",
       "4    NC-00005  Professional services   Ontario         36   \n",
       "\n",
       "         first_channel        plan  signup_discount_pct  tenure_months  \\\n",
       "0             Referral      Growth                   25              7   \n",
       "1          Paid search      Growth                    0             17   \n",
       "2          Paid search  Enterprise                   15             17   \n",
       "3  Content syndication      Growth                   10             36   \n",
       "4             Referral     Starter                    0             30   \n",
       "\n",
       "   onboarding_completed  integrations_connected  seats_used_pct  \\\n",
       "0                     1                       1            0.54   \n",
       "1                     1                       0            0.63   \n",
       "2                     1                       3            0.83   \n",
       "3                     1                       1            0.96   \n",
       "4                     1                       0            0.41   \n",
       "\n",
       "   logins_per_week  support_tickets_90d  first_year_value  churned_next_90d  \n",
       "0              3.7                    0             11210                 0  \n",
       "1              7.1                    1             28640                 0  \n",
       "2             12.7                    2             37270                 0  \n",
       "3              4.3                    1             18150                 0  \n",
       "4              9.4                    2              8290                 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_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",
    "customers = pd.read_csv(\"northpine_customers.csv\")\n",
    "print(customers.shape)\n",
    "customers.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "504b504c",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:48:42.589828Z",
     "iopub.status.busy": "2026-12-05T03:48:42.589727Z",
     "iopub.status.idle": "2026-12-05T03:48:42.592567Z",
     "shell.execute_reply": "2026-12-05T03:48:42.592057Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "churned_next_90d\n",
       "0    2974\n",
       "1    1026\n",
       "Name: count, dtype: int64"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "customers[\"churned_next_90d\"].value_counts()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "74068702",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:48:42.594013Z",
     "iopub.status.busy": "2026-12-05T03:48:42.593884Z",
     "iopub.status.idle": "2026-12-05T03:48:42.596905Z",
     "shell.execute_reply": "2026-12-05T03:48:42.596384Z"
    }
   },
   "outputs": [],
   "source": [
    "numeric = [\"employees\", \"signup_discount_pct\", \"tenure_months\", \"onboarding_completed\",\n",
    "           \"integrations_connected\", \"seats_used_pct\", \"logins_per_week\",\n",
    "           \"support_tickets_90d\"]\n",
    "categorical = [\"plan\"]\n",
    "\n",
    "X = customers[numeric + categorical].copy()\n",
    "X[\"employees\"] = np.log10(X[\"employees\"])   # 10 -> 1, 100 -> 2, 1,000 -> 3\n",
    "y = customers[\"churned_next_90d\"]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "9ad7f9b4",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:48:42.597862Z",
     "iopub.status.busy": "2026-12-05T03:48:42.597800Z",
     "iopub.status.idle": "2026-12-05T03:48:42.608831Z",
     "shell.execute_reply": "2026-12-05T03:48:42.608389Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "past customers (to learn from): 2,800, 718 churned\n",
      "customers to score now:         1,200, 308 churned\n"
     ]
    }
   ],
   "source": [
    "X_past, X_now, y_past, y_now = train_test_split(\n",
    "    X, y, test_size=0.3, stratify=y, random_state=42)\n",
    "\n",
    "print(f\"past customers (to learn from): {len(X_past):,}, {y_past.sum()} churned\")\n",
    "print(f\"customers to score now:         {len(X_now):,}, {y_now.sum()} churned\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "73d3660d",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:48:42.610112Z",
     "iopub.status.busy": "2026-12-05T03:48:42.610026Z",
     "iopub.status.idle": "2026-12-05T03:48:42.612172Z",
     "shell.execute_reply": "2026-12-05T03:48:42.611737Z"
    }
   },
   "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": "05ba9a8c",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:48:42.613449Z",
     "iopub.status.busy": "2026-12-05T03:48:42.613355Z",
     "iopub.status.idle": "2026-12-05T03:48:44.172606Z",
     "shell.execute_reply": "2026-12-05T03:48:44.172017Z"
    }
   },
   "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.594</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>5</td>\n",
       "      <td>0.686</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>10</td>\n",
       "      <td>0.710</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>20</td>\n",
       "      <td>0.735</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>40</td>\n",
       "      <td>0.738</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>80</td>\n",
       "      <td>0.741</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>120</td>\n",
       "      <td>0.743</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>160</td>\n",
       "      <td>0.746</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8</th>\n",
       "      <td>240</td>\n",
       "      <td>0.753</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>9</th>\n",
       "      <td>320</td>\n",
       "      <td>0.752</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>10</th>\n",
       "      <td>480</td>\n",
       "      <td>0.757</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>11</th>\n",
       "      <td>640</td>\n",
       "      <td>0.757</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "      k  cv_auc\n",
       "0     1   0.594\n",
       "1     5   0.686\n",
       "2    10   0.710\n",
       "3    20   0.735\n",
       "4    40   0.738\n",
       "5    80   0.741\n",
       "6   120   0.743\n",
       "7   160   0.746\n",
       "8   240   0.753\n",
       "9   320   0.752\n",
       "10  480   0.757\n",
       "11  640   0.757"
      ]
     },
     "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, 80, 120, 160, 240, 320, 480, 640]:\n",
    "    knn.set_params(kneighborsclassifier__n_neighbors=k)\n",
    "    auc = cross_val_score(knn, X_past, y_past, 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": "d14d76f2",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:48:44.173679Z",
     "iopub.status.busy": "2026-12-05T03:48:44.173593Z",
     "iopub.status.idle": "2026-12-05T03:48:44.278577Z",
     "shell.execute_reply": "2026-12-05T03:48:44.278054Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "k = 480, test AUC = 0.774\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_past, y_past)\n",
    "\n",
    "risk = knn.predict_proba(X_now)[:, 1]\n",
    "print(f\"k = {best_k}, test AUC = {roc_auc_score(y_now, risk):.3f}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "7477792c",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:48:44.279540Z",
     "iopub.status.busy": "2026-12-05T03:48:44.279457Z",
     "iopub.status.idle": "2026-12-05T03:48:44.284637Z",
     "shell.execute_reply": "2026-12-05T03:48:44.284297Z"
    }
   },
   "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>customers</th>\n",
       "      <th>churned</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>120</td>\n",
       "      <td>91</td>\n",
       "      <td>0.758</td>\n",
       "      <td>2.955</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>120</td>\n",
       "      <td>52</td>\n",
       "      <td>0.433</td>\n",
       "      <td>1.688</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>120</td>\n",
       "      <td>40</td>\n",
       "      <td>0.333</td>\n",
       "      <td>1.299</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>120</td>\n",
       "      <td>33</td>\n",
       "      <td>0.275</td>\n",
       "      <td>1.071</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>120</td>\n",
       "      <td>30</td>\n",
       "      <td>0.250</td>\n",
       "      <td>0.974</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>120</td>\n",
       "      <td>19</td>\n",
       "      <td>0.158</td>\n",
       "      <td>0.617</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>120</td>\n",
       "      <td>13</td>\n",
       "      <td>0.108</td>\n",
       "      <td>0.422</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8</th>\n",
       "      <td>120</td>\n",
       "      <td>10</td>\n",
       "      <td>0.083</td>\n",
       "      <td>0.325</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>9</th>\n",
       "      <td>120</td>\n",
       "      <td>11</td>\n",
       "      <td>0.092</td>\n",
       "      <td>0.357</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>10</th>\n",
       "      <td>120</td>\n",
       "      <td>9</td>\n",
       "      <td>0.075</td>\n",
       "      <td>0.292</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "        customers  churned   rate   lift\n",
       "decile                                  \n",
       "1             120       91  0.758  2.955\n",
       "2             120       52  0.433  1.688\n",
       "3             120       40  0.333  1.299\n",
       "4             120       33  0.275  1.071\n",
       "5             120       30  0.250  0.974\n",
       "6             120       19  0.158  0.617\n",
       "7             120       13  0.108  0.422\n",
       "8             120       10  0.083  0.325\n",
       "9             120       11  0.092  0.357\n",
       "10            120        9  0.075  0.292"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "ranked = pd.DataFrame({\"risk\": risk, \"churned\": y_now.values})\n",
    "ranked = ranked.sort_values(\"risk\", ascending=False, kind=\"stable\").reset_index(drop=True)\n",
    "ranked[\"decile\"] = ranked.index * 10 // len(ranked) + 1\n",
    "\n",
    "by_decile = ranked.groupby(\"decile\")[\"churned\"].agg(customers=\"count\",\n",
    "                                                    churned=\"sum\",\n",
    "                                                    rate=\"mean\")\n",
    "by_decile[\"lift\"] = by_decile[\"rate\"] / ranked[\"churned\"].mean()\n",
    "by_decile.round(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "5da60d51",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:48:44.286013Z",
     "iopub.status.busy": "2026-12-05T03:48:44.285935Z",
     "iopub.status.idle": "2026-12-05T03:48:44.293260Z",
     "shell.execute_reply": "2026-12-05T03:48:44.292738Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "customer_id   plan  tenure_months  onboarding_completed  seats_used_pct  logins_per_week  support_tickets_90d  churned_next_90d\n",
      "   NC-02063 Growth             15                     0            0.03              1.6                    4                 1\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>customer_id</th>\n",
       "      <th>plan</th>\n",
       "      <th>tenure_months</th>\n",
       "      <th>onboarding_completed</th>\n",
       "      <th>seats_used_pct</th>\n",
       "      <th>logins_per_week</th>\n",
       "      <th>support_tickets_90d</th>\n",
       "      <th>churned_next_90d</th>\n",
       "      <th>distance</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>3943</th>\n",
       "      <td>NC-03944</td>\n",
       "      <td>Growth</td>\n",
       "      <td>13</td>\n",
       "      <td>0</td>\n",
       "      <td>0.21</td>\n",
       "      <td>1.8</td>\n",
       "      <td>3</td>\n",
       "      <td>0</td>\n",
       "      <td>1.31</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3922</th>\n",
       "      <td>NC-03923</td>\n",
       "      <td>Growth</td>\n",
       "      <td>10</td>\n",
       "      <td>0</td>\n",
       "      <td>0.29</td>\n",
       "      <td>1.6</td>\n",
       "      <td>5</td>\n",
       "      <td>1</td>\n",
       "      <td>1.55</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2852</th>\n",
       "      <td>NC-02853</td>\n",
       "      <td>Growth</td>\n",
       "      <td>13</td>\n",
       "      <td>0</td>\n",
       "      <td>0.14</td>\n",
       "      <td>3.5</td>\n",
       "      <td>4</td>\n",
       "      <td>0</td>\n",
       "      <td>1.57</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2983</th>\n",
       "      <td>NC-02984</td>\n",
       "      <td>Growth</td>\n",
       "      <td>15</td>\n",
       "      <td>0</td>\n",
       "      <td>0.03</td>\n",
       "      <td>4.1</td>\n",
       "      <td>5</td>\n",
       "      <td>1</td>\n",
       "      <td>1.61</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2422</th>\n",
       "      <td>NC-02423</td>\n",
       "      <td>Growth</td>\n",
       "      <td>23</td>\n",
       "      <td>0</td>\n",
       "      <td>0.28</td>\n",
       "      <td>0.3</td>\n",
       "      <td>4</td>\n",
       "      <td>1</td>\n",
       "      <td>1.63</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "     customer_id    plan  tenure_months  onboarding_completed  seats_used_pct  \\\n",
       "3943    NC-03944  Growth             13                     0            0.21   \n",
       "3922    NC-03923  Growth             10                     0            0.29   \n",
       "2852    NC-02853  Growth             13                     0            0.14   \n",
       "2983    NC-02984  Growth             15                     0            0.03   \n",
       "2422    NC-02423  Growth             23                     0            0.28   \n",
       "\n",
       "      logins_per_week  support_tickets_90d  churned_next_90d  distance  \n",
       "3943              1.8                    3                 0      1.31  \n",
       "3922              1.6                    5                 1      1.55  \n",
       "2852              3.5                    4                 0      1.57  \n",
       "2983              4.1                    5                 1      1.61  \n",
       "2422              0.3                    4                 1      1.63  "
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "steps = knn.named_steps\n",
    "top = X_now.iloc[[np.argmax(risk)]]\n",
    "distance, index = steps[\"kneighborsclassifier\"].kneighbors(\n",
    "    steps[\"columntransformer\"].transform(top), n_neighbors=5)\n",
    "\n",
    "show = [\"customer_id\", \"plan\", \"tenure_months\", \"onboarding_completed\",\n",
    "        \"seats_used_pct\", \"logins_per_week\", \"support_tickets_90d\", \"churned_next_90d\"]\n",
    "print(customers.loc[top.index, show].to_string(index=False))\n",
    "neighbours = customers.loc[X_past.index[index[0]], show]\n",
    "neighbours.assign(distance=distance[0].round(2))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "06e8f4cb",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:48:44.294340Z",
     "iopub.status.busy": "2026-12-05T03:48:44.294259Z",
     "iopub.status.idle": "2026-12-05T03:48:44.318346Z",
     "shell.execute_reply": "2026-12-05T03:48:44.317875Z"
    }
   },
   "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>customer_id</th>\n",
       "      <th>plan</th>\n",
       "      <th>seats_used_pct</th>\n",
       "      <th>logins_per_week</th>\n",
       "      <th>support_tickets_90d</th>\n",
       "      <th>risk</th>\n",
       "      <th>reason</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>2062</th>\n",
       "      <td>NC-02063</td>\n",
       "      <td>Growth</td>\n",
       "      <td>0.03</td>\n",
       "      <td>1.6</td>\n",
       "      <td>4</td>\n",
       "      <td>0.588</td>\n",
       "      <td>8 of its 10 closest past customers left</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1078</th>\n",
       "      <td>NC-01079</td>\n",
       "      <td>Growth</td>\n",
       "      <td>0.03</td>\n",
       "      <td>2.4</td>\n",
       "      <td>4</td>\n",
       "      <td>0.581</td>\n",
       "      <td>7 of its 10 closest past customers left</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1849</th>\n",
       "      <td>NC-01850</td>\n",
       "      <td>Growth</td>\n",
       "      <td>0.03</td>\n",
       "      <td>1.6</td>\n",
       "      <td>4</td>\n",
       "      <td>0.569</td>\n",
       "      <td>10 of its 10 closest past customers left</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1522</th>\n",
       "      <td>NC-01523</td>\n",
       "      <td>Growth</td>\n",
       "      <td>0.26</td>\n",
       "      <td>1.8</td>\n",
       "      <td>6</td>\n",
       "      <td>0.562</td>\n",
       "      <td>8 of its 10 closest past customers left</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1370</th>\n",
       "      <td>NC-01371</td>\n",
       "      <td>Growth</td>\n",
       "      <td>0.14</td>\n",
       "      <td>0.6</td>\n",
       "      <td>5</td>\n",
       "      <td>0.558</td>\n",
       "      <td>10 of its 10 closest past customers left</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2526</th>\n",
       "      <td>NC-02527</td>\n",
       "      <td>Growth</td>\n",
       "      <td>0.20</td>\n",
       "      <td>0.9</td>\n",
       "      <td>8</td>\n",
       "      <td>0.554</td>\n",
       "      <td>9 of its 10 closest past customers left</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2684</th>\n",
       "      <td>NC-02685</td>\n",
       "      <td>Growth</td>\n",
       "      <td>0.23</td>\n",
       "      <td>2.4</td>\n",
       "      <td>6</td>\n",
       "      <td>0.552</td>\n",
       "      <td>9 of its 10 closest past customers left</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2964</th>\n",
       "      <td>NC-02965</td>\n",
       "      <td>Growth</td>\n",
       "      <td>0.14</td>\n",
       "      <td>1.2</td>\n",
       "      <td>5</td>\n",
       "      <td>0.542</td>\n",
       "      <td>9 of its 10 closest past customers left</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1015</th>\n",
       "      <td>NC-01016</td>\n",
       "      <td>Growth</td>\n",
       "      <td>0.17</td>\n",
       "      <td>2.5</td>\n",
       "      <td>4</td>\n",
       "      <td>0.542</td>\n",
       "      <td>8 of its 10 closest past customers left</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>80</th>\n",
       "      <td>NC-00081</td>\n",
       "      <td>Growth</td>\n",
       "      <td>0.21</td>\n",
       "      <td>1.4</td>\n",
       "      <td>5</td>\n",
       "      <td>0.540</td>\n",
       "      <td>8 of its 10 closest past customers left</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "     customer_id    plan  seats_used_pct  logins_per_week  \\\n",
       "2062    NC-02063  Growth            0.03              1.6   \n",
       "1078    NC-01079  Growth            0.03              2.4   \n",
       "1849    NC-01850  Growth            0.03              1.6   \n",
       "1522    NC-01523  Growth            0.26              1.8   \n",
       "1370    NC-01371  Growth            0.14              0.6   \n",
       "2526    NC-02527  Growth            0.20              0.9   \n",
       "2684    NC-02685  Growth            0.23              2.4   \n",
       "2964    NC-02965  Growth            0.14              1.2   \n",
       "1015    NC-01016  Growth            0.17              2.5   \n",
       "80      NC-00081  Growth            0.21              1.4   \n",
       "\n",
       "      support_tickets_90d   risk                                    reason  \n",
       "2062                    4  0.588   8 of its 10 closest past customers left  \n",
       "1078                    4  0.581   7 of its 10 closest past customers left  \n",
       "1849                    4  0.569  10 of its 10 closest past customers left  \n",
       "1522                    6  0.562   8 of its 10 closest past customers left  \n",
       "1370                    5  0.558  10 of its 10 closest past customers left  \n",
       "2526                    8  0.554   9 of its 10 closest past customers left  \n",
       "2684                    6  0.552   9 of its 10 closest past customers left  \n",
       "2964                    5  0.542   9 of its 10 closest past customers left  \n",
       "1015                    4  0.542   8 of its 10 closest past customers left  \n",
       "80                      5  0.540   8 of its 10 closest past customers left  "
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "now = customers.loc[X_now.index].copy()\n",
    "now[\"risk\"] = risk.round(3)\n",
    "\n",
    "_, closest = steps[\"kneighborsclassifier\"].kneighbors(\n",
    "    steps[\"columntransformer\"].transform(X_now), n_neighbors=10)\n",
    "now[\"closest_10_left\"] = y_past.values[closest].sum(axis=1)\n",
    "now[\"reason\"] = now[\"closest_10_left\"].astype(str) + \" of its 10 closest past customers left\"\n",
    "\n",
    "call_list = now.sort_values(\"risk\", ascending=False, kind=\"stable\").head(50)\n",
    "call_list[[\"customer_id\"]].to_csv(\"churn_call_list.csv\", index=False)\n",
    "\n",
    "call_list[[\"customer_id\", \"plan\", \"seats_used_pct\", \"logins_per_week\",\n",
    "           \"support_tickets_90d\", \"risk\", \"reason\"]].head(10)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "db0378ef",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:48:44.319674Z",
     "iopub.status.busy": "2026-12-05T03:48:44.319588Z",
     "iopub.status.idle": "2026-12-05T03:48:44.335984Z",
     "shell.execute_reply": "2026-12-05T03:48:44.335603Z"
    }
   },
   "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_churn_rate</th>\n",
       "      <th>auc</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>Lowest seat use first</th>\n",
       "      <td>0.692</td>\n",
       "      <td>0.720</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Fewest logins first</th>\n",
       "      <td>0.492</td>\n",
       "      <td>0.691</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Most support tickets first</th>\n",
       "      <td>0.583</td>\n",
       "      <td>0.654</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>KNN churn risk</th>\n",
       "      <td>0.758</td>\n",
       "      <td>0.774</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Logistic regression</th>\n",
       "      <td>0.742</td>\n",
       "      <td>0.784</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                            top_10pct_churn_rate    auc\n",
       "Lowest seat use first                      0.692  0.720\n",
       "Fewest logins first                        0.492  0.691\n",
       "Most support tickets first                 0.583  0.654\n",
       "KNN churn risk                             0.758  0.774\n",
       "Logistic regression                        0.742  0.784"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "logit = make_pipeline(prep, LogisticRegression(max_iter=1000)).fit(X_past, y_past)\n",
    "\n",
    "def top_decile_rate(score):\n",
    "    order = pd.DataFrame({\"score\": score, \"churned\": y_now.values})\n",
    "    order = order.sort_values(\"score\", ascending=False, kind=\"stable\")\n",
    "    return order[\"churned\"].head(len(order) // 10).mean()\n",
    "\n",
    "rankings = {\n",
    "    \"Lowest seat use first\": -X_now[\"seats_used_pct\"],\n",
    "    \"Fewest logins first\": -X_now[\"logins_per_week\"],\n",
    "    \"Most support tickets first\": X_now[\"support_tickets_90d\"],\n",
    "    \"KNN churn risk\": risk,\n",
    "    \"Logistic regression\": logit.predict_proba(X_now)[:, 1],\n",
    "}\n",
    "pd.DataFrame({\n",
    "    \"top_10pct_churn_rate\": {n: round(top_decile_rate(s), 3) for n, s in rankings.items()},\n",
    "    \"auc\": {n: round(roc_auc_score(y_now, s), 3) for n, s in rankings.items()},\n",
    "})"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6e77528a",
   "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_churn_charts.json`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "6df277dc",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:48:44.337166Z",
     "iopub.status.busy": "2026-12-05T03:48:44.337088Z",
     "iopub.status.idle": "2026-12-05T03:48:45.293506Z",
     "shell.execute_reply": "2026-12-05T03:48:45.293098Z"
    }
   },
   "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>scaled</th>\n",
       "      <th>raw</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>1</td>\n",
       "      <td>0.594</td>\n",
       "      <td>0.575</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>5</td>\n",
       "      <td>0.686</td>\n",
       "      <td>0.633</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>10</td>\n",
       "      <td>0.710</td>\n",
       "      <td>0.652</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>20</td>\n",
       "      <td>0.735</td>\n",
       "      <td>0.671</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>40</td>\n",
       "      <td>0.738</td>\n",
       "      <td>0.681</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>80</td>\n",
       "      <td>0.741</td>\n",
       "      <td>0.682</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>120</td>\n",
       "      <td>0.743</td>\n",
       "      <td>0.681</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>160</td>\n",
       "      <td>0.746</td>\n",
       "      <td>0.675</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8</th>\n",
       "      <td>240</td>\n",
       "      <td>0.753</td>\n",
       "      <td>0.658</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>9</th>\n",
       "      <td>320</td>\n",
       "      <td>0.752</td>\n",
       "      <td>0.656</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>10</th>\n",
       "      <td>480</td>\n",
       "      <td>0.757</td>\n",
       "      <td>0.645</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>11</th>\n",
       "      <td>640</td>\n",
       "      <td>0.757</td>\n",
       "      <td>0.632</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "      k  scaled    raw\n",
       "0     1   0.594  0.575\n",
       "1     5   0.686  0.633\n",
       "2    10   0.710  0.652\n",
       "3    20   0.735  0.671\n",
       "4    40   0.738  0.681\n",
       "5    80   0.741  0.682\n",
       "6   120   0.743  0.681\n",
       "7   160   0.746  0.675\n",
       "8   240   0.753  0.658\n",
       "9   320   0.752  0.656\n",
       "10  480   0.757  0.645\n",
       "11  640   0.757  0.632"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import json\n",
    "from sklearn.base import clone\n",
    "\n",
    "# Test-set risk scores and outcomes, for the cut-off chart\n",
    "charts = {\"base_rate\": round(float(y_now.mean()), 4), \"best_k\": int(best_k),\n",
    "          \"test_auc\": round(float(roc_auc_score(y_now, risk)), 3),\n",
    "          \"scores\": [round(float(s), 4) for s in risk],\n",
    "          \"labels\": [int(v) for v in y_now]}\n",
    "\n",
    "# The k curve, with and without scaling\n",
    "k_curve = []\n",
    "for k, auc in results:\n",
    "    raw = make_pipeline(make_column_transformer((\"passthrough\", numeric),\n",
    "                                                (OneHotEncoder(handle_unknown=\"ignore\"), categorical)),\n",
    "                        KNeighborsClassifier(n_neighbors=k))\n",
    "    auc_raw = cross_val_score(raw, X_past, y_past, cv=folds, scoring=\"roc_auc\").mean()\n",
    "    k_curve.append({\"k\": k, \"scaled\": auc, \"raw\": round(float(auc_raw), 3)})\n",
    "charts[\"k_curve\"] = k_curve\n",
    "pd.DataFrame(k_curve)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "278b9280",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:48:45.294659Z",
     "iopub.status.busy": "2026-12-05T03:48:45.294593Z",
     "iopub.status.idle": "2026-12-05T03:48:45.302178Z",
     "shell.execute_reply": "2026-12-05T03:48:45.301773Z"
    }
   },
   "outputs": [],
   "source": [
    "# The comparison table, for the comparison chart\n",
    "charts[\"compare\"] = [{\"name\": n, \"top\": round(float(top_decile_rate(s)), 3),\n",
    "                      \"auc\": round(float(roc_auc_score(y_now, s)), 3)} for n, s in rankings.items()]\n",
    "charts[\"deciles\"] = [{\"decile\": int(d), \"rate\": round(float(r.rate), 3), \"churned\": int(r.churned),\n",
    "                      \"customers\": int(r.customers)} for d, r in by_decile.iterrows()]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "66264d6e",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:48:45.303617Z",
     "iopub.status.busy": "2026-12-05T03:48:45.303534Z",
     "iopub.status.idle": "2026-12-05T03:48:45.313913Z",
     "shell.execute_reply": "2026-12-05T03:48:45.313438Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "282 of 480 neighbours of the top customer churned; 8 of its 10 closest\n"
     ]
    }
   ],
   "source": [
    "# The call list: the top 10 customers, each with all of its voting neighbours, nearest first\n",
    "dist_all, idx_all = steps[\"kneighborsclassifier\"].kneighbors(\n",
    "    steps[\"columntransformer\"].transform(X_now.loc[call_list.head(10).index]))\n",
    "rows = []\n",
    "for (_, c), d, ix in zip(call_list.head(10).iterrows(), dist_all, idx_all):\n",
    "    nb = customers.loc[X_past.index[ix]]\n",
    "    rows.append({\"id\": c.customer_id, \"plan\": c.plan, \"seats\": float(c.seats_used_pct),\n",
    "                 \"logins\": float(c.logins_per_week), \"tickets\": int(c.support_tickets_90d),\n",
    "                 \"tenure\": int(c.tenure_months), \"onb\": int(c.onboarding_completed),\n",
    "                 \"risk\": round(float(c.risk), 4), \"churned\": int(c.churned_next_90d),\n",
    "                 \"left\": int(round(float(c.risk) * best_k)),\n",
    "                 \"nb\": [{\"id\": r.customer_id, \"d\": round(float(dd), 2), \"y\": int(r.churned_next_90d),\n",
    "                         \"seats\": float(r.seats_used_pct), \"logins\": float(r.logins_per_week),\n",
    "                         \"plan\": r.plan} for dd, r in zip(d[:40], nb.head(40).itertuples())]})\n",
    "charts[\"call_list\"] = rows\n",
    "print(rows[0][\"left\"], \"of\", best_k, \"neighbours of the top customer churned;\",\n",
    "      sum(n[\"y\"] for n in rows[0][\"nb\"][:10]), \"of its 10 closest\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "ae099b19",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:48:45.314972Z",
     "iopub.status.busy": "2026-12-05T03:48:45.314903Z",
     "iopub.status.idle": "2026-12-05T03:48:45.319012Z",
     "shell.execute_reply": "2026-12-05T03:48:45.318693Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "sample churn rate: 0.250\n"
     ]
    }
   ],
   "source": [
    "# Playground: past customers on the two columns that matter most, seat use and logins\n",
    "sc = StandardScaler().fit(X_past[[\"seats_used_pct\", \"logins_per_week\"]])\n",
    "sample = customers.loc[X_past.index].sample(400, random_state=7)\n",
    "charts[\"points\"] = [{\"s\": float(r.seats_used_pct), \"l\": float(r.logins_per_week),\n",
    "                     \"c\": int(r.churned_next_90d), \"id\": r.customer_id}\n",
    "                    for r in sample.itertuples()]\n",
    "charts[\"scale\"] = {\"seats_sd\": round(float(sc.scale_[0]), 4), \"logins_sd\": round(float(sc.scale_[1]), 4)}\n",
    "print(f\"sample churn rate: {sample['churned_next_90d'].mean():.3f}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "998e087d",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:48:45.320277Z",
     "iopub.status.busy": "2026-12-05T03:48:45.320206Z",
     "iopub.status.idle": "2026-12-05T03:48:45.326450Z",
     "shell.execute_reply": "2026-12-05T03:48:45.325844Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "                         min  median      max\n",
      "employees               5.00  177.00  5000.00\n",
      "signup_discount_pct     0.00    0.00    25.00\n",
      "tenure_months           2.00   20.00    36.00\n",
      "onboarding_completed    0.00    1.00     1.00\n",
      "integrations_connected  0.00    2.00     9.00\n",
      "seats_used_pct          0.03    0.61     0.99\n",
      "logins_per_week         0.00    4.10    38.60\n",
      "support_tickets_90d     0.00    1.00    12.00\n",
      "plan\n",
      "Growth        3066\n",
      "Enterprise     573\n",
      "Starter        361\n",
      "Name: count, dtype: int64\n",
      "call the top 60: 48 of 308 churners (16%); a random 60 would hold 15\n",
      "call the top 120: 91 of 308 churners (30%); a random 120 would hold 31\n",
      "call the top 240: 143 of 308 churners (46%); a random 240 would hold 62\n",
      "call the top 360: 183 of 308 churners (59%); a random 360 would hold 92\n",
      "mean risk score in the top decile: 0.454\n"
     ]
    }
   ],
   "source": [
    "# Figures quoted in the guide: column ranges, and churners found at each call-list size\n",
    "print(customers[numeric].agg([\"min\", \"median\", \"max\"]).T)\n",
    "print(customers[\"plan\"].value_counts())\n",
    "found = ranked[\"churned\"].cumsum()\n",
    "for share in [0.05, 0.1, 0.2, 0.3]:\n",
    "    n = int(len(ranked) * share)\n",
    "    print(f\"call the top {n:,}: {found.iloc[n - 1]} of {ranked['churned'].sum()} churners \"\n",
    "          f\"({found.iloc[n - 1] / ranked['churned'].sum():.0%}); a random {n:,} would hold \"\n",
    "          f\"{n * ranked['churned'].mean():.0f}\")\n",
    "print(f\"mean risk score in the top decile: {ranked['risk'].head(120).mean():.3f}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "f0b3ba44",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:48:45.327538Z",
     "iopub.status.busy": "2026-12-05T03:48:45.327444Z",
     "iopub.status.idle": "2026-12-05T03:48:45.363837Z",
     "shell.execute_reply": "2026-12-05T03:48:45.363456Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Lowest seat use first: cut at 0.33, 116 above it, 13 tied at it; top 10% churn rate over 200 random tie orders: mean 0.681, range 0.667 to 0.692\n",
      "Fewest logins first: cut at 1.3, 107 above it, 14 tied at it; top 10% churn rate over 200 random tie orders: mean 0.496, range 0.492 to 0.500\n",
      "Most support tickets first: cut at 4, 57 above it, 66 tied at it; top 10% churn rate over 200 random tie orders: mean 0.596, range 0.583 to 0.608\n"
     ]
    }
   ],
   "source": [
    "# Single-column rules have many ties: where the top-10% cut falls, and how much tie order matters\n",
    "n_top = len(X_now) // 10\n",
    "shuffle = np.random.default_rng(0)\n",
    "for name in [\"Lowest seat use first\", \"Fewest logins first\", \"Most support tickets first\"]:\n",
    "    s = np.asarray(rankings[name])\n",
    "    cut = np.sort(s)[::-1][n_top - 1]\n",
    "    rates = []\n",
    "    for _ in range(200):                      # shuffle the rows, so tied customers fall in a random order\n",
    "        p = shuffle.permutation(len(s))\n",
    "        top = p[np.argsort(-s[p], kind=\"stable\")[:n_top]]\n",
    "        rates.append(y_now.values[top].mean())\n",
    "    print(f\"{name}: cut at {abs(cut):g}, {(s > cut).sum()} above it, {(s == cut).sum()} tied at it; \"\n",
    "          f\"top 10% churn rate over 200 random tie orders: mean {np.mean(rates):.3f}, \"\n",
    "          f\"range {min(rates):.3f} to {max(rates):.3f}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "7025d347",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:48:45.364943Z",
     "iopub.status.busy": "2026-12-05T03:48:45.364872Z",
     "iopub.status.idle": "2026-12-05T03:48:45.735080Z",
     "shell.execute_reply": "2026-12-05T03:48:45.734501Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "with industry, region and channel: 0.756   without: 0.757\n"
     ]
    }
   ],
   "source": [
    "# Do the columns we left out help? Add industry, region and first channel back in\n",
    "wide = customers[numeric + categorical + [\"industry\", \"region\", \"first_channel\"]].copy()\n",
    "wide[\"employees\"] = np.log10(wide[\"employees\"])\n",
    "wide_model = make_pipeline(\n",
    "    make_column_transformer((StandardScaler(), numeric),\n",
    "                            (OneHotEncoder(handle_unknown=\"ignore\"),\n",
    "                             categorical + [\"industry\", \"region\", \"first_channel\"])),\n",
    "    KNeighborsClassifier(n_neighbors=best_k))\n",
    "with_extra = cross_val_score(wide_model, wide.loc[X_past.index], y_past, cv=folds, scoring=\"roc_auc\").mean()\n",
    "without = cross_val_score(knn, X_past, y_past, cv=folds, scoring=\"roc_auc\").mean()\n",
    "print(f\"with industry, region and channel: {with_extra:.3f}   without: {without:.3f}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "e5545ae3",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:48:45.736735Z",
     "iopub.status.busy": "2026-12-05T03:48:45.736615Z",
     "iopub.status.idle": "2026-12-05T03:48:45.742625Z",
     "shell.execute_reply": "2026-12-05T03:48:45.742122Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "saved 11 chart datasets\n"
     ]
    }
   ],
   "source": [
    "with open(\"knn_churn_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
}
