{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "4fe69b83",
   "metadata": {},
   "source": [
    "# KNN for marketing: recommend the next add-on\n",
    "\n",
    "Companion notebook to the guide at https://martinguzman.ca/blog/knn-product-recommendations\n",
    "\n",
    "Put `northpine_addons.csv` and `northpine_customers.csv` in the same folder as this notebook (download them from https://martinguzman.ca/guides/ml/). Northpine Software is a made-up company; the data is synthetic."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "347fec8e",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:52:00.948032Z",
     "iopub.status.busy": "2026-12-05T03:52:00.947970Z",
     "iopub.status.idle": "2026-12-05T03:52:01.125697Z",
     "shell.execute_reply": "2026-12-05T03:52:01.125290Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(4000, 16)\n",
      "['crm_sync', 'accounting_sync', 'ecommerce_connector', 'payments', 'help_desk', 'team_chat', 'single_sign_on', 'audit_log', 'advanced_reporting', 'api_access', 'warehouse_export', 'e_signature']\n",
      "customer_id  crm_sync  accounting_sync  ecommerce_connector  payments  help_desk  team_chat  single_sign_on  audit_log  advanced_reporting  api_access  warehouse_export  e_signature\n",
      "   NC-00001         1                0                    0         0          0          0               0          0                   1           0                 0            1\n",
      "   NC-00002         0                0                    0         1          0          0               1          0                   1           1                 0            0\n",
      "   NC-00003         1                0                    0         0          0          1               1          0                   0           0                 0            1\n",
      "   NC-00004         0                1                    0         1          0          0               0          0                   0           0                 0            0\n",
      "   NC-00005         0                0                    0         0          1          1               0          0                   0           0                 0            0\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "pd.set_option(\"display.max_colwidth\", None)\n",
    "pd.set_option(\"display.width\", 200)\n",
    "\n",
    "addons = pd.read_csv(\"northpine_addons.csv\")\n",
    "customers = pd.read_csv(\"northpine_customers.csv\")[[\"customer_id\", \"industry\", \"plan\", \"employees\"]]\n",
    "data = customers.merge(addons, on=\"customer_id\")\n",
    "\n",
    "ADDONS = list(addons.columns[1:])\n",
    "print(data.shape)\n",
    "print(ADDONS)\n",
    "print(addons.head().to_string(index=False))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "170fd525",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:52:01.126895Z",
     "iopub.status.busy": "2026-12-05T03:52:01.126799Z",
     "iopub.status.idle": "2026-12-05T03:52:01.130633Z",
     "shell.execute_reply": "2026-12-05T03:52:01.130292Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "add-ons per customer: mean 2.61\n",
      "0      81\n",
      "1     497\n",
      "2    1312\n",
      "3    1354\n",
      "4     554\n",
      "5     177\n",
      "6      24\n",
      "7       1\n",
      "\n",
      "crm_sync               0.327\n",
      "e_signature            0.295\n",
      "advanced_reporting     0.272\n",
      "team_chat              0.267\n",
      "payments               0.265\n",
      "accounting_sync        0.250\n",
      "help_desk              0.226\n",
      "api_access             0.204\n",
      "warehouse_export       0.194\n",
      "ecommerce_connector    0.117\n",
      "audit_log              0.112\n",
      "single_sign_on         0.080\n"
     ]
    }
   ],
   "source": [
    "owned = data[ADDONS].sum(axis=1)\n",
    "print(f\"add-ons per customer: mean {owned.mean():.2f}\")\n",
    "print(owned.value_counts().sort_index().to_string())\n",
    "print()\n",
    "print(data[ADDONS].mean().sort_values(ascending=False, kind=\"stable\").round(3).to_string())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "09185ab6",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:52:01.131796Z",
     "iopub.status.busy": "2026-12-05T03:52:01.131719Z",
     "iopub.status.idle": "2026-12-05T03:52:01.204999Z",
     "shell.execute_reply": "2026-12-05T03:52:01.204609Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "4,000 x 4,000 similarities\n",
      "customer_id  crm_sync  accounting_sync  ecommerce_connector  payments  help_desk  team_chat  single_sign_on  audit_log  advanced_reporting  api_access  warehouse_export  e_signature\n",
      "   NC-00001         1                0                    0         0          0          0               0          0                   1           0                 0            1\n",
      "   NC-00002         0                0                    0         1          0          0               1          0                   1           1                 0            0\n",
      "similarity of these two: 0.167\n"
     ]
    }
   ],
   "source": [
    "M = data[ADDONS].to_numpy()          # one row per customer, one column per add-on, 1 = uses it\n",
    "\n",
    "def jaccard(A):\n",
    "    \"\"\"Similarity of every row with every other row: shared add-ons / add-ons either one uses.\"\"\"\n",
    "    A = A.astype(float)\n",
    "    shared = A @ A.T\n",
    "    size = A.sum(axis=1)\n",
    "    either = size[:, None] + size[None, :] - shared\n",
    "    return np.divide(shared, either, out=np.zeros_like(shared), where=either > 0)\n",
    "\n",
    "S_full = jaccard(M)\n",
    "print(f\"{S_full.shape[0]:,} x {S_full.shape[1]:,} similarities\")\n",
    "print(data.loc[[0, 1], [\"customer_id\"] + ADDONS].to_string(index=False))\n",
    "print(f\"similarity of these two: {S_full[0, 1]:.3f}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "be30d32f",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:52:01.206326Z",
     "iopub.status.busy": "2026-12-05T03:52:01.206218Z",
     "iopub.status.idle": "2026-12-05T03:52:01.224054Z",
     "shell.execute_reply": "2026-12-05T03:52:01.223647Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "customers with 2+ add-ons: 3,422\n",
      "tuning: 1,711   test: 1,711\n"
     ]
    }
   ],
   "source": [
    "rng = np.random.default_rng(42)\n",
    "eligible = np.where(M.sum(axis=1) >= 2)[0]\n",
    "\n",
    "H = M.copy()                 # what the model is allowed to see\n",
    "hidden = {}                  # customer row -> the add-on we hid\n",
    "for u in eligible:\n",
    "    j = rng.choice(np.where(M[u] == 1)[0])\n",
    "    H[u, j] = 0\n",
    "    hidden[u] = j\n",
    "\n",
    "order = rng.permutation(eligible)\n",
    "tune, test = np.sort(order[: len(order) // 2]), np.sort(order[len(order) // 2:])\n",
    "print(f\"customers with 2+ add-ons: {len(eligible):,}\")\n",
    "print(f\"tuning: {len(tune):,}   test: {len(test):,}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "318369bc",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:52:01.225337Z",
     "iopub.status.busy": "2026-12-05T03:52:01.225245Z",
     "iopub.status.idle": "2026-12-05T03:52:01.234855Z",
     "shell.execute_reply": "2026-12-05T03:52:01.234466Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "most popular, top 3: 0.441\n"
     ]
    }
   ],
   "source": [
    "def hit_rate(recommend, rows, n=3):\n",
    "    \"\"\"Share of customers whose hidden add-on is among the n recommendations.\"\"\"\n",
    "    return np.mean([hidden[u] in recommend(u)[:n] for u in rows])\n",
    "\n",
    "popularity = H.mean(axis=0)\n",
    "\n",
    "def rank(score):\n",
    "    \"\"\"Add-ons from highest score to lowest. Ties go to the more popular add-on.\"\"\"\n",
    "    return np.lexsort((-popularity, -score))\n",
    "\n",
    "def most_popular(u):\n",
    "    score = popularity.copy()\n",
    "    score[H[u] == 1] = -1                      # never recommend what they already use\n",
    "    return rank(score)\n",
    "\n",
    "print(f\"most popular, top 3: {hit_rate(most_popular, test):.3f}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "e17b0a52",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:52:01.235971Z",
     "iopub.status.busy": "2026-12-05T03:52:01.235899Z",
     "iopub.status.idle": "2026-12-05T03:52:01.735681Z",
     "shell.execute_reply": "2026-12-05T03:52:01.735247Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tuning half, most popular:      0.440\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tuning half, plain KNN, k =  5: 0.453\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tuning half, plain KNN, k = 10: 0.466\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tuning half, plain KNN, k = 20: 0.491\n"
     ]
    }
   ],
   "source": [
    "S = jaccard(H)\n",
    "np.fill_diagonal(S, -1)                        # a customer is not its own neighbour\n",
    "\n",
    "def knn_naive(u, k):\n",
    "    neighbours = np.argsort(-S[u], kind=\"stable\")[:k]\n",
    "    score = H[neighbours].mean(axis=0)         # share of neighbours using each add-on\n",
    "    score[H[u] == 1] = -1\n",
    "    return rank(score)\n",
    "\n",
    "print(f\"tuning half, most popular:      {hit_rate(most_popular, tune):.3f}\")\n",
    "for k in [5, 10, 20]:\n",
    "    print(f\"tuning half, plain KNN, k = {k:>2}: {hit_rate(lambda u: knn_naive(u, k), tune):.3f}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "77e88dbf",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:52:01.736748Z",
     "iopub.status.busy": "2026-12-05T03:52:01.736676Z",
     "iopub.status.idle": "2026-12-05T03:52:02.162519Z",
     "shell.execute_reply": "2026-12-05T03:52:02.161961Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "k =  5: 95.3% of neighbours have nothing to recommend\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "k = 10: 94.6% of neighbours have nothing to recommend\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "k = 20: 93.6% of neighbours have nothing to recommend\n"
     ]
    }
   ],
   "source": [
    "def nothing_new(u, k):\n",
    "    \"\"\"Share of the k nearest customers who use nothing that customer u lacks.\"\"\"\n",
    "    neighbours = np.argsort(-S[u], kind=\"stable\")[:k]\n",
    "    new = H[neighbours][:, H[u] == 0].sum(axis=1)\n",
    "    return np.mean(new == 0)\n",
    "\n",
    "for k in [5, 10, 20]:\n",
    "    print(f\"k = {k:>2}: {np.mean([nothing_new(u, k) for u in tune]):.1%} of neighbours have nothing to recommend\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "be18377b",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:52:02.163578Z",
     "iopub.status.busy": "2026-12-05T03:52:02.163504Z",
     "iopub.status.idle": "2026-12-05T03:52:06.074183Z",
     "shell.execute_reply": "2026-12-05T03:52:06.073684Z"
    }
   },
   "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>plain</th>\n",
       "      <th>fixed</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>5</td>\n",
       "      <td>0.453</td>\n",
       "      <td>0.755</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>10</td>\n",
       "      <td>0.466</td>\n",
       "      <td>0.784</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>20</td>\n",
       "      <td>0.491</td>\n",
       "      <td>0.821</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>40</td>\n",
       "      <td>0.520</td>\n",
       "      <td>0.839</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>80</td>\n",
       "      <td>0.600</td>\n",
       "      <td>0.841</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>160</td>\n",
       "      <td>0.728</td>\n",
       "      <td>0.846</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>240</td>\n",
       "      <td>0.830</td>\n",
       "      <td>0.846</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>320</td>\n",
       "      <td>0.839</td>\n",
       "      <td>0.842</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8</th>\n",
       "      <td>480</td>\n",
       "      <td>0.850</td>\n",
       "      <td>0.846</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>9</th>\n",
       "      <td>640</td>\n",
       "      <td>0.840</td>\n",
       "      <td>0.808</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "     k  plain  fixed\n",
       "0    5  0.453  0.755\n",
       "1   10  0.466  0.784\n",
       "2   20  0.491  0.821\n",
       "3   40  0.520  0.839\n",
       "4   80  0.600  0.841\n",
       "5  160  0.728  0.846\n",
       "6  240  0.830  0.846\n",
       "7  320  0.839  0.842\n",
       "8  480  0.850  0.846\n",
       "9  640  0.840  0.808"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def knn(u, k):\n",
    "    lacks = H[u] == 0\n",
    "    has_something_new = H[:, lacks].sum(axis=1) > 0\n",
    "    sim = np.where(has_something_new, S[u], -1)   # only neighbours with something to offer\n",
    "    neighbours = np.argsort(-sim, kind=\"stable\")[:k]\n",
    "    score = H[neighbours].mean(axis=0)\n",
    "    score[H[u] == 1] = -1\n",
    "    return rank(score)\n",
    "\n",
    "results = []\n",
    "for k in [5, 10, 20, 40, 80, 160, 240, 320, 480, 640]:\n",
    "    results.append((k, round(hit_rate(lambda u: knn_naive(u, k), tune), 3),\n",
    "                       round(hit_rate(lambda u: knn(u, k), tune), 3)))\n",
    "pd.DataFrame(results, columns=[\"k\", \"plain\", \"fixed\"])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "85ab8656",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:52:06.075317Z",
     "iopub.status.busy": "2026-12-05T03:52:06.075231Z",
     "iopub.status.idle": "2026-12-05T03:52:06.476513Z",
     "shell.execute_reply": "2026-12-05T03:52:06.476055Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "plain KNN, k = 480: test hit rate, top 3: 0.852\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "fixed KNN, k = 160: test hit rate, top 3: 0.853\n"
     ]
    }
   ],
   "source": [
    "best_k_naive = max(results, key=lambda r: r[1])[0]\n",
    "best_k = max(results, key=lambda r: r[2])[0]\n",
    "print(f\"plain KNN, k = {best_k_naive}: test hit rate, top 3: {hit_rate(lambda u: knn_naive(u, best_k_naive), test):.3f}\")\n",
    "print(f\"fixed KNN, k = {best_k}: test hit rate, top 3: {hit_rate(lambda u: knn(u, best_k), test):.3f}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "b79efab7",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:52:06.477628Z",
     "iopub.status.busy": "2026-12-05T03:52:06.477547Z",
     "iopub.status.idle": "2026-12-05T03:52:06.489377Z",
     "shell.execute_reply": "2026-12-05T03:52:06.488950Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "item-based KNN, top 3: 0.856\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "accounting_sync        0.178\n",
       "ecommerce_connector    0.125\n",
       "audit_log              0.123\n",
       "e_signature            0.092\n",
       "Name: payments, dtype: float64"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "I = jaccard(H.T)                    # add-on x add-on: how often two add-ons go together\n",
    "np.fill_diagonal(I, 0)\n",
    "\n",
    "def knn_items(u):\n",
    "    score = I[:, H[u] == 1].sum(axis=1)       # how close each add-on is to the ones they use\n",
    "    score[H[u] == 1] = -1\n",
    "    return rank(score)\n",
    "\n",
    "print(f\"item-based KNN, top 3: {hit_rate(knn_items, test):.3f}\")\n",
    "pairs = pd.DataFrame(I, index=ADDONS, columns=ADDONS)\n",
    "pairs[\"payments\"].sort_values(ascending=False, kind=\"stable\").head(4).round(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "c887aea8",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:52:06.490360Z",
     "iopub.status.busy": "2026-12-05T03:52:06.490278Z",
     "iopub.status.idle": "2026-12-05T03:52:06.493333Z",
     "shell.execute_reply": "2026-12-05T03:52:06.492937Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "NC-00002 | Software | Growth | 2706 employees\n",
      "uses:   ['payments', 'single_sign_on', 'advanced_reporting']\n",
      "hidden: api_access\n",
      "\n",
      "of its 160 nearest customers, how many use each add-on it lacks:\n",
      "api_access          48\n",
      "warehouse_export    39\n",
      "accounting_sync     23\n",
      "e_signature         23\n",
      "crm_sync            22\n"
     ]
    }
   ],
   "source": [
    "u = test[0]\n",
    "row = data.iloc[u]\n",
    "print(row.customer_id, \"|\", row.industry, \"|\", row.plan, \"|\", row.employees, \"employees\")\n",
    "print(\"uses:  \", [a for a, v in zip(ADDONS, H[u]) if v])\n",
    "print(\"hidden:\", ADDONS[hidden[u]])\n",
    "\n",
    "lacks = H[u] == 0\n",
    "sim = np.where(H[:, lacks].sum(axis=1) > 0, S[u], -1)\n",
    "neighbours = np.argsort(-sim, kind=\"stable\")[:best_k]\n",
    "votes = pd.Series(H[neighbours].sum(axis=0), index=ADDONS)[lacks]\n",
    "print(f\"\\nof its {best_k} nearest customers, how many use each add-on it lacks:\")\n",
    "print(votes.sort_values(ascending=False, kind=\"stable\").head(5).to_string())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "5a8662a7",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:52:06.494183Z",
     "iopub.status.busy": "2026-12-05T03:52:06.494124Z",
     "iopub.status.idle": "2026-12-05T03:52:07.112698Z",
     "shell.execute_reply": "2026-12-05T03:52:07.112187Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "logistic regression, top 3: 0.842\n"
     ]
    }
   ],
   "source": [
    "from sklearn.linear_model import LogisticRegression\n",
    "\n",
    "P = np.zeros(H.shape)            # P[u, j]: the chance customer u uses add-on j, given the others it uses\n",
    "for j in range(len(ADDONS)):\n",
    "    others = np.delete(H, j, axis=1)\n",
    "    P[:, j] = LogisticRegression(max_iter=1000).fit(others, H[:, j]).predict_proba(others)[:, 1]\n",
    "\n",
    "def logistic(u):\n",
    "    score = P[u].copy()\n",
    "    score[H[u] == 1] = -1\n",
    "    return rank(score)\n",
    "\n",
    "print(f\"logistic regression, top 3: {hit_rate(logistic, test):.3f}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "e9fe2e1b",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:52:07.113937Z",
     "iopub.status.busy": "2026-12-05T03:52:07.113820Z",
     "iopub.status.idle": "2026-12-05T03:52:08.394596Z",
     "shell.execute_reply": "2026-12-05T03:52:08.394256Z"
    }
   },
   "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_1</th>\n",
       "      <th>top_3</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>Most popular overall</th>\n",
       "      <td>0.197</td>\n",
       "      <td>0.441</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Most popular in their industry and plan</th>\n",
       "      <td>0.308</td>\n",
       "      <td>0.535</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Plain KNN (k = 10)</th>\n",
       "      <td>0.210</td>\n",
       "      <td>0.468</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Plain KNN, tuned (k = 480)</th>\n",
       "      <td>0.559</td>\n",
       "      <td>0.852</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>KNN, neighbours with something new (k = 160)</th>\n",
       "      <td>0.558</td>\n",
       "      <td>0.853</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Item-based KNN</th>\n",
       "      <td>0.564</td>\n",
       "      <td>0.856</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Logistic regression, one per add-on</th>\n",
       "      <td>0.544</td>\n",
       "      <td>0.842</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                                              top_1  top_3\n",
       "Most popular overall                          0.197  0.441\n",
       "Most popular in their industry and plan       0.308  0.535\n",
       "Plain KNN (k = 10)                            0.210  0.468\n",
       "Plain KNN, tuned (k = 480)                    0.559  0.852\n",
       "KNN, neighbours with something new (k = 160)  0.558  0.853\n",
       "Item-based KNN                                0.564  0.856\n",
       "Logistic regression, one per add-on           0.544  0.842"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "segment = data[\"industry\"] + \" / \" + data[\"plan\"]\n",
    "\n",
    "def segment_popular(u):\n",
    "    peers = segment.to_numpy() == segment[u]\n",
    "    peers[u] = False\n",
    "    score = H[peers].mean(axis=0)\n",
    "    score[H[u] == 1] = -1\n",
    "    return rank(score)\n",
    "\n",
    "methods = {\n",
    "    \"Most popular overall\": most_popular,\n",
    "    \"Most popular in their industry and plan\": segment_popular,\n",
    "    \"Plain KNN (k = 10)\": lambda u: knn_naive(u, 10),\n",
    "    f\"Plain KNN, tuned (k = {best_k_naive})\": lambda u: knn_naive(u, best_k_naive),\n",
    "    f\"KNN, neighbours with something new (k = {best_k})\": lambda u: knn(u, best_k),\n",
    "    \"Item-based KNN\": knn_items,\n",
    "    \"Logistic regression, one per add-on\": logistic,\n",
    "}\n",
    "pd.DataFrame({f\"top_{n}\": {name: round(hit_rate(f, test, n), 3) for name, f in methods.items()}\n",
    "              for n in [1, 3]})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "57e61f19",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:52:08.395833Z",
     "iopub.status.busy": "2026-12-05T03:52:08.395754Z",
     "iopub.status.idle": "2026-12-05T03:52:09.040569Z",
     "shell.execute_reply": "2026-12-05T03:52:09.040169Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "next_best\n",
      "e_signature            743\n",
      "crm_sync               598\n",
      "advanced_reporting     574\n",
      "team_chat              374\n",
      "help_desk              360\n",
      "payments               322\n",
      "single_sign_on         255\n",
      "accounting_sync        238\n",
      "audit_log              174\n",
      "warehouse_export       152\n",
      "api_access             129\n",
      "ecommerce_connector     81\n",
      "most-popular rule: crm_sync first for 2,693 customers\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>plan</th>\n",
       "      <th>uses</th>\n",
       "      <th>next_best</th>\n",
       "      <th>lookalikes_using</th>\n",
       "      <th>share_of_lookalikes</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>320</th>\n",
       "      <td>NC-00321</td>\n",
       "      <td>Software</td>\n",
       "      <td>Growth</td>\n",
       "      <td>team_chat, advanced_reporting, e_signature</td>\n",
       "      <td>crm_sync</td>\n",
       "      <td>152</td>\n",
       "      <td>0.950</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3031</th>\n",
       "      <td>NC-03032</td>\n",
       "      <td>Professional services</td>\n",
       "      <td>Growth</td>\n",
       "      <td>ecommerce_connector, team_chat, advanced_reporting, e_signature</td>\n",
       "      <td>crm_sync</td>\n",
       "      <td>152</td>\n",
       "      <td>0.950</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2265</th>\n",
       "      <td>NC-02266</td>\n",
       "      <td>Software</td>\n",
       "      <td>Growth</td>\n",
       "      <td>help_desk, team_chat, advanced_reporting, e_signature</td>\n",
       "      <td>crm_sync</td>\n",
       "      <td>151</td>\n",
       "      <td>0.944</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>186</th>\n",
       "      <td>NC-00187</td>\n",
       "      <td>Software</td>\n",
       "      <td>Growth</td>\n",
       "      <td>single_sign_on, advanced_reporting, api_access</td>\n",
       "      <td>warehouse_export</td>\n",
       "      <td>149</td>\n",
       "      <td>0.931</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>520</th>\n",
       "      <td>NC-00521</td>\n",
       "      <td>Software</td>\n",
       "      <td>Enterprise</td>\n",
       "      <td>single_sign_on, advanced_reporting, warehouse_export</td>\n",
       "      <td>api_access</td>\n",
       "      <td>149</td>\n",
       "      <td>0.931</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>862</th>\n",
       "      <td>NC-00863</td>\n",
       "      <td>Software</td>\n",
       "      <td>Growth</td>\n",
       "      <td>team_chat, audit_log, advanced_reporting, e_signature</td>\n",
       "      <td>crm_sync</td>\n",
       "      <td>148</td>\n",
       "      <td>0.925</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1493</th>\n",
       "      <td>NC-01494</td>\n",
       "      <td>Education</td>\n",
       "      <td>Growth</td>\n",
       "      <td>single_sign_on, warehouse_export</td>\n",
       "      <td>api_access</td>\n",
       "      <td>146</td>\n",
       "      <td>0.912</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3376</th>\n",
       "      <td>NC-03377</td>\n",
       "      <td>Software</td>\n",
       "      <td>Growth</td>\n",
       "      <td>help_desk, single_sign_on, advanced_reporting, api_access</td>\n",
       "      <td>warehouse_export</td>\n",
       "      <td>145</td>\n",
       "      <td>0.906</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "     customer_id               industry        plan                                                             uses         next_best  lookalikes_using  share_of_lookalikes\n",
       "320     NC-00321               Software      Growth                       team_chat, advanced_reporting, e_signature          crm_sync               152                0.950\n",
       "3031    NC-03032  Professional services      Growth  ecommerce_connector, team_chat, advanced_reporting, e_signature          crm_sync               152                0.950\n",
       "2265    NC-02266               Software      Growth            help_desk, team_chat, advanced_reporting, e_signature          crm_sync               151                0.944\n",
       "186     NC-00187               Software      Growth                   single_sign_on, advanced_reporting, api_access  warehouse_export               149                0.931\n",
       "520     NC-00521               Software  Enterprise             single_sign_on, advanced_reporting, warehouse_export        api_access               149                0.931\n",
       "862     NC-00863               Software      Growth            team_chat, audit_log, advanced_reporting, e_signature          crm_sync               148                0.925\n",
       "1493    NC-01494              Education      Growth                                 single_sign_on, warehouse_export        api_access               146                0.912\n",
       "3376    NC-03377               Software      Growth        help_desk, single_sign_on, advanced_reporting, api_access  warehouse_export               145                0.906"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "S_all = jaccard(M)               # now use everything we know, nothing hidden\n",
    "np.fill_diagonal(S_all, -1)\n",
    "\n",
    "rows = []\n",
    "for u in range(len(data)):\n",
    "    if M[u].sum() == len(ADDONS):\n",
    "        continue\n",
    "    lacks = M[u] == 0\n",
    "    sim = np.where(M[:, lacks].sum(axis=1) > 0, S_all[u], -1)\n",
    "    neighbours = np.argsort(-sim, kind=\"stable\")[:best_k]\n",
    "    using = M[neighbours].sum(axis=0)\n",
    "    using[~lacks] = -1\n",
    "    top = rank(using)[0]\n",
    "    rows.append((data.customer_id[u], data.industry[u], data.plan[u],\n",
    "                 \", \".join(a for a, v in zip(ADDONS, M[u]) if v) or \"none\",\n",
    "                 ADDONS[top], using[top], round(using[top] / best_k, 3)))\n",
    "\n",
    "next_best = pd.DataFrame(rows, columns=[\"customer_id\", \"industry\", \"plan\", \"uses\", \"next_best\",\n",
    "                                        \"lookalikes_using\", \"share_of_lookalikes\"])\n",
    "next_best = next_best.sort_values(\"share_of_lookalikes\", ascending=False, kind=\"stable\")\n",
    "next_best.to_csv(\"next_best_addon.csv\", index=False)\n",
    "print(next_best[\"next_best\"].value_counts().to_string())\n",
    "print(f\"most-popular rule: crm_sync first for {(M[:, ADDONS.index('crm_sync')] == 0).sum():,} customers\")\n",
    "next_best.drop_duplicates(\"uses\").head(8)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7e9ef633",
   "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_recs_charts.json`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "79b5673d",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:52:09.041692Z",
     "iopub.status.busy": "2026-12-05T03:52:09.041628Z",
     "iopub.status.idle": "2026-12-05T03:52:13.684527Z",
     "shell.execute_reply": "2026-12-05T03:52:13.684065Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "                 a                b  similarity\n",
      "        api_access warehouse_export       0.223\n",
      "          crm_sync        team_chat       0.190\n",
      "   accounting_sync         payments       0.178\n",
      "          crm_sync      e_signature       0.160\n",
      "advanced_reporting       api_access       0.154\n",
      "     k  naive  fixed  share\n",
      "0    5  0.453  0.755  0.953\n",
      "1   10  0.466  0.784  0.946\n",
      "2   20  0.491  0.821  0.936\n",
      "3   40  0.520  0.839  0.913\n",
      "4   80  0.600  0.841  0.862\n",
      "5  160  0.728  0.846  0.770\n",
      "6  240  0.830  0.846  0.724\n",
      "7  320  0.839  0.842  0.666\n",
      "8  480  0.850  0.846  0.589\n",
      "9  640  0.840  0.808  0.515\n",
      "                                           name                                 hits\n",
      "0                          Most popular overall  [0.197, 0.299, 0.441, 0.524, 0.665]\n",
      "1       Most popular in their industry and plan  [0.308, 0.445, 0.535, 0.647, 0.751]\n",
      "2                            Plain KNN (k = 10)   [0.21, 0.323, 0.468, 0.545, 0.675]\n",
      "3                    Plain KNN, tuned (k = 480)  [0.559, 0.757, 0.852, 0.905, 0.931]\n",
      "4  KNN, neighbours with something new (k = 160)   [0.558, 0.76, 0.853, 0.905, 0.932]\n",
      "5                                Item-based KNN  [0.564, 0.738, 0.856, 0.902, 0.923]\n",
      "6           Logistic regression, one per add-on  [0.544, 0.745, 0.842, 0.894, 0.921]\n"
     ]
    }
   ],
   "source": [
    "import json\n",
    "\n",
    "charts = {\"addons\": ADDONS, \"best_k\": int(best_k), \"best_k_naive\": int(best_k_naive), \"n_test\": int(len(test))}\n",
    "charts[\"popularity\"] = [round(float(v), 4) for v in M.mean(axis=0)]\n",
    "charts[\"popularity_seen\"] = [round(float(v), 6) for v in popularity]   # tie order in the playground\n",
    "charts[\"owned_counts\"] = {int(k): int(v) for k, v in pd.Series(M.sum(axis=1)).value_counts().sort_index().items()}\n",
    "charts[\"k_curve\"] = [{\"k\": k, \"naive\": n, \"fixed\": f} for k, n, f in results]\n",
    "charts[\"k_curve_baseline\"] = round(float(hit_rate(most_popular, tune)), 3)\n",
    "charts[\"nothing_new\"] = [{\"k\": k, \"share\": round(float(np.mean([nothing_new(u, k) for u in tune])), 3)}\n",
    "                         for k, _, _ in results]\n",
    "charts[\"methods\"] = [{\"name\": name, \"hits\": [round(float(hit_rate(f, test, n)), 3) for n in range(1, 6)]}\n",
    "                     for name, f in methods.items()]\n",
    "charts[\"items\"] = [[round(float(v), 3) for v in r] for r in I]\n",
    "pairs_long = [(ADDONS[a], ADDONS[b], round(float(I[a, b]), 3))\n",
    "              for a in range(len(ADDONS)) for b in range(a + 1, len(ADDONS))]\n",
    "print(pd.DataFrame(pairs_long, columns=[\"a\", \"b\", \"similarity\"])\n",
    "        .sort_values(\"similarity\", ascending=False, kind=\"stable\").head(5).to_string(index=False))\n",
    "print(pd.DataFrame(charts[\"k_curve\"]).merge(pd.DataFrame(charts[\"nothing_new\"]), on=\"k\"))\n",
    "print(pd.DataFrame(charts[\"methods\"]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "f89f9702",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:52:13.685575Z",
     "iopub.status.busy": "2026-12-05T03:52:13.685493Z",
     "iopub.status.idle": "2026-12-05T03:52:14.530829Z",
     "shell.execute_reply": "2026-12-05T03:52:14.530471Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "most popular, tuning half: 0.440\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "plain KNN, k =  5, tuning half: ties by popularity 0.453, ties in column order 0.406\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "plain KNN, k = 10, tuning half: ties by popularity 0.466, ties in column order 0.426\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "plain KNN, k = 20, tuning half: ties by popularity 0.491, ties in column order 0.450\n"
     ]
    }
   ],
   "source": [
    "# Tie order matters for plain KNN. The same rule with ties left in column order, as a plain argsort does\n",
    "def knn_naive_column_order(u, k):\n",
    "    neighbours = np.argsort(-S[u], kind=\"stable\")[:k]\n",
    "    score = H[neighbours].mean(axis=0)\n",
    "    score[H[u] == 1] = -1\n",
    "    return np.argsort(-score, kind=\"stable\")\n",
    "\n",
    "print(f\"most popular, tuning half: {charts['k_curve_baseline']:.3f}\")\n",
    "for k in [5, 10, 20]:\n",
    "    print(f\"plain KNN, k = {k:>2}, tuning half: ties by popularity {hit_rate(lambda u: knn_naive(u, k), tune):.3f}, \"\n",
    "          f\"ties in column order {hit_rate(lambda u: knn_naive_column_order(u, k), tune):.3f}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "09415093",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:52:14.531983Z",
     "iopub.status.busy": "2026-12-05T03:52:14.531913Z",
     "iopub.status.idle": "2026-12-05T03:52:14.538106Z",
     "shell.execute_reply": "2026-12-05T03:52:14.537730Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "NC-00002 Software Growth hidden: api_access\n",
      "NC-00003 Education Enterprise hidden: single_sign_on\n",
      "NC-00004 Healthcare Growth hidden: accounting_sync\n",
      "NC-00005 Professional services Starter hidden: help_desk\n",
      "NC-00028 Manufacturing Starter hidden: payments\n",
      "NC-00043 Retail Enterprise hidden: ecommerce_connector\n"
     ]
    }
   ],
   "source": [
    "# Playground: a few test customers, with their 30 nearest neighbours under both rules\n",
    "def neighbour_list(u, rule, k=30):\n",
    "    if rule == \"fixed\":\n",
    "        sim = np.where(H[:, H[u] == 0].sum(axis=1) > 0, S[u], -1)\n",
    "    else:\n",
    "        sim = S[u]\n",
    "    nb = np.argsort(-sim, kind=\"stable\")[:k]\n",
    "    return [{\"id\": data.customer_id[v], \"s\": round(float(S[u, v]), 3),\n",
    "             \"a\": [int(x) for x in H[v]]} for v in nb]\n",
    "\n",
    "picks, seen = [], set()\n",
    "for u in test:\n",
    "    key = (data.industry[u], tuple(H[u]))\n",
    "    if H[u].sum() >= 1 and key not in seen and data.industry[u] not in {p_[1] for p_ in picks}:\n",
    "        seen.add(key)\n",
    "        picks.append((u, data.industry[u]))\n",
    "    if len(picks) == 6:\n",
    "        break\n",
    "charts[\"playground\"] = [{\n",
    "    \"id\": data.customer_id[u], \"industry\": data.industry[u], \"plan\": data.plan[u],\n",
    "    \"employees\": int(data.employees[u]), \"uses\": [int(x) for x in H[u]], \"hidden\": int(hidden[u]),\n",
    "    \"naive\": neighbour_list(u, \"naive\"), \"fixed\": neighbour_list(u, \"fixed\"),\n",
    "} for u, _ in picks]\n",
    "for p_ in charts[\"playground\"]:\n",
    "    print(p_[\"id\"], p_[\"industry\"], p_[\"plan\"], \"hidden:\", ADDONS[p_[\"hidden\"]])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "f8d94bfe",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:52:14.539126Z",
     "iopub.status.busy": "2026-12-05T03:52:14.539064Z",
     "iopub.status.idle": "2026-12-05T03:52:14.542996Z",
     "shell.execute_reply": "2026-12-05T03:52:14.542628Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "saved 13 chart datasets\n"
     ]
    }
   ],
   "source": [
    "with open(\"knn_recs_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
}
