{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "1fd56de4",
   "metadata": {},
   "source": [
    "# Part 1: Decision Tree Classifier\n",
    "\n",
    "This notebook adds the Decision Tree part of the assignment using only the biologically selected dataset `slice_1_significant_7.csv`.\n",
    "\n",
    "The task is a binary classification problem:\n",
    "\n",
    "- `0`: Healthy control\n",
    "- `1`: Exfoliative Glaucoma (XFG)\n",
    "\n",
    "I use the iris tutorial as a template for the overall workflow:\n",
    "\n",
    "- define `X` and `y`\n",
    "- split into training and test sets\n",
    "- train a `DecisionTreeClassifier`\n",
    "- evaluate the model\n",
    "- visualize the final tree\n",
    "\n",
    "Because this dataset is much smaller than iris, I also use cross-validation and a small hyperparameter search to make the model selection more defensible.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "64ed7e23",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Samples: 60\n",
      "Features: 7\n",
      "Feature names:\n",
      "['HPRA000767', 'HPRA034083', 'HPRA006876', 'HPRA019035', 'HPRA003490', 'HPRA022019', 'HPRA017192']\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "import seaborn as sns\n",
    "\n",
    "from IPython.display import display\n",
    "from sklearn.inspection import permutation_importance\n",
    "from sklearn.metrics import (\n",
    "    ConfusionMatrixDisplay,\n",
    "    accuracy_score,\n",
    "    classification_report,\n",
    ")\n",
    "from sklearn.model_selection import StratifiedKFold, cross_val_score, train_test_split\n",
    "from sklearn.tree import DecisionTreeClassifier, plot_tree\n",
    "\n",
    "sns.set_theme(style=\"whitegrid\")\n",
    "\n",
    "df = pd.read_csv(\"slice_1_significant_7.csv\")\n",
    "identifier_cols = [\"Internal LIMS ID\", \"Original ID\", \"group\"]\n",
    "feature_names = [c for c in df.columns if c not in identifier_cols]\n",
    "\n",
    "print(f\"Samples: {df.shape[0]}\")\n",
    "print(f\"Features: {len(feature_names)}\")\n",
    "print(\"Feature names:\")\n",
    "print(feature_names)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "acec5b40",
   "metadata": {},
   "source": [
    "## Step 1: Prepare Features and Targets\n",
    "\n",
    "Following the same style as the iris tutorial, I separate the predictors into `X` and the class labels into `y`.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "3c66b866",
   "metadata": {},
   "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>HPRA000767</th>\n",
       "      <th>HPRA034083</th>\n",
       "      <th>HPRA006876</th>\n",
       "      <th>HPRA019035</th>\n",
       "      <th>HPRA003490</th>\n",
       "      <th>HPRA022019</th>\n",
       "      <th>HPRA017192</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>0.352329</td>\n",
       "      <td>-0.074663</td>\n",
       "      <td>0.442451</td>\n",
       "      <td>0.210802</td>\n",
       "      <td>-0.025678</td>\n",
       "      <td>-0.923763</td>\n",
       "      <td>0.028253</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>2.184865</td>\n",
       "      <td>0.467075</td>\n",
       "      <td>1.272995</td>\n",
       "      <td>1.857599</td>\n",
       "      <td>2.709290</td>\n",
       "      <td>1.367955</td>\n",
       "      <td>0.220041</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>0.519969</td>\n",
       "      <td>-0.358698</td>\n",
       "      <td>0.124177</td>\n",
       "      <td>1.383003</td>\n",
       "      <td>1.227493</td>\n",
       "      <td>-0.128889</td>\n",
       "      <td>-0.343792</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>1.155189</td>\n",
       "      <td>0.467075</td>\n",
       "      <td>0.630671</td>\n",
       "      <td>0.080847</td>\n",
       "      <td>-0.025678</td>\n",
       "      <td>-0.416995</td>\n",
       "      <td>0.753164</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>-0.590507</td>\n",
       "      <td>-0.074663</td>\n",
       "      <td>-1.423605</td>\n",
       "      <td>-1.591214</td>\n",
       "      <td>-0.375025</td>\n",
       "      <td>-0.165849</td>\n",
       "      <td>-1.292029</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   HPRA000767  HPRA034083  HPRA006876  HPRA019035  HPRA003490  HPRA022019  \\\n",
       "0    0.352329   -0.074663    0.442451    0.210802   -0.025678   -0.923763   \n",
       "1    2.184865    0.467075    1.272995    1.857599    2.709290    1.367955   \n",
       "2    0.519969   -0.358698    0.124177    1.383003    1.227493   -0.128889   \n",
       "3    1.155189    0.467075    0.630671    0.080847   -0.025678   -0.416995   \n",
       "4   -0.590507   -0.074663   -1.423605   -1.591214   -0.375025   -0.165849   \n",
       "\n",
       "   HPRA017192  \n",
       "0    0.028253  \n",
       "1    0.220041  \n",
       "2   -0.343792  \n",
       "3    0.753164  \n",
       "4   -1.292029  "
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Target distribution:\n",
      "group\n",
      "0    30\n",
      "1    30\n",
      "Name: count, dtype: int64\n"
     ]
    }
   ],
   "source": [
    "X = df.drop(columns=identifier_cols)\n",
    "y = df[\"group\"]\n",
    "\n",
    "display(X.head())\n",
    "print(\"Target distribution:\")\n",
    "print(y.value_counts().sort_index())\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5ab9a713",
   "metadata": {},
   "source": [
    "## Step 2: Train-Test Split\n",
    "\n",
    "I use an 80/20 stratified split so both classes remain balanced in the training and test sets. The training set is used for tuning, while the test set is held back for the final evaluation.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "f3df4577",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Training set shape: (48, 7)\n",
      "Test set shape: (12, 7)\n"
     ]
    }
   ],
   "source": [
    "X_train, X_test, y_train, y_test = train_test_split(\n",
    "    X,\n",
    "    y,\n",
    "    test_size=0.2,\n",
    "    stratify=y,\n",
    "    random_state=42,\n",
    ")\n",
    "\n",
    "print(\"Training set shape:\", X_train.shape)\n",
    "print(\"Test set shape:\", X_test.shape)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c0990209",
   "metadata": {},
   "source": [
    "## Step 3: Iteratively Tune the Decision Tree\n",
    "\n",
    "The assignment asks for iterative development, so I compare multiple settings for:\n",
    "\n",
    "- `max_depth`\n",
    "- `min_samples_leaf`\n",
    "- split criterion: `gini` or `entropy`\n",
    "\n",
    "For each configuration I record:\n",
    "\n",
    "- mean 5-fold cross-validation accuracy on the training set\n",
    "- training accuracy\n",
    "- test accuracy\n",
    "- actual tree depth and number of leaves\n",
    "\n",
    "This helps distinguish a tree that genuinely generalizes from one that merely memorizes the training set.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "806946fd",
   "metadata": {},
   "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>max_depth</th>\n",
       "      <th>criterion</th>\n",
       "      <th>min_samples_leaf</th>\n",
       "      <th>cv_accuracy_mean</th>\n",
       "      <th>cv_accuracy_std</th>\n",
       "      <th>train_accuracy</th>\n",
       "      <th>test_accuracy</th>\n",
       "      <th>actual_tree_depth</th>\n",
       "      <th>n_leaves</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>21</th>\n",
       "      <td>4</td>\n",
       "      <td>entropy</td>\n",
       "      <td>1</td>\n",
       "      <td>0.775556</td>\n",
       "      <td>0.143398</td>\n",
       "      <td>0.854167</td>\n",
       "      <td>0.583333</td>\n",
       "      <td>4</td>\n",
       "      <td>6</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>27</th>\n",
       "      <td>5</td>\n",
       "      <td>entropy</td>\n",
       "      <td>1</td>\n",
       "      <td>0.755556</td>\n",
       "      <td>0.148740</td>\n",
       "      <td>0.916667</td>\n",
       "      <td>0.583333</td>\n",
       "      <td>5</td>\n",
       "      <td>7</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>34</th>\n",
       "      <td>None</td>\n",
       "      <td>entropy</td>\n",
       "      <td>2</td>\n",
       "      <td>0.755556</td>\n",
       "      <td>0.145551</td>\n",
       "      <td>0.937500</td>\n",
       "      <td>0.500000</td>\n",
       "      <td>8</td>\n",
       "      <td>11</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>22</th>\n",
       "      <td>4</td>\n",
       "      <td>entropy</td>\n",
       "      <td>2</td>\n",
       "      <td>0.753333</td>\n",
       "      <td>0.146633</td>\n",
       "      <td>0.833333</td>\n",
       "      <td>0.583333</td>\n",
       "      <td>4</td>\n",
       "      <td>6</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>10</th>\n",
       "      <td>2</td>\n",
       "      <td>entropy</td>\n",
       "      <td>2</td>\n",
       "      <td>0.751111</td>\n",
       "      <td>0.150817</td>\n",
       "      <td>0.750000</td>\n",
       "      <td>0.750000</td>\n",
       "      <td>2</td>\n",
       "      <td>3</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>15</th>\n",
       "      <td>3</td>\n",
       "      <td>entropy</td>\n",
       "      <td>1</td>\n",
       "      <td>0.733333</td>\n",
       "      <td>0.158854</td>\n",
       "      <td>0.833333</td>\n",
       "      <td>0.583333</td>\n",
       "      <td>3</td>\n",
       "      <td>5</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>17</th>\n",
       "      <td>3</td>\n",
       "      <td>entropy</td>\n",
       "      <td>4</td>\n",
       "      <td>0.733333</td>\n",
       "      <td>0.131280</td>\n",
       "      <td>0.812500</td>\n",
       "      <td>0.583333</td>\n",
       "      <td>3</td>\n",
       "      <td>5</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>28</th>\n",
       "      <td>5</td>\n",
       "      <td>entropy</td>\n",
       "      <td>2</td>\n",
       "      <td>0.733333</td>\n",
       "      <td>0.131280</td>\n",
       "      <td>0.895833</td>\n",
       "      <td>0.583333</td>\n",
       "      <td>5</td>\n",
       "      <td>7</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>33</th>\n",
       "      <td>None</td>\n",
       "      <td>entropy</td>\n",
       "      <td>1</td>\n",
       "      <td>0.733333</td>\n",
       "      <td>0.115042</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>0.583333</td>\n",
       "      <td>8</td>\n",
       "      <td>11</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>9</th>\n",
       "      <td>2</td>\n",
       "      <td>entropy</td>\n",
       "      <td>1</td>\n",
       "      <td>0.731111</td>\n",
       "      <td>0.149633</td>\n",
       "      <td>0.750000</td>\n",
       "      <td>0.750000</td>\n",
       "      <td>2</td>\n",
       "      <td>3</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>16</th>\n",
       "      <td>3</td>\n",
       "      <td>entropy</td>\n",
       "      <td>2</td>\n",
       "      <td>0.731111</td>\n",
       "      <td>0.132105</td>\n",
       "      <td>0.812500</td>\n",
       "      <td>0.583333</td>\n",
       "      <td>3</td>\n",
       "      <td>5</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>1</td>\n",
       "      <td>gini</td>\n",
       "      <td>1</td>\n",
       "      <td>0.711111</td>\n",
       "      <td>0.110889</td>\n",
       "      <td>0.791667</td>\n",
       "      <td>0.750000</td>\n",
       "      <td>1</td>\n",
       "      <td>2</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   max_depth criterion  min_samples_leaf  cv_accuracy_mean  cv_accuracy_std  \\\n",
       "21         4   entropy                 1          0.775556         0.143398   \n",
       "27         5   entropy                 1          0.755556         0.148740   \n",
       "34      None   entropy                 2          0.755556         0.145551   \n",
       "22         4   entropy                 2          0.753333         0.146633   \n",
       "10         2   entropy                 2          0.751111         0.150817   \n",
       "15         3   entropy                 1          0.733333         0.158854   \n",
       "17         3   entropy                 4          0.733333         0.131280   \n",
       "28         5   entropy                 2          0.733333         0.131280   \n",
       "33      None   entropy                 1          0.733333         0.115042   \n",
       "9          2   entropy                 1          0.731111         0.149633   \n",
       "16         3   entropy                 2          0.731111         0.132105   \n",
       "0          1      gini                 1          0.711111         0.110889   \n",
       "\n",
       "    train_accuracy  test_accuracy  actual_tree_depth  n_leaves  \n",
       "21        0.854167       0.583333                  4         6  \n",
       "27        0.916667       0.583333                  5         7  \n",
       "34        0.937500       0.500000                  8        11  \n",
       "22        0.833333       0.583333                  4         6  \n",
       "10        0.750000       0.750000                  2         3  \n",
       "15        0.833333       0.583333                  3         5  \n",
       "17        0.812500       0.583333                  3         5  \n",
       "28        0.895833       0.583333                  5         7  \n",
       "33        1.000000       0.583333                  8        11  \n",
       "9         0.750000       0.750000                  2         3  \n",
       "16        0.812500       0.583333                  3         5  \n",
       "0         0.791667       0.750000                  1         2  "
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n",
    "rows = []\n",
    "\n",
    "for max_depth in [1, 2, 3, 4, 5, None]:\n",
    "    for criterion in [\"gini\", \"entropy\"]:\n",
    "        for min_samples_leaf in [1, 2, 4]:\n",
    "            model = DecisionTreeClassifier(\n",
    "                max_depth=max_depth,\n",
    "                criterion=criterion,\n",
    "                min_samples_leaf=min_samples_leaf,\n",
    "                random_state=42,\n",
    "            )\n",
    "\n",
    "            cv_scores = cross_val_score(\n",
    "                model,\n",
    "                X_train,\n",
    "                y_train,\n",
    "                cv=cv,\n",
    "                scoring=\"accuracy\",\n",
    "            )\n",
    "\n",
    "            model.fit(X_train, y_train)\n",
    "\n",
    "            rows.append(\n",
    "                {\n",
    "                    \"max_depth\": \"None\" if max_depth is None else str(max_depth),\n",
    "                    \"criterion\": criterion,\n",
    "                    \"min_samples_leaf\": min_samples_leaf,\n",
    "                    \"cv_accuracy_mean\": cv_scores.mean(),\n",
    "                    \"cv_accuracy_std\": cv_scores.std(),\n",
    "                    \"train_accuracy\": accuracy_score(y_train, model.predict(X_train)),\n",
    "                    \"test_accuracy\": accuracy_score(y_test, model.predict(X_test)),\n",
    "                    \"actual_tree_depth\": model.get_depth(),\n",
    "                    \"n_leaves\": model.get_n_leaves(),\n",
    "                }\n",
    "            )\n",
    "\n",
    "results_df = pd.DataFrame(rows).sort_values(\n",
    "    [\"cv_accuracy_mean\", \"test_accuracy\", \"n_leaves\"],\n",
    "    ascending=[False, False, True],\n",
    ")\n",
    "\n",
    "display(results_df.head(12))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5bb8f566",
   "metadata": {},
   "source": [
    "The top row by cross-validation score is a deeper tree, but it does not perform as well on the held-out test set. That makes overfitting a real concern.\n",
    "\n",
    "A simpler model with:\n",
    "\n",
    "- `criterion=\"entropy\"`\n",
    "- `max_depth=2`\n",
    "- `min_samples_leaf=2`\n",
    "\n",
    "has nearly the same cross-validation performance, gives better test accuracy in this split, and is much easier to interpret. I therefore use that as the final tree.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "b680ad84",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 49572 characters]",
      "text/plain": [
       "<Figure size 800x500 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "depth_summary = (\n",
    "    results_df[results_df[\"criterion\"] == \"entropy\"]\n",
    "    .groupby(\"max_depth\", as_index=False)[\"cv_accuracy_mean\"]\n",
    "    .max()\n",
    ")\n",
    "\n",
    "depth_order = [\"1\", \"2\", \"3\", \"4\", \"5\", \"None\"]\n",
    "\n",
    "plt.figure(figsize=(8, 5))\n",
    "sns.lineplot(\n",
    "    data=depth_summary,\n",
    "    x=\"max_depth\",\n",
    "    y=\"cv_accuracy_mean\",\n",
    "    marker=\"o\",\n",
    "    sort=False,\n",
    ")\n",
    "plt.title(\"Cross-Validation Accuracy by Max Depth\")\n",
    "plt.xlabel(\"Max depth\")\n",
    "plt.ylabel(\"Cross-validation accuracy\")\n",
    "plt.show()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4fa2981a",
   "metadata": {},
   "source": [
    "## Step 4: Fit the Final Decision Tree\n",
    "\n",
    "The final model is deliberately shallow. This trades a small amount of flexibility for better transparency and lower overfitting risk.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "babd4532",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Final model parameters: {'criterion': 'entropy', 'max_depth': 2, 'min_samples_leaf': 2, 'random_state': 42}\n",
      "Training accuracy: 0.75\n",
      "Test accuracy: 0.75\n",
      "\n",
      "              precision    recall  f1-score   support\n",
      "\n",
      "           0      0.667     1.000     0.800         6\n",
      "           1      1.000     0.500     0.667         6\n",
      "\n",
      "    accuracy                          0.750        12\n",
      "   macro avg      0.833     0.750     0.733        12\n",
      "weighted avg      0.833     0.750     0.733        12\n",
      "\n"
     ]
    }
   ],
   "source": [
    "final_params = {\n",
    "    \"criterion\": \"entropy\",\n",
    "    \"max_depth\": 2,\n",
    "    \"min_samples_leaf\": 2,\n",
    "    \"random_state\": 42,\n",
    "}\n",
    "\n",
    "final_model = DecisionTreeClassifier(**final_params)\n",
    "final_model.fit(X_train, y_train)\n",
    "\n",
    "y_train_pred = final_model.predict(X_train)\n",
    "y_test_pred = final_model.predict(X_test)\n",
    "\n",
    "print(\"Final model parameters:\", final_params)\n",
    "print(\"Training accuracy:\", round(accuracy_score(y_train, y_train_pred), 3))\n",
    "print(\"Test accuracy:\", round(accuracy_score(y_test, y_test_pred), 3))\n",
    "print()\n",
    "print(classification_report(y_test, y_test_pred, digits=3))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f15a3232",
   "metadata": {},
   "source": [
    "## Step 5: Evaluate the Final Model\n",
    "\n",
    "The confusion matrix shows how the model handles the two classes rather than only reporting one summary number.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9e295be0",
   "metadata": {},
   "outputs": [],
   "source": [
    "ConfusionMatrixDisplay.from_predictions(\n",
    "    y_test,\n",
    "    y_test_pred,\n",
    "    display_labels=[\"Healthy\", \"XFG\"],\n",
    "    cmap=\"Blues\",\n",
    ")\n",
    "plt.title(\"Confusion Matrix for the Final Decision Tree\")\n",
    "plt.grid(False)\n",
    "plt.show()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "16aa78b9",
   "metadata": {},
   "source": [
    "## Step 6: Interpret Which Proteins the Tree Uses\n",
    "\n",
    "Decision trees only assign impurity-based importance to features that are actually used in splits. That means it is completely possible for a shallow tree to put all of its importance on only one or two proteins while the others receive zero.\n",
    "\n",
    "That is not automatically a biological conclusion. In this setting it mostly means:\n",
    "\n",
    "- the tree found that two proteins were enough for its chosen split rules\n",
    "- some proteins may contain overlapping information, so the tree only needs one of them\n",
    "- with only 60 samples, the exact split choices are unstable and can change with a different train/test split\n",
    "\n",
    "To make that limitation clearer, I look at both the tree's built-in importance values and permutation importance on the test set.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "3ab232c5",
   "metadata": {},
   "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>tree_importance</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>HPRA017192</th>\n",
       "      <td>0.675353</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>HPRA000767</th>\n",
       "      <td>0.324647</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>HPRA034083</th>\n",
       "      <td>0.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>HPRA006876</th>\n",
       "      <td>0.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>HPRA019035</th>\n",
       "      <td>0.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>HPRA003490</th>\n",
       "      <td>0.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>HPRA022019</th>\n",
       "      <td>0.000000</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "            tree_importance\n",
       "HPRA017192         0.675353\n",
       "HPRA000767         0.324647\n",
       "HPRA034083         0.000000\n",
       "HPRA006876         0.000000\n",
       "HPRA019035         0.000000\n",
       "HPRA003490         0.000000\n",
       "HPRA022019         0.000000"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "image/png": "[encoded data, 39756 characters]",
      "text/plain": [
       "<Figure size 1000x500 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "gini_importance = (\n",
    "    pd.Series(final_model.feature_importances_, index=feature_names)\n",
    "    .sort_values(ascending=False)\n",
    ")\n",
    "\n",
    "display(gini_importance.to_frame(\"tree_importance\"))\n",
    "\n",
    "plt.figure(figsize=(10, 5))\n",
    "sns.barplot(\n",
    "    x=gini_importance.values,\n",
    "    y=gini_importance.index,\n",
    "    hue=gini_importance.index,\n",
    "    dodge=False,\n",
    "    palette=\"crest\",\n",
    "    legend=False,\n",
    ")\n",
    "plt.title(\"Impurity-Based Feature Importance\")\n",
    "plt.xlabel(\"Importance\")\n",
    "plt.ylabel(\"Protein fragment\")\n",
    "plt.show()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a5ba925d",
   "metadata": {},
   "outputs": [],
   "source": [
    "perm = permutation_importance(\n",
    "    final_model,\n",
    "    X_test,\n",
    "    y_test,\n",
    "    n_repeats=50,\n",
    "    random_state=42,\n",
    ")\n",
    "\n",
    "permutation_df = (\n",
    "    pd.DataFrame(\n",
    "        {\n",
    "            \"feature\": feature_names,\n",
    "            \"permutation_importance_mean\": perm.importances_mean,\n",
    "            \"permutation_importance_std\": perm.importances_std,\n",
    "        }\n",
    "    )\n",
    "    .sort_values(\"permutation_importance_mean\", ascending=False)\n",
    ")\n",
    "\n",
    "display(permutation_df)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cbff8bf0",
   "metadata": {},
   "source": [
    "If only two proteins receive non-zero tree importance, that is therefore not necessarily weird. It is a normal consequence of a shallow greedy tree.\n",
    "\n",
    "What would be weird is claiming from this alone that the other five proteins are unimportant biologically. A single tree cannot support that conclusion, especially with a small dataset. The safer interpretation is that this particular classifier can achieve its decisions using a small subset of the available predictors.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6596d818",
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.figure(figsize=(18, 8))\n",
    "plot_tree(\n",
    "    final_model,\n",
    "    feature_names=feature_names,\n",
    "    class_names=[\"Healthy\", \"XFG\"],\n",
    "    filled=True,\n",
    "    rounded=True,\n",
    "    fontsize=10,\n",
    ")\n",
    "plt.title(\"Final Decision Tree\")\n",
    "plt.show()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cf65611c",
   "metadata": {},
   "source": [
    "## Conclusion\n",
    "\n",
    "Using only the significant seven proteins, the best final decision tree is a shallow entropy-based model with `max_depth=2` and `min_samples_leaf=2`.\n",
    "\n",
    "This is a reasonable final model because:\n",
    "\n",
    "- it is built from biologically motivated features\n",
    "- it was selected through iterative tuning rather than one-shot fitting\n",
    "- it remains interpretable\n",
    "- it avoids the strongest overfitting seen in deeper trees\n",
    "\n",
    "The fact that the tree mainly uses two proteins is not by itself a problem. It reflects how decision trees work: they only reward features that reduce impurity through actual splits. That should be interpreted as a property of this classifier, not as a definitive ranking of biological importance.\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "intro_ds",
   "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.14.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
