{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "6860fab8",
   "metadata": {},
   "source": [
    "# KNN for marketing: fill in missing CRM data\n",
    "\n",
    "Companion notebook to the guide at https://martinguzman.ca/blog/knn-fill-missing-crm-data\n",
    "\n",
    "Put `northpine_firmographics.csv` in the same folder as this notebook (download it from https://martinguzman.ca/guides/ml/northpine_firmographics.csv). Northpine Software is a made-up company; the data is synthetic."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "14dd78f0",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:51:59.670834Z",
     "iopub.status.busy": "2026-12-05T03:51:59.670758Z",
     "iopub.status.idle": "2026-12-05T03:52:00.469119Z",
     "shell.execute_reply": "2026-12-05T03:52:00.468722Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(3000, 9)\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>company_id</th>\n",
       "      <th>industry</th>\n",
       "      <th>employees</th>\n",
       "      <th>annual_revenue_musd</th>\n",
       "      <th>linkedin_followers</th>\n",
       "      <th>open_job_postings</th>\n",
       "      <th>office_locations</th>\n",
       "      <th>company_age_years</th>\n",
       "      <th>website_pages</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>NF-00001</td>\n",
       "      <td>Education</td>\n",
       "      <td>690.0</td>\n",
       "      <td>34.7</td>\n",
       "      <td>4020</td>\n",
       "      <td>6</td>\n",
       "      <td>3</td>\n",
       "      <td>23</td>\n",
       "      <td>267</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>NF-00002</td>\n",
       "      <td>Professional services</td>\n",
       "      <td>117.0</td>\n",
       "      <td>21.7</td>\n",
       "      <td>520</td>\n",
       "      <td>2</td>\n",
       "      <td>2</td>\n",
       "      <td>8</td>\n",
       "      <td>84</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>NF-00003</td>\n",
       "      <td>Manufacturing</td>\n",
       "      <td>5262.0</td>\n",
       "      <td>754.4</td>\n",
       "      <td>21370</td>\n",
       "      <td>18</td>\n",
       "      <td>2</td>\n",
       "      <td>34</td>\n",
       "      <td>388</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>NF-00004</td>\n",
       "      <td>Professional services</td>\n",
       "      <td>NaN</td>\n",
       "      <td>2.3</td>\n",
       "      <td>320</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>12</td>\n",
       "      <td>95</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>NF-00005</td>\n",
       "      <td>Retail</td>\n",
       "      <td>46.0</td>\n",
       "      <td>2.7</td>\n",
       "      <td>220</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>4</td>\n",
       "      <td>268</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "  company_id               industry  employees  annual_revenue_musd  \\\n",
       "0   NF-00001              Education      690.0                 34.7   \n",
       "1   NF-00002  Professional services      117.0                 21.7   \n",
       "2   NF-00003          Manufacturing     5262.0                754.4   \n",
       "3   NF-00004  Professional services        NaN                  2.3   \n",
       "4   NF-00005                 Retail       46.0                  2.7   \n",
       "\n",
       "   linkedin_followers  open_job_postings  office_locations  company_age_years  \\\n",
       "0                4020                  6                 3                 23   \n",
       "1                 520                  2                 2                  8   \n",
       "2               21370                 18                 2                 34   \n",
       "3                 320                  1                 1                 12   \n",
       "4                 220                  0                 1                  4   \n",
       "\n",
       "   website_pages  \n",
       "0            267  \n",
       "1             84  \n",
       "2            388  \n",
       "3             95  \n",
       "4            268  "
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "from sklearn.impute import KNNImputer\n",
    "from sklearn.linear_model import LinearRegression\n",
    "from sklearn.neighbors import NearestNeighbors\n",
    "from sklearn.preprocessing import StandardScaler\n",
    "\n",
    "firms = pd.read_csv(\"northpine_firmographics.csv\")\n",
    "print(firms.shape)\n",
    "firms.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "13028d1d",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:52:00.470366Z",
     "iopub.status.busy": "2026-12-05T03:52:00.470286Z",
     "iopub.status.idle": "2026-12-05T03:52:00.475221Z",
     "shell.execute_reply": "2026-12-05T03:52:00.474836Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "missing headcount: 706 of 3,000 companies (23.5%)\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>linkedin_followers</th>\n",
       "      <th>annual_revenue_musd</th>\n",
       "      <th>open_job_postings</th>\n",
       "      <th>website_pages</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>employees</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>headcount known</th>\n",
       "      <td>1040.0</td>\n",
       "      <td>21.60</td>\n",
       "      <td>2.0</td>\n",
       "      <td>117.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>headcount missing</th>\n",
       "      <td>440.0</td>\n",
       "      <td>8.85</td>\n",
       "      <td>1.0</td>\n",
       "      <td>76.0</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                   linkedin_followers  annual_revenue_musd  open_job_postings  \\\n",
       "employees                                                                       \n",
       "headcount known                1040.0                21.60                2.0   \n",
       "headcount missing               440.0                 8.85                1.0   \n",
       "\n",
       "                   website_pages  \n",
       "employees                         \n",
       "headcount known            117.0  \n",
       "headcount missing           76.0  "
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "missing = firms[\"employees\"].isna()\n",
    "print(f\"missing headcount: {missing.sum():,} of {len(firms):,} companies ({missing.mean():.1%})\")\n",
    "\n",
    "firms.groupby(missing.map({False: \"headcount known\", True: \"headcount missing\"}))[\n",
    "    [\"linkedin_followers\", \"annual_revenue_musd\", \"open_job_postings\", \"website_pages\"]].median()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "684dce97",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:52:00.476468Z",
     "iopub.status.busy": "2026-12-05T03:52:00.476386Z",
     "iopub.status.idle": "2026-12-05T03:52:00.479923Z",
     "shell.execute_reply": "2026-12-05T03:52:00.479504Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "12 columns describe each company\n"
     ]
    }
   ],
   "source": [
    "numeric = [\"annual_revenue_musd\", \"linkedin_followers\", \"open_job_postings\",\n",
    "           \"office_locations\", \"company_age_years\", \"website_pages\"]\n",
    "\n",
    "table = np.log1p(firms[numeric])                                  # sizes vary a thousandfold\n",
    "table = table.join(pd.get_dummies(firms[\"industry\"], dtype=float))   # one column per sector\n",
    "table[\"log_employees\"] = np.log10(firms[\"employees\"].astype(float))  # the column to fill\n",
    "features = table.columns.drop(\"log_employees\")\n",
    "print(len(features), \"columns describe each company\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "cab777da",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:52:00.480836Z",
     "iopub.status.busy": "2026-12-05T03:52:00.480764Z",
     "iopub.status.idle": "2026-12-05T03:52:00.483686Z",
     "shell.execute_reply": "2026-12-05T03:52:00.483330Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "known: 2,294   test: 500   tuning: 500\n"
     ]
    }
   ],
   "source": [
    "known = firms.index[~missing]\n",
    "rng = np.random.default_rng(42)\n",
    "test_rows = np.sort(rng.choice(known, size=500, replace=False))\n",
    "tune_rows = np.sort(rng.choice(np.setdiff1d(known, test_rows), size=500, replace=False))\n",
    "\n",
    "truth = firms.loc[test_rows, \"employees\"].astype(float)\n",
    "tune_truth = firms.loc[tune_rows, \"employees\"].astype(float)\n",
    "print(f\"known: {len(known):,}   test: {len(test_rows)}   tuning: {len(tune_rows)}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "dca65a34",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:52:00.484809Z",
     "iopub.status.busy": "2026-12-05T03:52:00.484739Z",
     "iopub.status.idle": "2026-12-05T03:52:00.491657Z",
     "shell.execute_reply": "2026-12-05T03:52:00.491264Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "overall median: 140 employees\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>typical_error_factor</th>\n",
       "      <th>within_1.5x</th>\n",
       "      <th>band_correct</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>Overall median</th>\n",
       "      <td>2.26</td>\n",
       "      <td>0.270</td>\n",
       "      <td>0.64</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Industry median</th>\n",
       "      <td>2.28</td>\n",
       "      <td>0.274</td>\n",
       "      <td>0.64</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                 typical_error_factor  within_1.5x  band_correct\n",
       "Overall median                   2.26        0.270          0.64\n",
       "Industry median                  2.28        0.274          0.64"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def size_band(n):\n",
    "    return pd.cut(n, [0, 49, 499, np.inf], labels=[\"1-49\", \"50-499\", \"500+\"])\n",
    "\n",
    "def score(estimate, truth):\n",
    "    factor = np.maximum(estimate / truth, truth / estimate)   # 2.0 = off by double or half\n",
    "    return {\"typical_error_factor\": round(factor.median(), 2),\n",
    "            \"within_1.5x\": round((factor <= 1.5).mean(), 3),\n",
    "            \"band_correct\": round((size_band(estimate) == size_band(truth)).mean(), 3)}\n",
    "\n",
    "others = firms.loc[np.setdiff1d(known, test_rows)]\n",
    "overall_median = pd.Series(others[\"employees\"].median(), index=test_rows, dtype=float)\n",
    "industry_median = firms.loc[test_rows, \"industry\"].map(\n",
    "    others.groupby(\"industry\")[\"employees\"].median()).astype(float)\n",
    "print(f\"overall median: {overall_median.iloc[0]:.0f} employees\")\n",
    "\n",
    "pd.DataFrame({\"Overall median\": score(overall_median, truth),\n",
    "              \"Industry median\": score(industry_median, truth)}).T"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "cbc1bdb6",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:52:00.492780Z",
     "iopub.status.busy": "2026-12-05T03:52:00.492711Z",
     "iopub.status.idle": "2026-12-05T03:52:00.494694Z",
     "shell.execute_reply": "2026-12-05T03:52:00.494351Z"
    }
   },
   "outputs": [],
   "source": [
    "def knn_fill(table, hide, k):\n",
    "    \"\"\"Hide the headcounts in `hide`, then estimate every missing headcount from its k nearest companies.\"\"\"\n",
    "    work = table.copy()\n",
    "    work.loc[hide, \"log_employees\"] = np.nan\n",
    "    scaler = StandardScaler().fit(work)                  # learns each column's mean and spread, ignoring gaps\n",
    "    filled = KNNImputer(n_neighbors=k).fit_transform(scaler.transform(work))\n",
    "    filled = scaler.inverse_transform(filled)\n",
    "    column = work.columns.get_loc(\"log_employees\")\n",
    "    return pd.Series(10 ** filled[:, column], index=table.index).round()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "4a550d2c",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:52:00.495627Z",
     "iopub.status.busy": "2026-12-05T03:52:00.495563Z",
     "iopub.status.idle": "2026-12-05T03:52:00.999667Z",
     "shell.execute_reply": "2026-12-05T03:52:00.999211Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "best k: 10, typical error factor 1.3000\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>k</th>\n",
       "      <th>typical_error_factor</th>\n",
       "      <th>within_1.5x</th>\n",
       "      <th>band_correct</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>1</td>\n",
       "      <td>1.39</td>\n",
       "      <td>0.588</td>\n",
       "      <td>0.850</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>3</td>\n",
       "      <td>1.30</td>\n",
       "      <td>0.674</td>\n",
       "      <td>0.874</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>5</td>\n",
       "      <td>1.31</td>\n",
       "      <td>0.666</td>\n",
       "      <td>0.890</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>10</td>\n",
       "      <td>1.30</td>\n",
       "      <td>0.694</td>\n",
       "      <td>0.890</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>20</td>\n",
       "      <td>1.32</td>\n",
       "      <td>0.652</td>\n",
       "      <td>0.870</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>40</td>\n",
       "      <td>1.34</td>\n",
       "      <td>0.642</td>\n",
       "      <td>0.842</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>80</td>\n",
       "      <td>1.43</td>\n",
       "      <td>0.562</td>\n",
       "      <td>0.796</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "    k  typical_error_factor  within_1.5x  band_correct\n",
       "0   1                  1.39        0.588         0.850\n",
       "1   3                  1.30        0.674         0.874\n",
       "2   5                  1.31        0.666         0.890\n",
       "3  10                  1.30        0.694         0.890\n",
       "4  20                  1.32        0.652         0.870\n",
       "5  40                  1.34        0.642         0.842\n",
       "6  80                  1.43        0.562         0.796"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "results, error = [], {}\n",
    "for k in [1, 3, 5, 10, 20, 40, 80]:\n",
    "    estimate = knn_fill(table, np.r_[tune_rows, test_rows], k)[tune_rows]   # test headcounts stay hidden too\n",
    "    error[k] = np.maximum(estimate / tune_truth, tune_truth / estimate).median()\n",
    "    results.append({\"k\": k, **score(estimate, tune_truth)})\n",
    "\n",
    "best_k = min(error, key=error.get)   # lowest unrounded typical error; a tie goes to the smaller k\n",
    "print(f\"best k: {best_k}, typical error factor {error[best_k]:.4f}\")\n",
    "pd.DataFrame(results)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "99d59c7b",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:52:01.000835Z",
     "iopub.status.busy": "2026-12-05T03:52:01.000763Z",
     "iopub.status.idle": "2026-12-05T03:52:01.065349Z",
     "shell.execute_reply": "2026-12-05T03:52:01.064917Z"
    }
   },
   "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>typical_error_factor</th>\n",
       "      <th>within_1.5x</th>\n",
       "      <th>band_correct</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>Overall median</th>\n",
       "      <td>2.26</td>\n",
       "      <td>0.270</td>\n",
       "      <td>0.640</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Industry median</th>\n",
       "      <td>2.28</td>\n",
       "      <td>0.274</td>\n",
       "      <td>0.640</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>KNN, k=10</th>\n",
       "      <td>1.30</td>\n",
       "      <td>0.718</td>\n",
       "      <td>0.886</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                 typical_error_factor  within_1.5x  band_correct\n",
       "Overall median                   2.26        0.270         0.640\n",
       "Industry median                  2.28        0.274         0.640\n",
       "KNN, k=10                        1.30        0.718         0.886"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "knn_estimate = knn_fill(table, test_rows, best_k)[test_rows]\n",
    "\n",
    "comparison = pd.DataFrame({\"Overall median\": score(overall_median, truth),\n",
    "                           \"Industry median\": score(industry_median, truth),\n",
    "                           f\"KNN, k={best_k}\": score(knn_estimate, truth)}).T\n",
    "comparison"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "7cba9385",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:52:01.066608Z",
     "iopub.status.busy": "2026-12-05T03:52:01.066532Z",
     "iopub.status.idle": "2026-12-05T03:52:01.073127Z",
     "shell.execute_reply": "2026-12-05T03:52:01.072631Z"
    }
   },
   "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>KNN estimate</th>\n",
       "      <th>1-49</th>\n",
       "      <th>50-499</th>\n",
       "      <th>500+</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>true band</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>1-49</th>\n",
       "      <td>83</td>\n",
       "      <td>16</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>50-499</th>\n",
       "      <td>13</td>\n",
       "      <td>298</td>\n",
       "      <td>9</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>500+</th>\n",
       "      <td>0</td>\n",
       "      <td>19</td>\n",
       "      <td>62</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "KNN estimate  1-49  50-499  500+\n",
       "true band                       \n",
       "1-49            83      16     0\n",
       "50-499          13     298     9\n",
       "500+             0      19    62"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pd.crosstab(size_band(truth).rename(\"true band\"),\n",
    "            size_band(knn_estimate).rename(\"KNN estimate\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "66ca8c98",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:52:01.074199Z",
     "iopub.status.busy": "2026-12-05T03:52:01.074128Z",
     "iopub.status.idle": "2026-12-05T03:52:01.082332Z",
     "shell.execute_reply": "2026-12-05T03:52:01.081957Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'company_id': 'NF-00013', 'industry': 'Healthcare', 'employees': 199.0, 'annual_revenue_musd': 14.0, 'linkedin_followers': 3260, 'open_job_postings': 2}\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>company_id</th>\n",
       "      <th>industry</th>\n",
       "      <th>employees</th>\n",
       "      <th>annual_revenue_musd</th>\n",
       "      <th>linkedin_followers</th>\n",
       "      <th>open_job_postings</th>\n",
       "      <th>distance</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>2321</th>\n",
       "      <td>NF-02322</td>\n",
       "      <td>Healthcare</td>\n",
       "      <td>124.0</td>\n",
       "      <td>16.2</td>\n",
       "      <td>960</td>\n",
       "      <td>1</td>\n",
       "      <td>1.30</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2305</th>\n",
       "      <td>NF-02306</td>\n",
       "      <td>Healthcare</td>\n",
       "      <td>90.0</td>\n",
       "      <td>16.7</td>\n",
       "      <td>2250</td>\n",
       "      <td>1</td>\n",
       "      <td>1.49</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>305</th>\n",
       "      <td>NF-00306</td>\n",
       "      <td>Healthcare</td>\n",
       "      <td>115.0</td>\n",
       "      <td>27.0</td>\n",
       "      <td>830</td>\n",
       "      <td>2</td>\n",
       "      <td>1.56</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1363</th>\n",
       "      <td>NF-01364</td>\n",
       "      <td>Healthcare</td>\n",
       "      <td>202.0</td>\n",
       "      <td>40.3</td>\n",
       "      <td>1630</td>\n",
       "      <td>6</td>\n",
       "      <td>1.60</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1202</th>\n",
       "      <td>NF-01203</td>\n",
       "      <td>Healthcare</td>\n",
       "      <td>255.0</td>\n",
       "      <td>58.7</td>\n",
       "      <td>6830</td>\n",
       "      <td>3</td>\n",
       "      <td>1.62</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>291</th>\n",
       "      <td>NF-00292</td>\n",
       "      <td>Healthcare</td>\n",
       "      <td>114.0</td>\n",
       "      <td>22.3</td>\n",
       "      <td>1140</td>\n",
       "      <td>1</td>\n",
       "      <td>1.66</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>692</th>\n",
       "      <td>NF-00693</td>\n",
       "      <td>Healthcare</td>\n",
       "      <td>121.0</td>\n",
       "      <td>20.2</td>\n",
       "      <td>1190</td>\n",
       "      <td>1</td>\n",
       "      <td>1.69</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>260</th>\n",
       "      <td>NF-00261</td>\n",
       "      <td>Healthcare</td>\n",
       "      <td>119.0</td>\n",
       "      <td>15.3</td>\n",
       "      <td>600</td>\n",
       "      <td>2</td>\n",
       "      <td>1.75</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2555</th>\n",
       "      <td>NF-02556</td>\n",
       "      <td>Healthcare</td>\n",
       "      <td>446.0</td>\n",
       "      <td>25.6</td>\n",
       "      <td>6190</td>\n",
       "      <td>3</td>\n",
       "      <td>1.75</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1822</th>\n",
       "      <td>NF-01823</td>\n",
       "      <td>Healthcare</td>\n",
       "      <td>92.0</td>\n",
       "      <td>26.4</td>\n",
       "      <td>1180</td>\n",
       "      <td>1</td>\n",
       "      <td>1.76</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "     company_id    industry  employees  annual_revenue_musd  \\\n",
       "2321   NF-02322  Healthcare      124.0                 16.2   \n",
       "2305   NF-02306  Healthcare       90.0                 16.7   \n",
       "305    NF-00306  Healthcare      115.0                 27.0   \n",
       "1363   NF-01364  Healthcare      202.0                 40.3   \n",
       "1202   NF-01203  Healthcare      255.0                 58.7   \n",
       "291    NF-00292  Healthcare      114.0                 22.3   \n",
       "692    NF-00693  Healthcare      121.0                 20.2   \n",
       "260    NF-00261  Healthcare      119.0                 15.3   \n",
       "2555   NF-02556  Healthcare      446.0                 25.6   \n",
       "1822   NF-01823  Healthcare       92.0                 26.4   \n",
       "\n",
       "      linkedin_followers  open_job_postings  distance  \n",
       "2321                 960                  1      1.30  \n",
       "2305                2250                  1      1.49  \n",
       "305                  830                  2      1.56  \n",
       "1363                1630                  6      1.60  \n",
       "1202                6830                  3      1.62  \n",
       "291                 1140                  1      1.66  \n",
       "692                 1190                  1      1.69  \n",
       "260                  600                  2      1.75  \n",
       "2555                6190                  3      1.75  \n",
       "1822                1180                  1      1.76  "
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "work = table.copy()\n",
    "work.loc[test_rows, \"log_employees\"] = np.nan\n",
    "scaled = pd.DataFrame(StandardScaler().fit_transform(work[features]),\n",
    "                      index=work.index, columns=features)\n",
    "donors = work.index[work[\"log_employees\"].notna()]\n",
    "finder = NearestNeighbors(n_neighbors=best_k).fit(scaled.loc[donors])\n",
    "\n",
    "example = test_rows[0]\n",
    "distance, index = finder.kneighbors(scaled.loc[[example]])\n",
    "show = [\"company_id\", \"industry\", \"employees\", \"annual_revenue_musd\",\n",
    "        \"linkedin_followers\", \"open_job_postings\"]\n",
    "print(firms.loc[example, show].to_dict())\n",
    "firms.loc[donors[index[0]], show].assign(distance=distance[0].round(2))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "cbabfea7",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:52:01.083534Z",
     "iopub.status.busy": "2026-12-05T03:52:01.083448Z",
     "iopub.status.idle": "2026-12-05T03:52:01.085711Z",
     "shell.execute_reply": "2026-12-05T03:52:01.085327Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "geometric mean of the 10 neighbours: 146\n",
      "KNN estimate: 146   true headcount: 199\n"
     ]
    }
   ],
   "source": [
    "neighbour_sizes = firms.loc[donors[index[0]], \"employees\"].astype(float)\n",
    "print(f\"geometric mean of the {best_k} neighbours: {10 ** np.log10(neighbour_sizes).mean():.0f}\")\n",
    "print(f\"KNN estimate: {knn_estimate[example]:.0f}   true headcount: {truth[example]:.0f}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "623a94a3",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:52:01.086714Z",
     "iopub.status.busy": "2026-12-05T03:52:01.086650Z",
     "iopub.status.idle": "2026-12-05T03:52:01.140184Z",
     "shell.execute_reply": "2026-12-05T03:52:01.139787Z"
    }
   },
   "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>measured</th>\n",
       "      <th>estimated</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>employees_filled</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>1-49</th>\n",
       "      <td>0.185</td>\n",
       "      <td>0.438</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>50-499</th>\n",
       "      <td>0.657</td>\n",
       "      <td>0.531</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>500+</th>\n",
       "      <td>0.158</td>\n",
       "      <td>0.031</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                  measured  estimated\n",
       "employees_filled                     \n",
       "1-49                 0.185      0.438\n",
       "50-499               0.657      0.531\n",
       "500+                 0.158      0.031"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "filled = knn_fill(table, [], best_k)\n",
    "firms[\"employees_filled\"] = firms[\"employees\"].astype(float).fillna(filled).astype(int)\n",
    "firms[\"employees_is_estimate\"] = missing.astype(int)\n",
    "firms.to_csv(\"firmographics_filled.csv\", index=False)\n",
    "\n",
    "pd.DataFrame({\n",
    "    \"measured\": size_band(firms.loc[~missing, \"employees_filled\"]).value_counts(normalize=True).sort_index(),\n",
    "    \"estimated\": size_band(firms.loc[missing, \"employees_filled\"]).value_counts(normalize=True).sort_index(),\n",
    "}).round(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "1454442a",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:52:01.141353Z",
     "iopub.status.busy": "2026-12-05T03:52:01.141275Z",
     "iopub.status.idle": "2026-12-05T03:52:01.144780Z",
     "shell.execute_reply": "2026-12-05T03:52:01.144472Z"
    }
   },
   "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>company_id</th>\n",
       "      <th>industry</th>\n",
       "      <th>annual_revenue_musd</th>\n",
       "      <th>linkedin_followers</th>\n",
       "      <th>employees</th>\n",
       "      <th>employees_filled</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>NF-00004</td>\n",
       "      <td>Professional services</td>\n",
       "      <td>2.3</td>\n",
       "      <td>320</td>\n",
       "      <td>NaN</td>\n",
       "      <td>41</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>13</th>\n",
       "      <td>NF-00014</td>\n",
       "      <td>Healthcare</td>\n",
       "      <td>17.0</td>\n",
       "      <td>370</td>\n",
       "      <td>NaN</td>\n",
       "      <td>62</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>15</th>\n",
       "      <td>NF-00016</td>\n",
       "      <td>Software</td>\n",
       "      <td>13.7</td>\n",
       "      <td>250</td>\n",
       "      <td>NaN</td>\n",
       "      <td>58</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   company_id               industry  annual_revenue_musd  linkedin_followers  \\\n",
       "3    NF-00004  Professional services                  2.3                 320   \n",
       "13   NF-00014             Healthcare                 17.0                 370   \n",
       "15   NF-00016               Software                 13.7                 250   \n",
       "\n",
       "    employees  employees_filled  \n",
       "3         NaN                41  \n",
       "13        NaN                62  \n",
       "15        NaN                58  "
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "firms.loc[missing, [\"company_id\", \"industry\", \"annual_revenue_musd\", \"linkedin_followers\",\n",
    "                     \"employees\", \"employees_filled\"]].head(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "c823af55",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:52:01.145881Z",
     "iopub.status.busy": "2026-12-05T03:52:01.145813Z",
     "iopub.status.idle": "2026-12-05T03:52:01.152343Z",
     "shell.execute_reply": "2026-12-05T03:52:01.152012Z"
    }
   },
   "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>typical_error_factor</th>\n",
       "      <th>within_1.5x</th>\n",
       "      <th>band_correct</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>Overall median</th>\n",
       "      <td>2.26</td>\n",
       "      <td>0.270</td>\n",
       "      <td>0.640</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Industry median</th>\n",
       "      <td>2.28</td>\n",
       "      <td>0.274</td>\n",
       "      <td>0.640</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>KNN, k=10</th>\n",
       "      <td>1.30</td>\n",
       "      <td>0.718</td>\n",
       "      <td>0.886</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Linear regression</th>\n",
       "      <td>1.23</td>\n",
       "      <td>0.826</td>\n",
       "      <td>0.902</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                   typical_error_factor  within_1.5x  band_correct\n",
       "Overall median                     2.26        0.270         0.640\n",
       "Industry median                    2.28        0.274         0.640\n",
       "KNN, k=10                          1.30        0.718         0.886\n",
       "Linear regression                  1.23        0.826         0.902"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "train = np.setdiff1d(known, test_rows)\n",
    "regression = LinearRegression().fit(table.loc[train, features], table.loc[train, \"log_employees\"])\n",
    "regression_estimate = pd.Series(10 ** regression.predict(table.loc[test_rows, features]),\n",
    "                                index=test_rows).round()\n",
    "\n",
    "comparison.loc[\"Linear regression\"] = score(regression_estimate, truth)\n",
    "comparison"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4ea7dbea",
   "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_impute_charts.json`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "3711bed6",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:52:01.153391Z",
     "iopub.status.busy": "2026-12-05T03:52:01.153321Z",
     "iopub.status.idle": "2026-12-05T03:52:01.164995Z",
     "shell.execute_reply": "2026-12-05T03:52:01.164582Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'knn': [[83, 16, 0], [13, 298, 9], [0, 19, 62]],\n",
       " 'overall': [[0, 99, 0], [0, 320, 0], [0, 81, 0]],\n",
       " 'industry': [[0, 99, 0], [0, 320, 0], [0, 81, 0]]}"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import json\n",
    "\n",
    "charts = {\"best_k\": int(best_k),\n",
    "          \"missing\": int(missing.sum()), \"n\": int(len(firms)),\n",
    "          \"overall_median\": float(overall_median.iloc[0]),\n",
    "          \"k_curve\": [{key: (float(v) if not isinstance(v, int) else v) for key, v in r.items()} for r in results],\n",
    "          \"comparison\": [{\"method\": m, **{c: float(v) for c, v in row.items()}}\n",
    "                         for m, row in comparison.iterrows()]}\n",
    "\n",
    "# Estimate against truth for the 500 test companies, for each method\n",
    "charts[\"scatter\"] = [{\"t\": int(t), \"k\": int(k), \"o\": int(o), \"i\": int(i), \"r\": int(r)}\n",
    "                     for t, k, o, i, r in zip(truth, knn_estimate, overall_median,\n",
    "                                              industry_median, regression_estimate)]\n",
    "\n",
    "# Size bands: true band (rows) against estimated band (columns), per method\n",
    "bands = [\"1-49\", \"50-499\", \"500+\"]\n",
    "charts[\"bands\"] = {name: pd.crosstab(size_band(truth), size_band(est)).reindex(\n",
    "                       index=bands, columns=bands, fill_value=0).values.tolist()\n",
    "                   for name, est in [(\"knn\", knn_estimate), (\"overall\", overall_median),\n",
    "                                     (\"industry\", industry_median)]}\n",
    "charts[\"bands\"]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "df3bd9e6",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:52:01.166109Z",
     "iopub.status.busy": "2026-12-05T03:52:01.166040Z",
     "iopub.status.idle": "2026-12-05T03:52:01.175747Z",
     "shell.execute_reply": "2026-12-05T03:52:01.175417Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "NF-02716 truth 30 estimate 29 recomputed 29\n",
      "NF-00259 truth 80 estimate 73 recomputed 73\n",
      "NF-00856 truth 154 estimate 188 recomputed 188\n",
      "NF-01432 truth 278 estimate 155 recomputed 155\n",
      "NF-02964 truth 715 estimate 778 recomputed 778\n"
     ]
    }
   ],
   "source": [
    "# Playground: five test companies, each with its 40 nearest complete companies (full model)\n",
    "picks = [truth.sort_values(kind=\"stable\").index[int(q * (len(truth) - 1))] for q in [0.1, 0.3, 0.5, 0.7, 0.9]]\n",
    "dist40, idx40 = NearestNeighbors(n_neighbors=40).fit(scaled.loc[donors]).kneighbors(scaled.loc[picks])\n",
    "charts[\"examples\"] = []\n",
    "for row, d, ix in zip(picks, dist40, idx40):\n",
    "    f = firms.loc[row]\n",
    "    charts[\"examples\"].append({\n",
    "        \"id\": f.company_id, \"ind\": f.industry, \"f\": int(f.linkedin_followers),\n",
    "        \"rev\": float(f.annual_revenue_musd), \"jobs\": int(f.open_job_postings), \"truth\": int(f.employees),\n",
    "        \"est\": int(knn_estimate[row]),\n",
    "        \"nb\": [{\"id\": firms.loc[j, \"company_id\"], \"f\": int(firms.loc[j, \"linkedin_followers\"]),\n",
    "                \"e\": int(firms.loc[j, \"employees\"]), \"d\": round(float(dd), 3)}\n",
    "               for dd, j in zip(d, donors[ix])]})\n",
    "    check = round(10 ** np.log10([n[\"e\"] for n in charts[\"examples\"][-1][\"nb\"][:best_k]]).mean())\n",
    "    print(f.company_id, \"truth\", int(f.employees), \"estimate\", int(knn_estimate[row]), \"recomputed\", check)\n",
    "\n",
    "background = np.random.default_rng(7).choice(donors, size=400, replace=False)\n",
    "charts[\"points\"] = [{\"f\": int(firms.loc[j, \"linkedin_followers\"]), \"e\": int(firms.loc[j, \"employees\"])}\n",
    "                    for j in np.sort(background)]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "f0bb31f0",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:52:01.176835Z",
     "iopub.status.busy": "2026-12-05T03:52:01.176768Z",
     "iopub.status.idle": "2026-12-05T03:52:01.179976Z",
     "shell.execute_reply": "2026-12-05T03:52:01.179559Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "median measured 141.5  median estimated 59.0\n"
     ]
    }
   ],
   "source": [
    "# Distribution: measured headcounts against the 706 estimates, on a log scale\n",
    "edges = np.arange(0.5, 4.01, 0.25)\n",
    "measured = np.histogram(np.log10(firms.loc[~missing, \"employees_filled\"]), edges)[0]\n",
    "estimated = np.histogram(np.log10(firms.loc[missing, \"employees_filled\"]), edges)[0]\n",
    "charts[\"distribution\"] = {\"edges\": edges.round(2).tolist(),\n",
    "                          \"measured\": measured.tolist(), \"estimated\": estimated.tolist(),\n",
    "                          \"median_measured\": float(firms.loc[~missing, \"employees_filled\"].median()),\n",
    "                          \"median_estimated\": float(firms.loc[missing, \"employees_filled\"].median())}\n",
    "print(\"median measured\", charts[\"distribution\"][\"median_measured\"],\n",
    "      \" median estimated\", charts[\"distribution\"][\"median_estimated\"])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "b4588e0d",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:52:01.180983Z",
     "iopub.status.busy": "2026-12-05T03:52:01.180902Z",
     "iopub.status.idle": "2026-12-05T03:52:01.185828Z",
     "shell.execute_reply": "2026-12-05T03:52:01.185485Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "saved 11 chart datasets\n"
     ]
    }
   ],
   "source": [
    "with open(\"knn_impute_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
}
