{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "13c46e06",
   "metadata": {},
   "source": [
    "# Decision trees for marketing: predict a new customer's first-year value\n",
    "\n",
    "Companion notebook to the guides at https://martinguzman.ca/blog/decision-tree-explained and https://martinguzman.ca/blog/decision-tree-customer-value\n",
    "\n",
    "Put `tamarack_customers.csv` in the same folder as this notebook (download it from https://martinguzman.ca/guides/ml/tamarack_customers.csv). Tamarack & Talus is a made-up online outdoor gear retailer; the data is synthetic."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "f7407f38",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:28:12.974853Z",
     "iopub.status.busy": "2026-12-05T03:28:12.974697Z",
     "iopub.status.idle": "2026-12-05T03:28:13.826423Z",
     "shell.execute_reply": "2026-12-05T03:28:13.825943Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(8000, 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>first_order_date</th>\n",
       "      <th>province</th>\n",
       "      <th>channel</th>\n",
       "      <th>device</th>\n",
       "      <th>first_category</th>\n",
       "      <th>first_order_value</th>\n",
       "      <th>items_in_first_order</th>\n",
       "      <th>discount_code</th>\n",
       "      <th>account_created</th>\n",
       "      <th>loyalty_signup</th>\n",
       "      <th>orders_90d</th>\n",
       "      <th>spend_90d</th>\n",
       "      <th>returned_first_order</th>\n",
       "      <th>first_year_value</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>TT-00001</td>\n",
       "      <td>2025-01-01</td>\n",
       "      <td>Ontario</td>\n",
       "      <td>Referral</td>\n",
       "      <td>Mobile</td>\n",
       "      <td>Clothing</td>\n",
       "      <td>56.41</td>\n",
       "      <td>2</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0.00</td>\n",
       "      <td>0</td>\n",
       "      <td>56.41</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>TT-00002</td>\n",
       "      <td>2025-01-01</td>\n",
       "      <td>Ontario</td>\n",
       "      <td>Paid search</td>\n",
       "      <td>Desktop</td>\n",
       "      <td>Footwear</td>\n",
       "      <td>50.64</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>96.47</td>\n",
       "      <td>0</td>\n",
       "      <td>147.11</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>TT-00003</td>\n",
       "      <td>2025-01-01</td>\n",
       "      <td>Ontario</td>\n",
       "      <td>Affiliate and review sites</td>\n",
       "      <td>Desktop</td>\n",
       "      <td>Backpacks</td>\n",
       "      <td>223.36</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>109.21</td>\n",
       "      <td>0</td>\n",
       "      <td>332.57</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>TT-00004</td>\n",
       "      <td>2025-01-01</td>\n",
       "      <td>Ontario</td>\n",
       "      <td>Paid social</td>\n",
       "      <td>Mobile</td>\n",
       "      <td>Clothing</td>\n",
       "      <td>106.88</td>\n",
       "      <td>2</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0.00</td>\n",
       "      <td>1</td>\n",
       "      <td>0.00</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>TT-00005</td>\n",
       "      <td>2025-01-01</td>\n",
       "      <td>Ontario</td>\n",
       "      <td>Paid social</td>\n",
       "      <td>Desktop</td>\n",
       "      <td>Footwear</td>\n",
       "      <td>125.76</td>\n",
       "      <td>2</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>0.00</td>\n",
       "      <td>0</td>\n",
       "      <td>125.76</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "  customer_id first_order_date province                     channel   device  \\\n",
       "0    TT-00001       2025-01-01  Ontario                    Referral   Mobile   \n",
       "1    TT-00002       2025-01-01  Ontario                 Paid search  Desktop   \n",
       "2    TT-00003       2025-01-01  Ontario  Affiliate and review sites  Desktop   \n",
       "3    TT-00004       2025-01-01  Ontario                 Paid social   Mobile   \n",
       "4    TT-00005       2025-01-01  Ontario                 Paid social  Desktop   \n",
       "\n",
       "  first_category  first_order_value  items_in_first_order  discount_code  \\\n",
       "0       Clothing              56.41                     2              0   \n",
       "1       Footwear              50.64                     1              0   \n",
       "2      Backpacks             223.36                     1              1   \n",
       "3       Clothing             106.88                     2              1   \n",
       "4       Footwear             125.76                     2              1   \n",
       "\n",
       "   account_created  loyalty_signup  orders_90d  spend_90d  \\\n",
       "0                0               0           0       0.00   \n",
       "1                1               0           1      96.47   \n",
       "2                0               0           1     109.21   \n",
       "3                1               0           0       0.00   \n",
       "4                1               1           0       0.00   \n",
       "\n",
       "   returned_first_order  first_year_value  \n",
       "0                     0             56.41  \n",
       "1                     0            147.11  \n",
       "2                     0            332.57  \n",
       "3                     1              0.00  \n",
       "4                     0            125.76  "
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "from sklearn.base import clone\n",
    "from sklearn.compose import make_column_transformer\n",
    "from sklearn.linear_model import LinearRegression\n",
    "from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\n",
    "from sklearn.model_selection import GridSearchCV, KFold, train_test_split\n",
    "from sklearn.pipeline import make_pipeline\n",
    "from sklearn.preprocessing import OneHotEncoder\n",
    "from sklearn.tree import DecisionTreeRegressor, export_text\n",
    "\n",
    "customers = pd.read_csv(\"tamarack_customers.csv\", parse_dates=[\"first_order_date\"])\n",
    "print(customers.shape)\n",
    "customers.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "8fc65451",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:28:13.827511Z",
     "iopub.status.busy": "2026-12-05T03:28:13.827436Z",
     "iopub.status.idle": "2026-12-05T03:28:13.831360Z",
     "shell.execute_reply": "2026-12-05T03:28:13.830928Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "count    8000.00\n",
      "mean      413.99\n",
      "std       444.66\n",
      "min         0.00\n",
      "25%       119.78\n",
      "50%       262.86\n",
      "75%       546.80\n",
      "max      3848.66\n",
      "Name: first_year_value, dtype: float64\n",
      "\n",
      "spent nothing after their first order: 36.6%\n",
      "share of all first-year value from the top 20% of customers: 54.7%\n"
     ]
    }
   ],
   "source": [
    "value = customers[\"first_year_value\"]\n",
    "print(value.describe().round(2))\n",
    "\n",
    "no_repeat = (customers[\"first_year_value\"] <= customers[\"first_order_value\"]).mean()\n",
    "ranked = value.sort_values(ascending=False, kind=\"stable\")\n",
    "top_fifth = ranked.head(len(ranked) // 5).sum() / ranked.sum()\n",
    "print(f\"\\nspent nothing after their first order: {no_repeat:.1%}\")\n",
    "print(f\"share of all first-year value from the top 20% of customers: {top_fifth:.1%}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "f7dcbd4d",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:28:13.832299Z",
     "iopub.status.busy": "2026-12-05T03:28:13.832215Z",
     "iopub.status.idle": "2026-12-05T03:28:13.834513Z",
     "shell.execute_reply": "2026-12-05T03:28:13.834156Z"
    }
   },
   "outputs": [],
   "source": [
    "customers[\"first_order_month\"] = customers[\"first_order_date\"].dt.month\n",
    "\n",
    "categorical = [\"channel\", \"first_category\", \"province\", \"device\"]\n",
    "numeric = [\"first_order_value\", \"items_in_first_order\", \"discount_code\",\n",
    "           \"account_created\", \"loyalty_signup\", \"first_order_month\"]\n",
    "after_first_order = [\"orders_90d\", \"spend_90d\", \"returned_first_order\"]   # not known yet: left out\n",
    "\n",
    "X = customers[categorical + numeric]\n",
    "y = customers[\"first_year_value\"]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "02b241a3",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:28:13.835399Z",
     "iopub.status.busy": "2026-12-05T03:28:13.835329Z",
     "iopub.status.idle": "2026-12-05T03:28:13.838320Z",
     "shell.execute_reply": "2026-12-05T03:28:13.837977Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "train: 5,600 customers, average value $415.35\n",
      "test:  2,400 customers, average value $410.80\n"
     ]
    }
   ],
   "source": [
    "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)\n",
    "\n",
    "print(f\"train: {len(X_train):,} customers, average value ${y_train.mean():,.2f}\")\n",
    "print(f\"test:  {len(X_test):,} customers, average value ${y_test.mean():,.2f}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "895d2267",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:28:13.839284Z",
     "iopub.status.busy": "2026-12-05T03:28:13.839213Z",
     "iopub.status.idle": "2026-12-05T03:28:13.840804Z",
     "shell.execute_reply": "2026-12-05T03:28:13.840493Z"
    }
   },
   "outputs": [],
   "source": [
    "prep = make_column_transformer(\n",
    "    (OneHotEncoder(handle_unknown=\"ignore\", sparse_output=False), categorical),\n",
    "    (\"passthrough\", numeric),\n",
    "    verbose_feature_names_out=False,\n",
    ")\n",
    "tree = make_pipeline(prep, DecisionTreeRegressor(random_state=42))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "87eb61c2",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:28:13.841637Z",
     "iopub.status.busy": "2026-12-05T03:28:13.841577Z",
     "iopub.status.idle": "2026-12-05T03:28:16.387258Z",
     "shell.execute_reply": "2026-12-05T03:28:16.386759Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "min_samples_leaf    1      10     30     60     100\n",
      "max_depth                                          \n",
      "2                 0.503  0.503  0.503  0.503  0.503\n",
      "3                 0.561  0.561  0.561  0.561  0.561\n",
      "4                 0.621  0.621  0.623  0.617  0.611\n",
      "5                 0.658  0.657  0.660  0.653  0.643\n",
      "6                 0.677  0.676  0.678  0.669  0.650\n",
      "7                 0.675  0.680  0.679  0.669  0.651\n",
      "8                 0.658  0.678  0.680  0.671  0.651\n",
      "10                0.597  0.668  0.677  0.671  0.651\n",
      "12                0.531  0.656  0.676  0.671  0.651\n",
      "15                0.456  0.653  0.676  0.671  0.651\n",
      "\n",
      "best: {'decisiontreeregressor__max_depth': 8, 'decisiontreeregressor__min_samples_leaf': 30} cross-validated R² 0.680\n"
     ]
    }
   ],
   "source": [
    "folds = KFold(n_splits=5, shuffle=True, random_state=42)\n",
    "\n",
    "grid = GridSearchCV(\n",
    "    tree,\n",
    "    {\"decisiontreeregressor__max_depth\": [2, 3, 4, 5, 6, 7, 8, 10, 12, 15],\n",
    "     \"decisiontreeregressor__min_samples_leaf\": [1, 10, 30, 60, 100]},\n",
    "    cv=folds, scoring=\"r2\")\n",
    "grid.fit(X_train, y_train)\n",
    "\n",
    "results = pd.DataFrame(grid.cv_results_[\"params\"])\n",
    "results.columns = [\"max_depth\", \"min_samples_leaf\"]\n",
    "results[\"cv_r2\"] = grid.cv_results_[\"mean_test_score\"].round(3)\n",
    "print(results.pivot(index=\"max_depth\", columns=\"min_samples_leaf\", values=\"cv_r2\"))\n",
    "print(\"\\nbest:\", grid.best_params_, f\"cross-validated R² {grid.best_score_:.3f}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "3f88ff09",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:28:16.388631Z",
     "iopub.status.busy": "2026-12-05T03:28:16.388528Z",
     "iopub.status.idle": "2026-12-05T03:28:16.395917Z",
     "shell.execute_reply": "2026-12-05T03:28:16.395363Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "leaves: 106, depth: 8\n",
      "R²    0.650\n",
      "MAE   $159.99   (guessing the average: $315.14)\n",
      "RMSE  $261.52   (guessing the average: $441.81)\n"
     ]
    }
   ],
   "source": [
    "model = grid.best_estimator_\n",
    "pred = model.predict(X_test)\n",
    "everyone_average = np.full(len(y_test), y_train.mean())\n",
    "\n",
    "print(f\"leaves: {model[-1].get_n_leaves()}, depth: {model[-1].get_depth()}\")\n",
    "print(f\"R²    {r2_score(y_test, pred):.3f}\")\n",
    "print(f\"MAE   ${mean_absolute_error(y_test, pred):,.2f}   (guessing the average: ${mean_absolute_error(y_test, everyone_average):,.2f})\")\n",
    "print(f\"RMSE  ${mean_squared_error(y_test, pred) ** 0.5:,.2f}   (guessing the average: ${mean_squared_error(y_test, everyone_average) ** 0.5:,.2f})\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "96ba6785",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:28:16.397454Z",
     "iopub.status.busy": "2026-12-05T03:28:16.397322Z",
     "iopub.status.idle": "2026-12-05T03:28:16.405303Z",
     "shell.execute_reply": "2026-12-05T03:28:16.404643Z"
    }
   },
   "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>predicted</th>\n",
       "      <th>actual</th>\n",
       "      <th>mae</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>tier</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>Low</th>\n",
       "      <td>600</td>\n",
       "      <td>99.12</td>\n",
       "      <td>98.98</td>\n",
       "      <td>53.10</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Medium</th>\n",
       "      <td>600</td>\n",
       "      <td>205.67</td>\n",
       "      <td>215.53</td>\n",
       "      <td>97.53</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>High</th>\n",
       "      <td>600</td>\n",
       "      <td>399.34</td>\n",
       "      <td>400.35</td>\n",
       "      <td>165.46</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Top</th>\n",
       "      <td>600</td>\n",
       "      <td>984.05</td>\n",
       "      <td>928.34</td>\n",
       "      <td>323.88</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "        customers  predicted  actual     mae\n",
       "tier                                        \n",
       "Low           600      99.12   98.98   53.10\n",
       "Medium        600     205.67  215.53   97.53\n",
       "High          600     399.34  400.35  165.46\n",
       "Top           600     984.05  928.34  323.88"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "test = X_test.assign(actual=y_test, predicted=pred, error=(pred - y_test).abs())\n",
    "test[\"tier\"] = pd.qcut(test[\"predicted\"].rank(method=\"first\"), 4,\n",
    "                       labels=[\"Low\", \"Medium\", \"High\", \"Top\"])\n",
    "\n",
    "by_tier = test.groupby(\"tier\", observed=True).agg(\n",
    "    customers=(\"actual\", \"size\"), predicted=(\"predicted\", \"mean\"),\n",
    "    actual=(\"actual\", \"mean\"), mae=(\"error\", \"mean\"))\n",
    "by_tier.round(2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "d68dfa76",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:28:16.406829Z",
     "iopub.status.busy": "2026-12-05T03:28:16.406727Z",
     "iopub.status.idle": "2026-12-05T03:28:16.412390Z",
     "shell.execute_reply": "2026-12-05T03:28:16.411848Z"
    }
   },
   "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>predicted</th>\n",
       "      <th>actual</th>\n",
       "      <th>mae</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>channel</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>Affiliate and review sites</th>\n",
       "      <td>278</td>\n",
       "      <td>427.41</td>\n",
       "      <td>386.73</td>\n",
       "      <td>154.67</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Direct</th>\n",
       "      <td>298</td>\n",
       "      <td>442.37</td>\n",
       "      <td>459.50</td>\n",
       "      <td>165.33</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Organic search</th>\n",
       "      <td>583</td>\n",
       "      <td>447.59</td>\n",
       "      <td>416.46</td>\n",
       "      <td>149.98</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Paid search</th>\n",
       "      <td>539</td>\n",
       "      <td>436.72</td>\n",
       "      <td>419.88</td>\n",
       "      <td>157.05</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Paid social</th>\n",
       "      <td>501</td>\n",
       "      <td>351.75</td>\n",
       "      <td>331.63</td>\n",
       "      <td>155.29</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Referral</th>\n",
       "      <td>201</td>\n",
       "      <td>446.29</td>\n",
       "      <td>528.45</td>\n",
       "      <td>208.07</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                            customers  predicted  actual     mae\n",
       "channel                                                         \n",
       "Affiliate and review sites        278     427.41  386.73  154.67\n",
       "Direct                            298     442.37  459.50  165.33\n",
       "Organic search                    583     447.59  416.46  149.98\n",
       "Paid search                       539     436.72  419.88  157.05\n",
       "Paid social                       501     351.75  331.63  155.29\n",
       "Referral                          201     446.29  528.45  208.07"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "test.groupby(\"channel\").agg(\n",
    "    customers=(\"actual\", \"size\"), predicted=(\"predicted\", \"mean\"),\n",
    "    actual=(\"actual\", \"mean\"), mae=(\"error\", \"mean\")).round(2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "11eba34c",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:28:16.413736Z",
     "iopub.status.busy": "2026-12-05T03:28:16.413642Z",
     "iopub.status.idle": "2026-12-05T03:28:16.416818Z",
     "shell.execute_reply": "2026-12-05T03:28:16.416275Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "|--- loyalty_signup <= 0\n",
      "|   |--- first_order_value <= 184\n",
      "|   |   |--- first_order_value <= 102\n",
      "|   |   |   |--- truncated branch of depth 6\n",
      "|   |   |--- first_order_value >  102\n",
      "|   |   |   |--- truncated branch of depth 6\n",
      "|   |--- first_order_value >  184\n",
      "|   |   |--- first_order_value <= 430\n",
      "|   |   |   |--- truncated branch of depth 6\n",
      "|   |   |--- first_order_value >  430\n",
      "|   |   |   |--- truncated branch of depth 4\n",
      "|--- loyalty_signup >  0\n",
      "|   |--- first_order_value <= 103\n",
      "|   |   |--- channel_Paid social <= 0\n",
      "|   |   |   |--- truncated branch of depth 6\n",
      "|   |   |--- channel_Paid social >  0\n",
      "|   |   |   |--- truncated branch of depth 3\n",
      "|   |--- first_order_value >  103\n",
      "|   |   |--- first_category_Tents <= 0\n",
      "|   |   |   |--- truncated branch of depth 6\n",
      "|   |   |--- first_category_Tents >  0\n",
      "|   |   |   |--- truncated branch of depth 4\n",
      "\n"
     ]
    }
   ],
   "source": [
    "names = list(model[0].get_feature_names_out())\n",
    "print(export_text(model[-1], feature_names=names, max_depth=2, decimals=0))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "26237ed8",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:28:16.418184Z",
     "iopub.status.busy": "2026-12-05T03:28:16.418099Z",
     "iopub.status.idle": "2026-12-05T03:28:16.422866Z",
     "shell.execute_reply": "2026-12-05T03:28:16.422236Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "        predicted  max_acquisition_cost\n",
      "tier                                   \n",
      "Low         99.12                 39.65\n",
      "Medium     205.67                 82.27\n",
      "High       399.34                159.74\n",
      "Top        984.05                393.62\n",
      "\n",
      "VIP welcome list: 240 customers\n",
      "their average first-year value: $1,277.12 (everyone: $410.80)\n",
      "share of the test set's first-year value: 31.1%\n"
     ]
    }
   ],
   "source": [
    "gross_margin = 0.40   # an assumption for this example: use your own\n",
    "\n",
    "caps = by_tier[[\"predicted\"]].assign(max_acquisition_cost=by_tier[\"predicted\"] * gross_margin)\n",
    "print(caps.round(2))\n",
    "\n",
    "vip = test.sort_values(\"predicted\", ascending=False, kind=\"stable\").head(len(test) // 10)\n",
    "print(f\"\\nVIP welcome list: {len(vip)} customers\")\n",
    "print(f\"their average first-year value: ${vip['actual'].mean():,.2f} (everyone: ${test['actual'].mean():,.2f})\")\n",
    "print(f\"share of the test set's first-year value: {vip['actual'].sum() / test['actual'].sum():.1%}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "308a17b5",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:28:16.424107Z",
     "iopub.status.busy": "2026-12-05T03:28:16.423987Z",
     "iopub.status.idle": "2026-12-05T03:28:16.444739Z",
     "shell.execute_reply": "2026-12-05T03:28:16.444044Z"
    }
   },
   "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>R²</th>\n",
       "      <th>MAE</th>\n",
       "      <th>RMSE</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>Average for everyone</th>\n",
       "      <td>-0.000</td>\n",
       "      <td>315.14</td>\n",
       "      <td>441.81</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Average by channel</th>\n",
       "      <td>0.013</td>\n",
       "      <td>313.06</td>\n",
       "      <td>438.99</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Average by first category</th>\n",
       "      <td>0.229</td>\n",
       "      <td>270.91</td>\n",
       "      <td>387.88</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Average by checkout type</th>\n",
       "      <td>0.299</td>\n",
       "      <td>251.85</td>\n",
       "      <td>369.95</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Linear regression</th>\n",
       "      <td>0.601</td>\n",
       "      <td>192.50</td>\n",
       "      <td>279.17</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Decision tree</th>\n",
       "      <td>0.650</td>\n",
       "      <td>159.99</td>\n",
       "      <td>261.52</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                              R²     MAE    RMSE\n",
       "Average for everyone      -0.000  315.14  441.81\n",
       "Average by channel         0.013  313.06  438.99\n",
       "Average by first category  0.229  270.91  387.88\n",
       "Average by checkout type   0.299  251.85  369.95\n",
       "Linear regression          0.601  192.50  279.17\n",
       "Decision tree              0.650  159.99  261.52"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def judge(p):\n",
    "    return {\"R²\": round(r2_score(y_test, p), 3),\n",
    "            \"MAE\": round(mean_absolute_error(y_test, p), 2),\n",
    "            \"RMSE\": round(mean_squared_error(y_test, p) ** 0.5, 2)}\n",
    "\n",
    "def average_by(columns):\n",
    "    means = X_train.assign(value=y_train).groupby(columns)[\"value\"].mean().rename(\"guess\")\n",
    "    return X_test.join(means, on=columns)[\"guess\"].fillna(y_train.mean()).values\n",
    "\n",
    "linear = make_pipeline(clone(prep), LinearRegression()).fit(X_train, y_train)\n",
    "\n",
    "comparison = pd.DataFrame({\n",
    "    \"Average for everyone\": judge(everyone_average),\n",
    "    \"Average by channel\": judge(average_by([\"channel\"])),\n",
    "    \"Average by first category\": judge(average_by([\"first_category\"])),\n",
    "    \"Average by checkout type\": judge(average_by([\"account_created\", \"loyalty_signup\"])),\n",
    "    \"Linear regression\": judge(linear.predict(X_test)),\n",
    "    \"Decision tree\": judge(pred),\n",
    "}).T\n",
    "comparison"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "76ff16e0",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:28:16.446296Z",
     "iopub.status.busy": "2026-12-05T03:28:16.446153Z",
     "iopub.status.idle": "2026-12-05T03:28:16.470228Z",
     "shell.execute_reply": "2026-12-05T03:28:16.469743Z"
    }
   },
   "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>R²</th>\n",
       "      <th>MAE</th>\n",
       "      <th>RMSE</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>Tree, first-order columns only</th>\n",
       "      <td>0.650</td>\n",
       "      <td>159.99</td>\n",
       "      <td>261.52</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Tree with 90-day columns, scored 90 days later</th>\n",
       "      <td>0.773</td>\n",
       "      <td>131.93</td>\n",
       "      <td>210.38</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Same tree, scored at the first order</th>\n",
       "      <td>0.405</td>\n",
       "      <td>188.96</td>\n",
       "      <td>340.89</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                                                   R²     MAE    RMSE\n",
       "Tree, first-order columns only                  0.650  159.99  261.52\n",
       "Tree with 90-day columns, scored 90 days later  0.773  131.93  210.38\n",
       "Same tree, scored at the first order            0.405  188.96  340.89"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "leaky_columns = categorical + numeric + after_first_order\n",
    "X_leaky = customers[leaky_columns]\n",
    "leaky_prep = make_column_transformer(\n",
    "    (OneHotEncoder(handle_unknown=\"ignore\", sparse_output=False), categorical),\n",
    "    (\"passthrough\", numeric + after_first_order),\n",
    "    verbose_feature_names_out=False,\n",
    ")\n",
    "leaky = make_pipeline(leaky_prep, DecisionTreeRegressor(random_state=42, **{\n",
    "    k.split(\"__\")[1]: v for k, v in grid.best_params_.items()}))\n",
    "leaky.fit(X_leaky.loc[X_train.index], y_train)\n",
    "\n",
    "with_90_days = X_leaky.loc[X_test.index]\n",
    "at_first_order = with_90_days.assign(orders_90d=0, spend_90d=0.0, returned_first_order=0)\n",
    "\n",
    "pd.DataFrame({\n",
    "    \"Tree, first-order columns only\": judge(pred),\n",
    "    \"Tree with 90-day columns, scored 90 days later\": judge(leaky.predict(with_90_days)),\n",
    "    \"Same tree, scored at the first order\": judge(leaky.predict(at_first_order)),\n",
    "}).T"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "51e387da",
   "metadata": {},
   "source": [
    "## Appendix: the numbers behind the charts\n",
    "\n",
    "The guides' interactive charts are drawn from the numbers computed below. Run these cells after the ones above; the last cell saves everything to `tree_charts.json`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "1f5ee293",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:28:16.471495Z",
     "iopub.status.busy": "2026-12-05T03:28:16.471396Z",
     "iopub.status.idle": "2026-12-05T03:28:16.511185Z",
     "shell.execute_reply": "2026-12-05T03:28:16.510711Z"
    }
   },
   "outputs": [],
   "source": [
    "import json\n",
    "from sklearn.inspection import permutation_importance\n",
    "from sklearn.model_selection import cross_validate\n",
    "\n",
    "best_depth = grid.best_params_[\"decisiontreeregressor__max_depth\"]\n",
    "best_leaf = grid.best_params_[\"decisiontreeregressor__min_samples_leaf\"]\n",
    "\n",
    "def tree_nodes(fitted, feature_names):\n",
    "    # every node of a fitted tree: its split rule, its customers and its average value\n",
    "    t = fitted.tree_\n",
    "    return [{\"f\": feature_names[t.feature[i]] if t.children_left[i] >= 0 else None,\n",
    "             \"t\": round(float(t.threshold[i]), 2) if t.children_left[i] >= 0 else None,\n",
    "             \"l\": int(t.children_left[i]), \"r\": int(t.children_right[i]),\n",
    "             \"n\": int(t.n_node_samples[i]), \"v\": round(float(t.value[i][0][0]), 2)}\n",
    "            for i in range(t.node_count)]\n",
    "\n",
    "charts = {\n",
    "    \"summary\": {\"n\": int(len(customers)), \"n_train\": int(len(X_train)), \"n_test\": int(len(X_test)),\n",
    "                \"mean_value\": round(float(y.mean()), 2), \"median_value\": round(float(y.median()), 2),\n",
    "                \"no_repeat\": round(float(no_repeat), 4), \"top_fifth\": round(float(top_fifth), 4),\n",
    "                \"best_depth\": best_depth, \"best_leaf\": best_leaf,\n",
    "                \"cv_r2\": round(float(grid.best_score_), 3),\n",
    "                \"leaves\": int(model[-1].get_n_leaves()), \"depth\": int(model[-1].get_depth())},\n",
    "    \"comparison\": [{\"name\": k, **v} for k, v in comparison.to_dict(\"index\").items()],\n",
    "    \"tuning\": results.to_dict(\"records\"),\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "0d492d8f",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:28:16.512539Z",
     "iopub.status.busy": "2026-12-05T03:28:16.512459Z",
     "iopub.status.idle": "2026-12-05T03:28:16.525551Z",
     "shell.execute_reply": "2026-12-05T03:28:16.525158Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "before any split: 5,600 customers, average $415.35, sum of squared errors 1,113.1 million\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>n_yes</th>\n",
       "      <th>n_no</th>\n",
       "      <th>mean_yes</th>\n",
       "      <th>mean_no</th>\n",
       "      <th>sse_yes_m</th>\n",
       "      <th>sse_no_m</th>\n",
       "      <th>sse_m</th>\n",
       "      <th>cut</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>loyalty member</th>\n",
       "      <td>1600.0</td>\n",
       "      <td>4000.0</td>\n",
       "      <td>772.43</td>\n",
       "      <td>272.52</td>\n",
       "      <td>570.9</td>\n",
       "      <td>256.6</td>\n",
       "      <td>827.5</td>\n",
       "      <td>0.2566</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>first order $99 or more</th>\n",
       "      <td>3325.0</td>\n",
       "      <td>2275.0</td>\n",
       "      <td>569.26</td>\n",
       "      <td>190.41</td>\n",
       "      <td>842.1</td>\n",
       "      <td>77.1</td>\n",
       "      <td>919.2</td>\n",
       "      <td>0.1742</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>created an account</th>\n",
       "      <td>3523.0</td>\n",
       "      <td>2077.0</td>\n",
       "      <td>544.55</td>\n",
       "      <td>196.21</td>\n",
       "      <td>889.7</td>\n",
       "      <td>64.8</td>\n",
       "      <td>954.5</td>\n",
       "      <td>0.1424</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>first order in Nov or Dec</th>\n",
       "      <td>1370.0</td>\n",
       "      <td>4230.0</td>\n",
       "      <td>338.72</td>\n",
       "      <td>440.17</td>\n",
       "      <td>221.8</td>\n",
       "      <td>880.6</td>\n",
       "      <td>1102.4</td>\n",
       "      <td>0.0096</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                            n_yes    n_no  mean_yes  mean_no  sse_yes_m  \\\n",
       "loyalty member             1600.0  4000.0    772.43   272.52      570.9   \n",
       "first order $99 or more    3325.0  2275.0    569.26   190.41      842.1   \n",
       "created an account         3523.0  2077.0    544.55   196.21      889.7   \n",
       "first order in Nov or Dec  1370.0  4230.0    338.72   440.17      221.8   \n",
       "\n",
       "                           sse_no_m   sse_m     cut  \n",
       "loyalty member                256.6   827.5  0.2566  \n",
       "first order $99 or more        77.1   919.2  0.1742  \n",
       "created an account             64.8   954.5  0.1424  \n",
       "first order in Nov or Dec     880.6  1102.4  0.0096  "
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# The math section's worked example: the first split, by hand\n",
    "root_sse = float(((y_train - y_train.mean()) ** 2).sum())\n",
    "\n",
    "def split_sse(mask):\n",
    "    left, right = y_train[mask], y_train[~mask]\n",
    "    sse_left = float(((left - left.mean()) ** 2).sum())\n",
    "    sse_right = float(((right - right.mean()) ** 2).sum())\n",
    "    return {\"n_yes\": int(len(left)), \"n_no\": int(len(right)),\n",
    "            \"mean_yes\": round(float(left.mean()), 2), \"mean_no\": round(float(right.mean()), 2),\n",
    "            \"sse_yes_m\": round(sse_left / 1e6, 1), \"sse_no_m\": round(sse_right / 1e6, 1),\n",
    "            \"sse_m\": round((sse_left + sse_right) / 1e6, 1),\n",
    "            \"cut\": round(1 - (sse_left + sse_right) / root_sse, 4)}\n",
    "\n",
    "print(f\"before any split: {len(y_train):,} customers, average ${y_train.mean():,.2f}, \"\n",
    "      f\"sum of squared errors {root_sse / 1e6:,.1f} million\")\n",
    "candidates = {\"loyalty member\": X_train[\"loyalty_signup\"] == 1,\n",
    "              \"first order $99 or more\": X_train[\"first_order_value\"] >= 99,\n",
    "              \"created an account\": X_train[\"account_created\"] == 1,\n",
    "              \"first order in Nov or Dec\": X_train[\"first_order_month\"] >= 11}\n",
    "worked = {\"root\": {\"n\": int(len(y_train)), \"mean\": round(float(y_train.mean()), 2),\n",
    "                   \"sse_m\": round(root_sse / 1e6, 1)},\n",
    "          \"splits\": {k: split_sse(v) for k, v in candidates.items()}}\n",
    "\n",
    "# every cut-off on first-order value: the search the tree runs on each column\n",
    "worked[\"order_cuts\"] = [{\"at\": c, **split_sse(X_train[\"first_order_value\"] >= c)}\n",
    "                        for c in [20, 30, 40, 50, 60, 70, 80, 90, 99, 110, 125, 150,\n",
    "                                  175, 200, 250, 300, 400, 500, 700]]\n",
    "charts[\"worked\"] = worked\n",
    "pd.DataFrame(worked[\"splits\"]).T"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "37857fca",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:28:16.526885Z",
     "iopub.status.busy": "2026-12-05T03:28:16.526793Z",
     "iopub.status.idle": "2026-12-05T03:28:16.531187Z",
     "shell.execute_reply": "2026-12-05T03:28:16.530820Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "playground sample: average $412.46\n"
     ]
    }
   ],
   "source": [
    "# The playground: 400 training customers, small enough to split by hand in the browser\n",
    "sample = X_train.assign(value=y_train).sample(400, random_state=42)\n",
    "charts[\"playground\"] = [\n",
    "    {\"fov\": round(float(r.first_order_value), 2), \"m\": int(r.first_order_month),\n",
    "     \"it\": int(r.items_in_first_order), \"loy\": int(r.loyalty_signup), \"acc\": int(r.account_created),\n",
    "     \"dis\": int(r.discount_code), \"cat\": r.first_category, \"ch\": r.channel, \"y\": round(float(r.value), 2)}\n",
    "    for r in sample.itertuples()]\n",
    "print(f\"playground sample: average ${sample['value'].mean():,.2f}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "82e72c20",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:28:16.532340Z",
     "iopub.status.busy": "2026-12-05T03:28:16.532266Z",
     "iopub.status.idle": "2026-12-05T03:28:18.549993Z",
     "shell.execute_reply": "2026-12-05T03:28:18.549507Z"
    }
   },
   "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>depth</th>\n",
       "      <th>free_train</th>\n",
       "      <th>free_cv</th>\n",
       "      <th>free_mae</th>\n",
       "      <th>leaf_train</th>\n",
       "      <th>leaf_cv</th>\n",
       "      <th>leaf_mae</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>1</td>\n",
       "      <td>0.2566</td>\n",
       "      <td>0.2526</td>\n",
       "      <td>270.50</td>\n",
       "      <td>0.2566</td>\n",
       "      <td>0.2526</td>\n",
       "      <td>270.50</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>2</td>\n",
       "      <td>0.5123</td>\n",
       "      <td>0.5026</td>\n",
       "      <td>209.32</td>\n",
       "      <td>0.5123</td>\n",
       "      <td>0.5026</td>\n",
       "      <td>209.32</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>3</td>\n",
       "      <td>0.5935</td>\n",
       "      <td>0.5607</td>\n",
       "      <td>193.82</td>\n",
       "      <td>0.5934</td>\n",
       "      <td>0.5614</td>\n",
       "      <td>193.49</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>4</td>\n",
       "      <td>0.6497</td>\n",
       "      <td>0.6210</td>\n",
       "      <td>174.36</td>\n",
       "      <td>0.6494</td>\n",
       "      <td>0.6230</td>\n",
       "      <td>173.80</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>5</td>\n",
       "      <td>0.6960</td>\n",
       "      <td>0.6577</td>\n",
       "      <td>162.71</td>\n",
       "      <td>0.6909</td>\n",
       "      <td>0.6601</td>\n",
       "      <td>163.03</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>6</td>\n",
       "      <td>0.7337</td>\n",
       "      <td>0.6772</td>\n",
       "      <td>158.66</td>\n",
       "      <td>0.7142</td>\n",
       "      <td>0.6779</td>\n",
       "      <td>158.64</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>7</td>\n",
       "      <td>0.7631</td>\n",
       "      <td>0.6752</td>\n",
       "      <td>157.96</td>\n",
       "      <td>0.7221</td>\n",
       "      <td>0.6793</td>\n",
       "      <td>158.22</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>8</td>\n",
       "      <td>0.7932</td>\n",
       "      <td>0.6582</td>\n",
       "      <td>160.84</td>\n",
       "      <td>0.7269</td>\n",
       "      <td>0.6804</td>\n",
       "      <td>157.40</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8</th>\n",
       "      <td>9</td>\n",
       "      <td>0.8228</td>\n",
       "      <td>0.6345</td>\n",
       "      <td>167.28</td>\n",
       "      <td>0.7288</td>\n",
       "      <td>0.6775</td>\n",
       "      <td>157.88</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>9</th>\n",
       "      <td>10</td>\n",
       "      <td>0.8527</td>\n",
       "      <td>0.5969</td>\n",
       "      <td>174.29</td>\n",
       "      <td>0.7295</td>\n",
       "      <td>0.6767</td>\n",
       "      <td>158.25</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>10</th>\n",
       "      <td>11</td>\n",
       "      <td>0.8806</td>\n",
       "      <td>0.5647</td>\n",
       "      <td>181.01</td>\n",
       "      <td>0.7296</td>\n",
       "      <td>0.6765</td>\n",
       "      <td>158.31</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>11</th>\n",
       "      <td>12</td>\n",
       "      <td>0.9058</td>\n",
       "      <td>0.5311</td>\n",
       "      <td>188.23</td>\n",
       "      <td>0.7296</td>\n",
       "      <td>0.6765</td>\n",
       "      <td>158.36</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>12</th>\n",
       "      <td>13</td>\n",
       "      <td>0.9296</td>\n",
       "      <td>0.5001</td>\n",
       "      <td>194.19</td>\n",
       "      <td>0.7296</td>\n",
       "      <td>0.6765</td>\n",
       "      <td>158.36</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>13</th>\n",
       "      <td>14</td>\n",
       "      <td>0.9493</td>\n",
       "      <td>0.4779</td>\n",
       "      <td>197.46</td>\n",
       "      <td>0.7296</td>\n",
       "      <td>0.6765</td>\n",
       "      <td>158.36</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>14</th>\n",
       "      <td>15</td>\n",
       "      <td>0.9649</td>\n",
       "      <td>0.4560</td>\n",
       "      <td>201.72</td>\n",
       "      <td>0.7296</td>\n",
       "      <td>0.6765</td>\n",
       "      <td>158.36</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "    depth  free_train  free_cv  free_mae  leaf_train  leaf_cv  leaf_mae\n",
       "0       1      0.2566   0.2526    270.50      0.2566   0.2526    270.50\n",
       "1       2      0.5123   0.5026    209.32      0.5123   0.5026    209.32\n",
       "2       3      0.5935   0.5607    193.82      0.5934   0.5614    193.49\n",
       "3       4      0.6497   0.6210    174.36      0.6494   0.6230    173.80\n",
       "4       5      0.6960   0.6577    162.71      0.6909   0.6601    163.03\n",
       "5       6      0.7337   0.6772    158.66      0.7142   0.6779    158.64\n",
       "6       7      0.7631   0.6752    157.96      0.7221   0.6793    158.22\n",
       "7       8      0.7932   0.6582    160.84      0.7269   0.6804    157.40\n",
       "8       9      0.8228   0.6345    167.28      0.7288   0.6775    157.88\n",
       "9      10      0.8527   0.5969    174.29      0.7295   0.6767    158.25\n",
       "10     11      0.8806   0.5647    181.01      0.7296   0.6765    158.31\n",
       "11     12      0.9058   0.5311    188.23      0.7296   0.6765    158.36\n",
       "12     13      0.9296   0.5001    194.19      0.7296   0.6765    158.36\n",
       "13     14      0.9493   0.4779    197.46      0.7296   0.6765    158.36\n",
       "14     15      0.9649   0.4560    201.72      0.7296   0.6765    158.36"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Depth against overfitting: training and cross-validated R² for every depth\n",
    "depth_curve = []\n",
    "for depth in range(1, 16):\n",
    "    row = {\"depth\": depth}\n",
    "    for leaf in [1, best_leaf]:\n",
    "        t = clone(tree).set_params(decisiontreeregressor__max_depth=depth,\n",
    "                                   decisiontreeregressor__min_samples_leaf=leaf)\n",
    "        cv = cross_validate(t, X_train, y_train, cv=folds, return_train_score=True,\n",
    "                            scoring=[\"r2\", \"neg_mean_absolute_error\"])\n",
    "        tag = \"free\" if leaf == 1 else \"leaf\"\n",
    "        row[f\"{tag}_train\"] = round(float(cv[\"train_r2\"].mean()), 4)\n",
    "        row[f\"{tag}_cv\"] = round(float(cv[\"test_r2\"].mean()), 4)\n",
    "        row[f\"{tag}_mae\"] = round(float(-cv[\"test_neg_mean_absolute_error\"].mean()), 2)\n",
    "    depth_curve.append(row)\n",
    "charts[\"depth_curve\"] = depth_curve\n",
    "pd.DataFrame(depth_curve)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "be1f8d87",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:28:18.551281Z",
     "iopub.status.busy": "2026-12-05T03:28:18.551193Z",
     "iopub.status.idle": "2026-12-05T03:28:29.203358Z",
     "shell.execute_reply": "2026-12-05T03:28:29.202975Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "full tree: 5556 leaves; alphas tried: 10 to 37,429\n",
      "best alpha: {'alpha': 544.0, 'leaves': 28, 'train': 0.7154, 'cv': 0.6722, 'mae': 164.18}\n"
     ]
    }
   ],
   "source": [
    "# Cost-complexity pruning: grow a full tree, then prune it back with a growing alpha\n",
    "full = clone(tree).fit(X_train, y_train)\n",
    "path = full[-1].cost_complexity_pruning_path(full[0].transform(X_train), y_train)\n",
    "alphas = np.unique(np.geomspace(10, path.ccp_alphas[-2], 36).round(0))\n",
    "pruning = []\n",
    "for a in alphas:\n",
    "    t = clone(tree).set_params(decisiontreeregressor__ccp_alpha=float(a))\n",
    "    cv = cross_validate(t, X_train, y_train, cv=folds, return_train_score=True,\n",
    "                        scoring=[\"r2\", \"neg_mean_absolute_error\"])\n",
    "    leaves = clone(t).fit(X_train, y_train)[-1].get_n_leaves()\n",
    "    pruning.append({\"alpha\": float(a), \"leaves\": int(leaves),\n",
    "                    \"train\": round(float(cv[\"train_r2\"].mean()), 4),\n",
    "                    \"cv\": round(float(cv[\"test_r2\"].mean()), 4),\n",
    "                    \"mae\": round(float(-cv[\"test_neg_mean_absolute_error\"].mean()), 2)})\n",
    "charts[\"pruning\"] = pruning\n",
    "best_prune = max(pruning, key=lambda r: r[\"cv\"])\n",
    "print(f\"full tree: {full[-1].get_n_leaves()} leaves; alphas tried: {alphas.min():,.0f} to {alphas.max():,.0f}\")\n",
    "print(\"best alpha:\", best_prune)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "14b10412",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:28:29.204491Z",
     "iopub.status.busy": "2026-12-05T03:28:29.204416Z",
     "iopub.status.idle": "2026-12-05T03:28:29.292345Z",
     "shell.execute_reply": "2026-12-05T03:28:29.291984Z"
    }
   },
   "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>leaves</th>\n",
       "      <th>cv_r2</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>2.0</td>\n",
       "      <td>0.1679</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>4.0</td>\n",
       "      <td>0.2494</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>8.0</td>\n",
       "      <td>0.2708</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>16.0</td>\n",
       "      <td>0.2695</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>50.0</td>\n",
       "      <td>0.2557</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8</th>\n",
       "      <td>87.0</td>\n",
       "      <td>0.2438</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   leaves   cv_r2\n",
       "1     2.0  0.1679\n",
       "2     4.0  0.2494\n",
       "3     8.0  0.2708\n",
       "4    16.0  0.2695\n",
       "6    50.0  0.2557\n",
       "8    87.0  0.2438"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# The decision surface: trees on two columns only (first-order value and month)\n",
    "two = [\"first_order_value\", \"first_order_month\"]\n",
    "grid_x = np.round(np.geomspace(15, 900, 60), 2)\n",
    "grid_m = np.arange(1, 13)\n",
    "gx, gm = np.meshgrid(grid_x, grid_m)\n",
    "cells = pd.DataFrame({\"first_order_value\": gx.ravel(), \"first_order_month\": gm.ravel()})\n",
    "surface = {}\n",
    "for depth in [1, 2, 3, 4, 6, 8]:\n",
    "    t2 = DecisionTreeRegressor(max_depth=depth, min_samples_leaf=best_leaf, random_state=42)\n",
    "    t2.fit(X_train[two], y_train)\n",
    "    surface[depth] = {\"values\": t2.predict(cells).round(0).reshape(gm.shape).tolist(),\n",
    "                      \"leaves\": int(t2.get_n_leaves()),\n",
    "                      \"cv\": round(float(cross_validate(t2, X_train[two], y_train, cv=folds,\n",
    "                                                       scoring=\"r2\")[\"test_score\"].mean()), 4)}\n",
    "dots = X_train[two].assign(value=y_train).sample(500, random_state=7)\n",
    "charts[\"surface\"] = {\"x\": grid_x.tolist(), \"m\": grid_m.tolist(), \"depths\": surface,\n",
    "                     \"dots\": [[round(float(a), 2), int(b), round(float(c), 2)] for a, b, c in dots.values]}\n",
    "pd.DataFrame({d: {\"leaves\": s[\"leaves\"], \"cv_r2\": s[\"cv\"]} for d, s in surface.items()}).T"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "b8098036",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:28:29.293506Z",
     "iopub.status.busy": "2026-12-05T03:28:29.293435Z",
     "iopub.status.idle": "2026-12-05T03:28:29.297902Z",
     "shell.execute_reply": "2026-12-05T03:28:29.297469Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "211 nodes; path: [0, 142, 174, 202, 203, 207, 209]\n"
     ]
    }
   ],
   "source": [
    "# The fitted tree, node by node, for the clickable diagram\n",
    "charts[\"tree\"] = tree_nodes(model[-1], names)\n",
    "\n",
    "# One test customer's path through the tree\n",
    "one = X_test.iloc[[int(np.argmax(pred))]]\n",
    "node_path = model[-1].decision_path(model[0].transform(one)).indices.tolist()\n",
    "charts[\"one_customer\"] = {\"row\": {k: (v.item() if hasattr(v, \"item\") else v) for k, v in one.iloc[0].items()},\n",
    "                          \"path\": node_path, \"actual\": round(float(y_test.loc[one.index[0]]), 2),\n",
    "                          \"predicted\": round(float(pred.max()), 2)}\n",
    "print(len(charts[\"tree\"]), \"nodes;\", \"path:\", node_path)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "179d1c05",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:28:29.298785Z",
     "iopub.status.busy": "2026-12-05T03:28:29.298715Z",
     "iopub.status.idle": "2026-12-05T03:28:29.431993Z",
     "shell.execute_reply": "2026-12-05T03:28:29.431562Z"
    }
   },
   "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>root</th>\n",
       "      <th>r2_depth3</th>\n",
       "      <th>r2_tuned</th>\n",
       "      <th>customer_1</th>\n",
       "      <th>customer_2</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>loyalty_signup</td>\n",
       "      <td>0.550</td>\n",
       "      <td>0.630</td>\n",
       "      <td>184.04</td>\n",
       "      <td>108.28</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>loyalty_signup</td>\n",
       "      <td>0.545</td>\n",
       "      <td>0.632</td>\n",
       "      <td>267.09</td>\n",
       "      <td>165.13</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>loyalty_signup</td>\n",
       "      <td>0.541</td>\n",
       "      <td>0.628</td>\n",
       "      <td>177.06</td>\n",
       "      <td>75.09</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>loyalty_signup</td>\n",
       "      <td>0.543</td>\n",
       "      <td>0.624</td>\n",
       "      <td>178.99</td>\n",
       "      <td>131.38</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>loyalty_signup</td>\n",
       "      <td>0.579</td>\n",
       "      <td>0.643</td>\n",
       "      <td>144.90</td>\n",
       "      <td>155.57</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>loyalty_signup</td>\n",
       "      <td>0.566</td>\n",
       "      <td>0.634</td>\n",
       "      <td>266.07</td>\n",
       "      <td>114.66</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "             root  r2_depth3  r2_tuned  customer_1  customer_2\n",
       "0  loyalty_signup      0.550     0.630      184.04      108.28\n",
       "1  loyalty_signup      0.545     0.632      267.09      165.13\n",
       "2  loyalty_signup      0.541     0.628      177.06       75.09\n",
       "3  loyalty_signup      0.543     0.624      178.99      131.38\n",
       "4  loyalty_signup      0.579     0.643      144.90      155.57\n",
       "5  loyalty_signup      0.566     0.634      266.07      114.66"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Instability: the same settings on six bootstrap samples of the training data\n",
    "rng = np.random.default_rng(42)\n",
    "examples = X_test.iloc[:5]\n",
    "boot = []\n",
    "for b in range(6):\n",
    "    rows = rng.integers(0, len(X_train), len(X_train))\n",
    "    small = clone(tree).set_params(decisiontreeregressor__max_depth=3,\n",
    "                                   decisiontreeregressor__min_samples_leaf=best_leaf)\n",
    "    small.fit(X_train.iloc[rows], y_train.iloc[rows])\n",
    "    deep = clone(model).fit(X_train.iloc[rows], y_train.iloc[rows])\n",
    "    boot.append({\"nodes\": tree_nodes(small[-1], names),\n",
    "                 \"r2_small\": round(float(r2_score(y_test, small.predict(X_test))), 3),\n",
    "                 \"r2_deep\": round(float(r2_score(y_test, deep.predict(X_test))), 3),\n",
    "                 \"examples\": deep.predict(examples).round(2).tolist()})\n",
    "charts[\"bootstrap\"] = {\"trees\": boot, \"examples_actual\": y_test.iloc[:5].round(2).tolist(),\n",
    "                       \"examples_model\": pred[:5].round(2).tolist()}\n",
    "pd.DataFrame([{\"root\": b[\"nodes\"][0][\"f\"], \"r2_depth3\": b[\"r2_small\"], \"r2_tuned\": b[\"r2_deep\"],\n",
    "               \"customer_1\": b[\"examples\"][0], \"customer_2\": b[\"examples\"][1]} for b in boot])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "f96a8639",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:28:29.433023Z",
     "iopub.status.busy": "2026-12-05T03:28:29.432950Z",
     "iopub.status.idle": "2026-12-05T03:28:29.800716Z",
     "shell.execute_reply": "2026-12-05T03:28:29.800362Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>feature</th>\n",
       "      <th>impurity</th>\n",
       "      <th>mean</th>\n",
       "      <th>std</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>loyalty_signup</td>\n",
       "      <td>0.3497</td>\n",
       "      <td>0.6169</td>\n",
       "      <td>0.0282</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>first_order_value</td>\n",
       "      <td>0.4077</td>\n",
       "      <td>0.3787</td>\n",
       "      <td>0.0203</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>first_category</td>\n",
       "      <td>0.1256</td>\n",
       "      <td>0.1656</td>\n",
       "      <td>0.0160</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>account_created</td>\n",
       "      <td>0.0364</td>\n",
       "      <td>0.0584</td>\n",
       "      <td>0.0055</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>channel</td>\n",
       "      <td>0.0351</td>\n",
       "      <td>0.0388</td>\n",
       "      <td>0.0061</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>first_order_month</td>\n",
       "      <td>0.0241</td>\n",
       "      <td>0.0193</td>\n",
       "      <td>0.0044</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>discount_code</td>\n",
       "      <td>0.0152</td>\n",
       "      <td>0.0136</td>\n",
       "      <td>0.0075</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>items_in_first_order</td>\n",
       "      <td>0.0058</td>\n",
       "      <td>0.0092</td>\n",
       "      <td>0.0032</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8</th>\n",
       "      <td>device</td>\n",
       "      <td>0.0003</td>\n",
       "      <td>0.0003</td>\n",
       "      <td>0.0004</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>9</th>\n",
       "      <td>province</td>\n",
       "      <td>0.0000</td>\n",
       "      <td>0.0000</td>\n",
       "      <td>0.0001</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                feature  impurity    mean     std\n",
       "0        loyalty_signup    0.3497  0.6169  0.0282\n",
       "1     first_order_value    0.4077  0.3787  0.0203\n",
       "2        first_category    0.1256  0.1656  0.0160\n",
       "3       account_created    0.0364  0.0584  0.0055\n",
       "4               channel    0.0351  0.0388  0.0061\n",
       "5     first_order_month    0.0241  0.0193  0.0044\n",
       "6         discount_code    0.0152  0.0136  0.0075\n",
       "7  items_in_first_order    0.0058  0.0092  0.0032\n",
       "8                device    0.0003  0.0003  0.0004\n",
       "9              province    0.0000  0.0000  0.0001"
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Two kinds of importance: how much each column cut squared error while the tree grew\n",
    "# (impurity), and how much test R² falls when the column is shuffled (permutation)\n",
    "impurity = pd.Series(model[-1].feature_importances_, index=names)\n",
    "by_column = {c: float(impurity[[n for n in names if n == c or n.startswith(c + \"_\")]].sum())\n",
    "             for c in categorical + numeric}\n",
    "perm = permutation_importance(model, X_test, y_test, scoring=\"r2\", n_repeats=20, random_state=42)\n",
    "charts[\"importance\"] = sorted(\n",
    "    [{\"feature\": c, \"impurity\": round(by_column[c], 4), \"mean\": round(float(m), 4),\n",
    "      \"std\": round(float(s), 4), \"runs\": [round(float(v), 4) for v in r]}\n",
    "     for c, m, s, r in zip(X_test.columns, perm.importances_mean, perm.importances_std, perm.importances)],\n",
    "    key=lambda d: -d[\"mean\"])\n",
    "pd.DataFrame(charts[\"importance\"])[[\"feature\", \"impurity\", \"mean\", \"std\"]]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "83240af4",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:28:29.801905Z",
     "iopub.status.busy": "2026-12-05T03:28:29.801829Z",
     "iopub.status.idle": "2026-12-05T03:28:29.850621Z",
     "shell.execute_reply": "2026-12-05T03:28:29.850272Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'with': 0.6804, 'without': 0.684, 'splits': 2, 'splits_total': 105}"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Province has no effect in this data. Does leaving it out cost anything?\n",
    "without = [c for c in categorical if c != \"province\"]\n",
    "t_without = make_pipeline(\n",
    "    make_column_transformer((OneHotEncoder(handle_unknown=\"ignore\", sparse_output=False), without),\n",
    "                            (\"passthrough\", numeric), verbose_feature_names_out=False),\n",
    "    DecisionTreeRegressor(random_state=42, max_depth=best_depth, min_samples_leaf=best_leaf))\n",
    "cv_without = cross_validate(t_without, X_train.drop(columns=\"province\"), y_train, cv=folds, scoring=\"r2\")\n",
    "province_splits = sum(1 for n in charts[\"tree\"] if n[\"f\"] and n[\"f\"].startswith(\"province_\"))\n",
    "charts[\"province\"] = {\"with\": round(float(grid.best_score_), 4),\n",
    "                      \"without\": round(float(cv_without[\"test_score\"].mean()), 4),\n",
    "                      \"splits\": province_splits,\n",
    "                      \"splits_total\": sum(1 for n in charts[\"tree\"] if n[\"f\"])}\n",
    "charts[\"province\"]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "a3f1769f",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:28:29.851690Z",
     "iopub.status.busy": "2026-12-05T03:28:29.851619Z",
     "iopub.status.idle": "2026-12-05T03:28:30.042162Z",
     "shell.execute_reply": "2026-12-05T03:28:30.041810Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>n</th>\n",
       "      <th>r2</th>\n",
       "      <th>sd</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>250</td>\n",
       "      <td>0.5007</td>\n",
       "      <td>0.0411</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>500</td>\n",
       "      <td>0.5833</td>\n",
       "      <td>0.0278</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>1000</td>\n",
       "      <td>0.6149</td>\n",
       "      <td>0.0289</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>2000</td>\n",
       "      <td>0.6518</td>\n",
       "      <td>0.0168</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>3000</td>\n",
       "      <td>0.6707</td>\n",
       "      <td>0.0224</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>4480</td>\n",
       "      <td>0.6804</td>\n",
       "      <td>0.0302</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "      n      r2      sd\n",
       "0   250  0.5007  0.0411\n",
       "1   500  0.5833  0.0278\n",
       "2  1000  0.6149  0.0289\n",
       "3  2000  0.6518  0.0168\n",
       "4  3000  0.6707  0.0224\n",
       "5  4480  0.6804  0.0302"
      ]
     },
     "execution_count": 24,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Learning curve: cross-validated R² as the training set grows\n",
    "learning = []\n",
    "for n in [250, 500, 1000, 2000, 3000, 4480]:\n",
    "    fold_r2 = []\n",
    "    for train_idx, valid_idx in folds.split(X_train):\n",
    "        sub = pd.Series(train_idx).sample(n=min(n, len(train_idx)), random_state=42).values\n",
    "        m = clone(model).fit(X_train.iloc[sub], y_train.iloc[sub])\n",
    "        fold_r2.append(r2_score(y_train.iloc[valid_idx], m.predict(X_train.iloc[valid_idx])))\n",
    "    learning.append({\"n\": n, \"r2\": round(float(np.mean(fold_r2)), 4), \"sd\": round(float(np.std(fold_r2)), 4)})\n",
    "charts[\"learning\"] = learning\n",
    "pd.DataFrame(learning)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "e1c517d6",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:28:30.043359Z",
     "iopub.status.busy": "2026-12-05T03:28:30.043286Z",
     "iopub.status.idle": "2026-12-05T03:28:30.063931Z",
     "shell.execute_reply": "2026-12-05T03:28:30.063567Z"
    }
   },
   "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>name</th>\n",
       "      <th>n</th>\n",
       "      <th>predicted</th>\n",
       "      <th>actual</th>\n",
       "      <th>mae</th>\n",
       "      <th>median_error</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>Account, not a member</td>\n",
       "      <td>851.0</td>\n",
       "      <td>360.00</td>\n",
       "      <td>350.16</td>\n",
       "      <td>151.49</td>\n",
       "      <td>106.94</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>Guest</td>\n",
       "      <td>895.0</td>\n",
       "      <td>194.63</td>\n",
       "      <td>191.43</td>\n",
       "      <td>69.03</td>\n",
       "      <td>47.64</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>Loyalty member</td>\n",
       "      <td>654.0</td>\n",
       "      <td>814.00</td>\n",
       "      <td>789.92</td>\n",
       "      <td>295.54</td>\n",
       "      <td>216.19</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                    name      n  predicted  actual     mae  median_error\n",
       "0  Account, not a member  851.0     360.00  350.16  151.49        106.94\n",
       "1                  Guest  895.0     194.63  191.43   69.03         47.64\n",
       "2         Loyalty member  654.0     814.00  789.92  295.54        216.19"
      ]
     },
     "execution_count": 25,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# The business case: predicted against actual, error by segment, tiers, value captured\n",
    "charts[\"points\"] = [[round(float(p), 2), round(float(a), 2), c, int(l), int(acc)]\n",
    "                    for p, a, c, l, acc in zip(test[\"predicted\"], test[\"actual\"], test[\"channel\"],\n",
    "                                               test[\"loyalty_signup\"], test[\"account_created\"])]\n",
    "test[\"checkout\"] = np.select([test[\"loyalty_signup\"] == 1, test[\"account_created\"] == 1],\n",
    "                             [\"Loyalty member\", \"Account, not a member\"], \"Guest\")\n",
    "segments = {}\n",
    "for col in [\"channel\", \"first_category\", \"checkout\", \"tier\"]:\n",
    "    g = test.groupby(col, observed=True).agg(n=(\"actual\", \"size\"), predicted=(\"predicted\", \"mean\"),\n",
    "                                             actual=(\"actual\", \"mean\"), mae=(\"error\", \"mean\"),\n",
    "                                             median_error=(\"error\", \"median\"))\n",
    "    segments[col] = [{\"name\": str(k), **{kk: round(float(vv), 2) for kk, vv in v.items()}}\n",
    "                     for k, v in g.to_dict(\"index\").items()]\n",
    "charts[\"segments\"] = segments\n",
    "\n",
    "order = test.sort_values(\"predicted\", ascending=False, kind=\"stable\")\n",
    "total = order[\"actual\"].sum()\n",
    "charts[\"gains\"] = [{\"pct\": p, \"captured\": round(float(order[\"actual\"].head(round(len(order) * p / 100)).sum() / total), 4)}\n",
    "                   for p in range(0, 101, 5)]\n",
    "charts[\"vip\"] = {\"n\": int(len(vip)), \"mean\": round(float(vip[\"actual\"].mean()), 2),\n",
    "                 \"all_mean\": round(float(test[\"actual\"].mean()), 2),\n",
    "                 \"share\": round(float(vip[\"actual\"].sum() / test[\"actual\"].sum()), 4)}\n",
    "charts[\"margin\"] = gross_margin\n",
    "leak_table = {\"clean\": judge(pred), \"leaky_later\": judge(leaky.predict(with_90_days)),\n",
    "              \"leaky_now\": judge(leaky.predict(at_first_order))}\n",
    "leak_imp = pd.Series(leaky[-1].feature_importances_, index=leaky[0].get_feature_names_out())\n",
    "leak_table[\"leaky_importance\"] = {c: round(float(leak_imp[c]), 4) for c in after_first_order}\n",
    "charts[\"leakage\"] = leak_table\n",
    "pd.DataFrame(segments[\"checkout\"])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "90b46ffa",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:28:30.065030Z",
     "iopub.status.busy": "2026-12-05T03:28:30.064967Z",
     "iopub.status.idle": "2026-12-05T03:28:30.076766Z",
     "shell.execute_reply": "2026-12-05T03:28:30.076369Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "saved 20 chart datasets\n"
     ]
    }
   ],
   "source": [
    "with open(\"tree_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
}
