{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "30b873f3",
   "metadata": {},
   "source": [
    "\n",
    "# Chapter 9\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3e06bca8",
   "metadata": {},
   "source": [
    "# Lab: Support Vector Machines\n",
    "In this lab, we use the `sklearn.svm` library to demonstrate the support\n",
    "vector classifier and the support vector machine.\n",
    "\n",
    "We  import some of our usual libraries."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "3973b95f",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-21T02:29:58.477582Z",
     "iopub.status.busy": "2023-08-21T02:29:58.477467Z",
     "iopub.status.idle": "2023-08-21T02:29:59.432527Z",
     "shell.execute_reply": "2023-08-21T02:29:59.432225Z"
    },
    "lines_to_next_cell": 0
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "from matplotlib.pyplot import subplots, cm\n",
    "import sklearn.model_selection as skm\n",
    "from ISLP import load_data, confusion_table\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "631b7d3d",
   "metadata": {},
   "source": [
    "We also collect the new imports\n",
    "needed for this lab."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "0161e55e",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-21T02:29:59.434432Z",
     "iopub.status.busy": "2023-08-21T02:29:59.434258Z",
     "iopub.status.idle": "2023-08-21T02:29:59.466972Z",
     "shell.execute_reply": "2023-08-21T02:29:59.466647Z"
    }
   },
   "outputs": [],
   "source": [
    "from sklearn.svm import SVC\n",
    "from ISLP.svm import plot as plot_svm\n",
    "from sklearn.metrics import RocCurveDisplay\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b397af05",
   "metadata": {},
   "source": [
    "We will use the function `RocCurveDisplay.from_estimator()` to\n",
    "produce several ROC plots, using a shorthand `roc_curve`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "7661b056",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-21T02:29:59.469128Z",
     "iopub.status.busy": "2023-08-21T02:29:59.468999Z",
     "iopub.status.idle": "2023-08-21T02:29:59.470961Z",
     "shell.execute_reply": "2023-08-21T02:29:59.470667Z"
    }
   },
   "outputs": [],
   "source": [
    "roc_curve = RocCurveDisplay.from_estimator # shorthand\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "38115984",
   "metadata": {},
   "source": [
    "## Support Vector Classifier\n",
    "\n",
    "We now use the `SupportVectorClassifier()` function (abbreviated `SVC()`) from `sklearn` to fit the support vector\n",
    "classifier for a given value of the parameter `C`.  The\n",
    "`C` argument allows us to specify the cost of a violation to\n",
    "the margin.  When the `cost` argument is small, then the margins\n",
    "will be wide and many support vectors will be on the margin or will\n",
    "violate the margin.  When the `C` argument is large, then the\n",
    "margins will be narrow and there will be few support vectors on the\n",
    "margin or violating the margin.\n",
    "\n",
    "Here we demonstrate\n",
    "the use of `SVC()` on a two-dimensional example, so that we can\n",
    "plot the resulting decision boundary. We begin by generating the\n",
    "observations, which belong to two classes, and checking whether the\n",
    "classes are linearly separable."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "46e9ab84",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-21T02:29:59.472867Z",
     "iopub.status.busy": "2023-08-21T02:29:59.472726Z",
     "iopub.status.idle": "2023-08-21T02:29:59.583508Z",
     "shell.execute_reply": "2023-08-21T02:29:59.583126Z"
    },
    "lines_to_next_cell": 0
   },
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 31212 characters]",
      "text/plain": [
       "<Figure size 800x800 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "rng = np.random.default_rng(1)\n",
    "X = rng.standard_normal((50, 2))\n",
    "y = np.array([-1]*25+[1]*25)\n",
    "X[y==1] += 1\n",
    "fig, ax = subplots(figsize=(8,8))\n",
    "ax.scatter(X[:,0],\n",
    "           X[:,1],\n",
    "           c=y,\n",
    "           cmap=cm.coolwarm);\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a9766d18",
   "metadata": {},
   "source": [
    "They are not.  We now fit the classifier."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "605ffdc0",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-21T02:29:59.585485Z",
     "iopub.status.busy": "2023-08-21T02:29:59.585317Z",
     "iopub.status.idle": "2023-08-21T02:29:59.590274Z",
     "shell.execute_reply": "2023-08-21T02:29:59.589979Z"
    },
    "lines_to_next_cell": 2
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<style>#sk-container-id-1 {color: black;}#sk-container-id-1 pre{padding: 0;}#sk-container-id-1 div.sk-toggleable {background-color: white;}#sk-container-id-1 label.sk-toggleable__label {cursor: pointer;display: block;width: 100%;margin-bottom: 0;padding: 0.3em;box-sizing: border-box;text-align: center;}#sk-container-id-1 label.sk-toggleable__label-arrow:before {content: \"▸\";float: left;margin-right: 0.25em;color: #696969;}#sk-container-id-1 label.sk-toggleable__label-arrow:hover:before {color: black;}#sk-container-id-1 div.sk-estimator:hover label.sk-toggleable__label-arrow:before {color: black;}#sk-container-id-1 div.sk-toggleable__content {max-height: 0;max-width: 0;overflow: hidden;text-align: left;background-color: #f0f8ff;}#sk-container-id-1 div.sk-toggleable__content pre {margin: 0.2em;color: black;border-radius: 0.25em;background-color: #f0f8ff;}#sk-container-id-1 input.sk-toggleable__control:checked~div.sk-toggleable__content {max-height: 200px;max-width: 100%;overflow: auto;}#sk-container-id-1 input.sk-toggleable__control:checked~label.sk-toggleable__label-arrow:before {content: \"▾\";}#sk-container-id-1 div.sk-estimator input.sk-toggleable__control:checked~label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-1 div.sk-label input.sk-toggleable__control:checked~label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-1 input.sk-hidden--visually {border: 0;clip: rect(1px 1px 1px 1px);clip: rect(1px, 1px, 1px, 1px);height: 1px;margin: -1px;overflow: hidden;padding: 0;position: absolute;width: 1px;}#sk-container-id-1 div.sk-estimator {font-family: monospace;background-color: #f0f8ff;border: 1px dotted black;border-radius: 0.25em;box-sizing: border-box;margin-bottom: 0.5em;}#sk-container-id-1 div.sk-estimator:hover {background-color: #d4ebff;}#sk-container-id-1 div.sk-parallel-item::after {content: \"\";width: 100%;border-bottom: 1px solid gray;flex-grow: 1;}#sk-container-id-1 div.sk-label:hover label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-1 div.sk-serial::before {content: \"\";position: absolute;border-left: 1px solid gray;box-sizing: border-box;top: 0;bottom: 0;left: 50%;z-index: 0;}#sk-container-id-1 div.sk-serial {display: flex;flex-direction: column;align-items: center;background-color: white;padding-right: 0.2em;padding-left: 0.2em;position: relative;}#sk-container-id-1 div.sk-item {position: relative;z-index: 1;}#sk-container-id-1 div.sk-parallel {display: flex;align-items: stretch;justify-content: center;background-color: white;position: relative;}#sk-container-id-1 div.sk-item::before, #sk-container-id-1 div.sk-parallel-item::before {content: \"\";position: absolute;border-left: 1px solid gray;box-sizing: border-box;top: 0;bottom: 0;left: 50%;z-index: -1;}#sk-container-id-1 div.sk-parallel-item {display: flex;flex-direction: column;z-index: 1;position: relative;background-color: white;}#sk-container-id-1 div.sk-parallel-item:first-child::after {align-self: flex-end;width: 50%;}#sk-container-id-1 div.sk-parallel-item:last-child::after {align-self: flex-start;width: 50%;}#sk-container-id-1 div.sk-parallel-item:only-child::after {width: 0;}#sk-container-id-1 div.sk-dashed-wrapped {border: 1px dashed gray;margin: 0 0.4em 0.5em 0.4em;box-sizing: border-box;padding-bottom: 0.4em;background-color: white;}#sk-container-id-1 div.sk-label label {font-family: monospace;font-weight: bold;display: inline-block;line-height: 1.2em;}#sk-container-id-1 div.sk-label-container {text-align: center;}#sk-container-id-1 div.sk-container {/* jupyter's `normalize.less` sets `[hidden] { display: none; }` but bootstrap.min.css set `[hidden] { display: none !important; }` so we also need the `!important` here to be able to override the default hidden behavior on the sphinx rendered scikit-learn.org. See: https://github.com/scikit-learn/scikit-learn/issues/21755 */display: inline-block !important;position: relative;}#sk-container-id-1 div.sk-text-repr-fallback {display: none;}</style><div id=\"sk-container-id-1\" class=\"sk-top-container\"><div class=\"sk-text-repr-fallback\"><pre>SVC(C=10, kernel=&#x27;linear&#x27;)</pre><b>In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. <br />On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.</b></div><div class=\"sk-container\" hidden><div class=\"sk-item\"><div class=\"sk-estimator sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-1\" type=\"checkbox\" checked><label for=\"sk-estimator-id-1\" class=\"sk-toggleable__label sk-toggleable__label-arrow\">SVC</label><div class=\"sk-toggleable__content\"><pre>SVC(C=10, kernel=&#x27;linear&#x27;)</pre></div></div></div></div></div>"
      ],
      "text/plain": [
       "SVC(C=10, kernel='linear')"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "svm_linear = SVC(C=10, kernel='linear')\n",
    "svm_linear.fit(X, y)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "16215b77",
   "metadata": {},
   "source": [
    "The support vector classifier with two features can\n",
    "be visualized by plotting values of its *decision function*.\n",
    "We have included a function for this in the `ISLP` package (inspired by a similar\n",
    "example in the `sklearn` docs)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "302a49a1",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-21T02:29:59.591976Z",
     "iopub.status.busy": "2023-08-21T02:29:59.591865Z",
     "iopub.status.idle": "2023-08-21T02:29:59.734225Z",
     "shell.execute_reply": "2023-08-21T02:29:59.733936Z"
    }
   },
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 34752 characters]",
      "text/plain": [
       "<Figure size 800x800 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "fig, ax = subplots(figsize=(8,8))\n",
    "plot_svm(X,\n",
    "         y,\n",
    "         svm_linear,\n",
    "         ax=ax)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6010e865",
   "metadata": {},
   "source": [
    "The decision\n",
    "boundary between the two classes is linear (because we used the\n",
    "argument `kernel='linear'`). The support vectors are marked with `+`\n",
    "and the remaining observations are plotted as circles.\n",
    "\n",
    "What if we instead used a smaller value of the cost parameter?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "cc1d6a13",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-21T02:29:59.735943Z",
     "iopub.status.busy": "2023-08-21T02:29:59.735816Z",
     "iopub.status.idle": "2023-08-21T02:29:59.878335Z",
     "shell.execute_reply": "2023-08-21T02:29:59.878032Z"
    },
    "lines_to_next_cell": 0
   },
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 35064 characters]",
      "text/plain": [
       "<Figure size 800x800 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "svm_linear_small = SVC(C=0.1, kernel='linear')\n",
    "svm_linear_small.fit(X, y)\n",
    "fig, ax = subplots(figsize=(8,8))\n",
    "plot_svm(X,\n",
    "         y,\n",
    "         svm_linear_small,\n",
    "         ax=ax)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "301d764d",
   "metadata": {},
   "source": [
    "With  a smaller value of the cost parameter, we\n",
    "obtain a larger number of support vectors, because the margin is now\n",
    "wider. For linear kernels, we can extract the\n",
    "coefficients of the linear decision boundary as follows:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "6133c846",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-21T02:29:59.880078Z",
     "iopub.status.busy": "2023-08-21T02:29:59.879965Z",
     "iopub.status.idle": "2023-08-21T02:29:59.882347Z",
     "shell.execute_reply": "2023-08-21T02:29:59.882070Z"
    },
    "lines_to_next_cell": 2
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[1.17303943, 0.77348227]])"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "svm_linear.coef_\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0693b3eb",
   "metadata": {},
   "source": [
    "Since the support vector machine is an estimator in `sklearn`, we\n",
    "can use the usual machinery to tune it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "9adb3793",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-21T02:29:59.883852Z",
     "iopub.status.busy": "2023-08-21T02:29:59.883749Z",
     "iopub.status.idle": "2023-08-21T02:29:59.910535Z",
     "shell.execute_reply": "2023-08-21T02:29:59.910272Z"
    },
    "lines_to_next_cell": 2
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'C': 1}"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "kfold = skm.KFold(5, \n",
    "                  random_state=0,\n",
    "                  shuffle=True)\n",
    "grid = skm.GridSearchCV(svm_linear,\n",
    "                        {'C':[0.001,0.01,0.1,1,5,10,100]},\n",
    "                        refit=True,\n",
    "                        cv=kfold,\n",
    "                        scoring='accuracy')\n",
    "grid.fit(X, y)\n",
    "grid.best_params_\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "611e76a6",
   "metadata": {},
   "source": [
    "We can easily access the cross-validation errors for each of these models\n",
    "in  `grid.cv_results_`. This prints out a lot of detail, so we\n",
    "extract the accuracy results only."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "d3ab343e",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-21T02:29:59.912005Z",
     "iopub.status.busy": "2023-08-21T02:29:59.911925Z",
     "iopub.status.idle": "2023-08-21T02:29:59.914189Z",
     "shell.execute_reply": "2023-08-21T02:29:59.913943Z"
    },
    "lines_to_next_cell": 0
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([0.46, 0.46, 0.72, 0.74, 0.74, 0.74, 0.74])"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "grid.cv_results_[('mean_test_score')]\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "41d85a2a",
   "metadata": {},
   "source": [
    "We see that  `C=1` results in the highest cross-validation\n",
    "accuracy of 0.74, though\n",
    "the accuracy is the same for several values of `C`.\n",
    "The classifier `grid.best_estimator_` can be used to predict the class\n",
    "label on a set of test observations. Let’s generate a test data set."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "6aba117e",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-21T02:29:59.915563Z",
     "iopub.status.busy": "2023-08-21T02:29:59.915487Z",
     "iopub.status.idle": "2023-08-21T02:29:59.917323Z",
     "shell.execute_reply": "2023-08-21T02:29:59.917078Z"
    }
   },
   "outputs": [],
   "source": [
    "X_test = rng.standard_normal((20, 2))\n",
    "y_test = np.array([-1]*10+[1]*10)\n",
    "X_test[y_test==1] += 1\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ddbda9de",
   "metadata": {},
   "source": [
    "Now we predict the class labels of these test observations. Here we\n",
    "use the best model selected by cross-validation in order to make the\n",
    "predictions."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "dbe7d737",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-21T02:29:59.918744Z",
     "iopub.status.busy": "2023-08-21T02:29:59.918666Z",
     "iopub.status.idle": "2023-08-21T02:29:59.925361Z",
     "shell.execute_reply": "2023-08-21T02:29:59.925039Z"
    }
   },
   "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>Truth</th>\n",
       "      <th>-1</th>\n",
       "      <th>1</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Predicted</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>-1</th>\n",
       "      <td>8</td>\n",
       "      <td>4</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>2</td>\n",
       "      <td>6</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "Truth      -1   1\n",
       "Predicted        \n",
       "-1          8   4\n",
       " 1          2   6"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "best_ = grid.best_estimator_\n",
    "y_test_hat = best_.predict(X_test)\n",
    "confusion_table(y_test_hat, y_test)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7f002ea6",
   "metadata": {},
   "source": [
    "Thus, with this value of `C`,\n",
    "70% of the test\n",
    "observations are correctly classified.  What if we had instead used\n",
    "`C=0.001`?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "ab1697c2",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-21T02:29:59.927158Z",
     "iopub.status.busy": "2023-08-21T02:29:59.927027Z",
     "iopub.status.idle": "2023-08-21T02:29:59.931558Z",
     "shell.execute_reply": "2023-08-21T02:29:59.931228Z"
    }
   },
   "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>Truth</th>\n",
       "      <th>-1</th>\n",
       "      <th>1</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Predicted</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>-1</th>\n",
       "      <td>2</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>8</td>\n",
       "      <td>10</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "Truth      -1   1\n",
       "Predicted        \n",
       "-1          2   0\n",
       " 1          8  10"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "svm_ = SVC(C=0.001,\n",
    "           kernel='linear').fit(X, y)\n",
    "y_test_hat = svm_.predict(X_test)\n",
    "confusion_table(y_test_hat, y_test)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7574703a",
   "metadata": {},
   "source": [
    "In this case 60% of test observations are correctly classified.\n",
    "\n",
    "We now consider a situation in which the two classes are linearly\n",
    "separable. Then we can find an optimal separating hyperplane using the\n",
    "`SVC()` estimator.  We first\n",
    "further separate the two classes in our simulated data so that they\n",
    "are linearly separable:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "0fd42b1e",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-21T02:29:59.933100Z",
     "iopub.status.busy": "2023-08-21T02:29:59.933001Z",
     "iopub.status.idle": "2023-08-21T02:30:00.054738Z",
     "shell.execute_reply": "2023-08-21T02:30:00.054338Z"
    }
   },
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 28136 characters]",
      "text/plain": [
       "<Figure size 800x800 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "X[y==1] += 1.9;\n",
    "fig, ax = subplots(figsize=(8,8))\n",
    "ax.scatter(X[:,0], X[:,1], c=y, cmap=cm.coolwarm);\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4bdaf415",
   "metadata": {},
   "source": [
    "Now the observations are just barely linearly separable."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "09c15299",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-21T02:30:00.056655Z",
     "iopub.status.busy": "2023-08-21T02:30:00.056526Z",
     "iopub.status.idle": "2023-08-21T02:30:00.061096Z",
     "shell.execute_reply": "2023-08-21T02:30:00.060792Z"
    }
   },
   "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>Truth</th>\n",
       "      <th>-1</th>\n",
       "      <th>1</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Predicted</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>-1</th>\n",
       "      <td>25</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>0</td>\n",
       "      <td>25</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "Truth      -1   1\n",
       "Predicted        \n",
       "-1         25   0\n",
       " 1          0  25"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "svm_ = SVC(C=1e5, kernel='linear').fit(X, y)\n",
    "y_hat = svm_.predict(X)\n",
    "confusion_table(y_hat, y)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d987eecc",
   "metadata": {},
   "source": [
    "We fit the\n",
    "support vector classifier and plot the resulting hyperplane, using a\n",
    "very large value of `C` so that no observations are\n",
    "misclassified. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "d5fd2ff9",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-21T02:30:00.062673Z",
     "iopub.status.busy": "2023-08-21T02:30:00.062585Z",
     "iopub.status.idle": "2023-08-21T02:30:00.199860Z",
     "shell.execute_reply": "2023-08-21T02:30:00.199129Z"
    },
    "lines_to_next_cell": 0
   },
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 35644 characters]",
      "text/plain": [
       "<Figure size 800x800 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "fig, ax = subplots(figsize=(8,8))\n",
    "plot_svm(X,\n",
    "         y,\n",
    "         svm_,\n",
    "         ax=ax)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0834d471",
   "metadata": {},
   "source": [
    "Indeed no training errors were made and only three support vectors were used.\n",
    "In fact, the large value of `C` also means that these three support points are *on the margin*, and define it.\n",
    "One may wonder how good the classifier could be on test data that depends on only three data points!\n",
    " We now try a smaller\n",
    "value of `C`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "39aff1b1",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-21T02:30:00.202380Z",
     "iopub.status.busy": "2023-08-21T02:30:00.202233Z",
     "iopub.status.idle": "2023-08-21T02:30:00.207886Z",
     "shell.execute_reply": "2023-08-21T02:30:00.207493Z"
    }
   },
   "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>Truth</th>\n",
       "      <th>-1</th>\n",
       "      <th>1</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Predicted</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>-1</th>\n",
       "      <td>25</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>0</td>\n",
       "      <td>25</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "Truth      -1   1\n",
       "Predicted        \n",
       "-1         25   0\n",
       " 1          0  25"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "svm_ = SVC(C=0.1, kernel='linear').fit(X, y)\n",
    "y_hat = svm_.predict(X)\n",
    "confusion_table(y_hat, y)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d0684844",
   "metadata": {},
   "source": [
    "Using `C=0.1`, we again do not misclassify any training observations, but we\n",
    "also obtain a much wider margin and make use of twelve support\n",
    "vectors. These jointly define the orientation of the decision boundary, and since there are more of them, it is more stable. It seems possible that this model will perform better on test\n",
    "data than the model with `C=1e5` (and indeed, a simple experiment with a large test set would bear this out)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "63a9d752",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-21T02:30:00.209907Z",
     "iopub.status.busy": "2023-08-21T02:30:00.209781Z",
     "iopub.status.idle": "2023-08-21T02:30:00.340803Z",
     "shell.execute_reply": "2023-08-21T02:30:00.340433Z"
    },
    "lines_to_next_cell": 2
   },
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 32776 characters]",
      "text/plain": [
       "<Figure size 800x800 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "fig, ax = subplots(figsize=(8,8))\n",
    "plot_svm(X,\n",
    "         y,\n",
    "         svm_,\n",
    "         ax=ax)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a70d84f4",
   "metadata": {},
   "source": [
    "## Support Vector Machine\n",
    "In order to fit an SVM using a non-linear kernel, we once again use\n",
    "the `SVC()`  estimator. However, now we use a different value\n",
    "of the parameter `kernel`. To fit an SVM with a polynomial\n",
    "kernel we use `kernel=\"poly\"`, and to fit an SVM with a\n",
    "radial kernel  we use\n",
    "`kernel=\"rbf\"`.  In the former case we also use the\n",
    "`degree` argument to specify a degree for the polynomial kernel\n",
    "(this is $d$ in (9.22)), and in the latter case we use\n",
    "`gamma` to specify a value of $\\gamma$ for the radial basis\n",
    "kernel  (9.24).\n",
    "\n",
    "We first generate some data with a non-linear class boundary, as follows:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "2fee8df5",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-21T02:30:00.342773Z",
     "iopub.status.busy": "2023-08-21T02:30:00.342626Z",
     "iopub.status.idle": "2023-08-21T02:30:00.345094Z",
     "shell.execute_reply": "2023-08-21T02:30:00.344774Z"
    }
   },
   "outputs": [],
   "source": [
    "X = rng.standard_normal((200, 2))\n",
    "X[:100] += 2\n",
    "X[100:150] -= 2\n",
    "y = np.array([1]*150+[2]*50)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d5c7545e",
   "metadata": {},
   "source": [
    "Plotting the data makes it clear that the class boundary is indeed non-linear."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "48f01abe",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-21T02:30:00.347053Z",
     "iopub.status.busy": "2023-08-21T02:30:00.346902Z",
     "iopub.status.idle": "2023-08-21T02:30:00.440453Z",
     "shell.execute_reply": "2023-08-21T02:30:00.440153Z"
    },
    "lines_to_next_cell": 2
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<matplotlib.collections.PathCollection at 0x28b7c65d0>"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "[encoded data, 70808 characters]",
      "text/plain": [
       "<Figure size 800x800 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "fig, ax = subplots(figsize=(8,8))\n",
    "ax.scatter(X[:,0],\n",
    "           X[:,1],\n",
    "           c=y,\n",
    "           cmap=cm.coolwarm)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7c0bc32b",
   "metadata": {},
   "source": [
    "The data is randomly split into training and testing groups. We then\n",
    "fit the training data using the `SVC()`  estimator with a\n",
    "radial kernel and $\\gamma=1$:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "4acc3246",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-21T02:30:00.442257Z",
     "iopub.status.busy": "2023-08-21T02:30:00.442156Z",
     "iopub.status.idle": "2023-08-21T02:30:00.446674Z",
     "shell.execute_reply": "2023-08-21T02:30:00.446369Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<style>#sk-container-id-2 {color: black;}#sk-container-id-2 pre{padding: 0;}#sk-container-id-2 div.sk-toggleable {background-color: white;}#sk-container-id-2 label.sk-toggleable__label {cursor: pointer;display: block;width: 100%;margin-bottom: 0;padding: 0.3em;box-sizing: border-box;text-align: center;}#sk-container-id-2 label.sk-toggleable__label-arrow:before {content: \"▸\";float: left;margin-right: 0.25em;color: #696969;}#sk-container-id-2 label.sk-toggleable__label-arrow:hover:before {color: black;}#sk-container-id-2 div.sk-estimator:hover label.sk-toggleable__label-arrow:before {color: black;}#sk-container-id-2 div.sk-toggleable__content {max-height: 0;max-width: 0;overflow: hidden;text-align: left;background-color: #f0f8ff;}#sk-container-id-2 div.sk-toggleable__content pre {margin: 0.2em;color: black;border-radius: 0.25em;background-color: #f0f8ff;}#sk-container-id-2 input.sk-toggleable__control:checked~div.sk-toggleable__content {max-height: 200px;max-width: 100%;overflow: auto;}#sk-container-id-2 input.sk-toggleable__control:checked~label.sk-toggleable__label-arrow:before {content: \"▾\";}#sk-container-id-2 div.sk-estimator input.sk-toggleable__control:checked~label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-2 div.sk-label input.sk-toggleable__control:checked~label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-2 input.sk-hidden--visually {border: 0;clip: rect(1px 1px 1px 1px);clip: rect(1px, 1px, 1px, 1px);height: 1px;margin: -1px;overflow: hidden;padding: 0;position: absolute;width: 1px;}#sk-container-id-2 div.sk-estimator {font-family: monospace;background-color: #f0f8ff;border: 1px dotted black;border-radius: 0.25em;box-sizing: border-box;margin-bottom: 0.5em;}#sk-container-id-2 div.sk-estimator:hover {background-color: #d4ebff;}#sk-container-id-2 div.sk-parallel-item::after {content: \"\";width: 100%;border-bottom: 1px solid gray;flex-grow: 1;}#sk-container-id-2 div.sk-label:hover label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-2 div.sk-serial::before {content: \"\";position: absolute;border-left: 1px solid gray;box-sizing: border-box;top: 0;bottom: 0;left: 50%;z-index: 0;}#sk-container-id-2 div.sk-serial {display: flex;flex-direction: column;align-items: center;background-color: white;padding-right: 0.2em;padding-left: 0.2em;position: relative;}#sk-container-id-2 div.sk-item {position: relative;z-index: 1;}#sk-container-id-2 div.sk-parallel {display: flex;align-items: stretch;justify-content: center;background-color: white;position: relative;}#sk-container-id-2 div.sk-item::before, #sk-container-id-2 div.sk-parallel-item::before {content: \"\";position: absolute;border-left: 1px solid gray;box-sizing: border-box;top: 0;bottom: 0;left: 50%;z-index: -1;}#sk-container-id-2 div.sk-parallel-item {display: flex;flex-direction: column;z-index: 1;position: relative;background-color: white;}#sk-container-id-2 div.sk-parallel-item:first-child::after {align-self: flex-end;width: 50%;}#sk-container-id-2 div.sk-parallel-item:last-child::after {align-self: flex-start;width: 50%;}#sk-container-id-2 div.sk-parallel-item:only-child::after {width: 0;}#sk-container-id-2 div.sk-dashed-wrapped {border: 1px dashed gray;margin: 0 0.4em 0.5em 0.4em;box-sizing: border-box;padding-bottom: 0.4em;background-color: white;}#sk-container-id-2 div.sk-label label {font-family: monospace;font-weight: bold;display: inline-block;line-height: 1.2em;}#sk-container-id-2 div.sk-label-container {text-align: center;}#sk-container-id-2 div.sk-container {/* jupyter's `normalize.less` sets `[hidden] { display: none; }` but bootstrap.min.css set `[hidden] { display: none !important; }` so we also need the `!important` here to be able to override the default hidden behavior on the sphinx rendered scikit-learn.org. See: https://github.com/scikit-learn/scikit-learn/issues/21755 */display: inline-block !important;position: relative;}#sk-container-id-2 div.sk-text-repr-fallback {display: none;}</style><div id=\"sk-container-id-2\" class=\"sk-top-container\"><div class=\"sk-text-repr-fallback\"><pre>SVC(C=1, gamma=1)</pre><b>In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. <br />On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.</b></div><div class=\"sk-container\" hidden><div class=\"sk-item\"><div class=\"sk-estimator sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-2\" type=\"checkbox\" checked><label for=\"sk-estimator-id-2\" class=\"sk-toggleable__label sk-toggleable__label-arrow\">SVC</label><div class=\"sk-toggleable__content\"><pre>SVC(C=1, gamma=1)</pre></div></div></div></div></div>"
      ],
      "text/plain": [
       "SVC(C=1, gamma=1)"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "(X_train, \n",
    " X_test,\n",
    " y_train,\n",
    " y_test) = skm.train_test_split(X,\n",
    "                                y,\n",
    "                                test_size=0.5,\n",
    "                                random_state=0)\n",
    "svm_rbf = SVC(kernel=\"rbf\", gamma=1, C=1)\n",
    "svm_rbf.fit(X_train, y_train)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b2c7e95e",
   "metadata": {},
   "source": [
    "The plot shows that the resulting SVM has a decidedly non-linear\n",
    "boundary. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "e9852a28",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-21T02:30:00.448268Z",
     "iopub.status.busy": "2023-08-21T02:30:00.448160Z",
     "iopub.status.idle": "2023-08-21T02:30:00.828511Z",
     "shell.execute_reply": "2023-08-21T02:30:00.828128Z"
    }
   },
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 51428 characters]",
      "text/plain": [
       "<Figure size 800x800 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "fig, ax = subplots(figsize=(8,8))\n",
    "plot_svm(X_train,\n",
    "         y_train,\n",
    "         svm_rbf,\n",
    "         ax=ax)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "acfa4bed",
   "metadata": {},
   "source": [
    "We can see from the figure that there are a fair number of training\n",
    "errors in this SVM fit.  If we increase the value of `C`, we\n",
    "can reduce the number of training errors. However, this comes at the\n",
    "price of a more irregular decision boundary that seems to be at risk\n",
    "of overfitting the data."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "01232fc9",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-21T02:30:00.830365Z",
     "iopub.status.busy": "2023-08-21T02:30:00.830226Z",
     "iopub.status.idle": "2023-08-21T02:30:01.132677Z",
     "shell.execute_reply": "2023-08-21T02:30:01.132224Z"
    }
   },
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 49760 characters]",
      "text/plain": [
       "<Figure size 800x800 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "svm_rbf = SVC(kernel=\"rbf\", gamma=1, C=1e5)\n",
    "svm_rbf.fit(X_train, y_train)\n",
    "fig, ax = subplots(figsize=(8,8))\n",
    "plot_svm(X_train,\n",
    "         y_train,\n",
    "         svm_rbf,\n",
    "         ax=ax)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5bc77e3f",
   "metadata": {},
   "source": [
    "We can perform cross-validation using `skm.GridSearchCV()`  to select the\n",
    "best choice of $\\gamma$ and `C` for an SVM with a radial\n",
    "kernel:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "bcbd15a4",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-21T02:30:01.134616Z",
     "iopub.status.busy": "2023-08-21T02:30:01.134486Z",
     "iopub.status.idle": "2023-08-21T02:30:01.243519Z",
     "shell.execute_reply": "2023-08-21T02:30:01.243203Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'C': 1, 'gamma': 0.5}"
      ]
     },
     "execution_count": 24,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "kfold = skm.KFold(5, \n",
    "                  random_state=0,\n",
    "                  shuffle=True)\n",
    "grid = skm.GridSearchCV(svm_rbf,\n",
    "                        {'C':[0.1,1,10,100,1000],\n",
    "                         'gamma':[0.5,1,2,3,4]},\n",
    "                        refit=True,\n",
    "                        cv=kfold,\n",
    "                        scoring='accuracy');\n",
    "grid.fit(X_train, y_train)\n",
    "grid.best_params_\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "997bbfbd",
   "metadata": {},
   "source": [
    "The best choice of parameters under five-fold CV is achieved at `C=1`\n",
    "and `gamma=0.5`, though several other values also achieve the same\n",
    "value."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "28ca551e",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-21T02:30:01.245550Z",
     "iopub.status.busy": "2023-08-21T02:30:01.245377Z",
     "iopub.status.idle": "2023-08-21T02:30:01.600896Z",
     "shell.execute_reply": "2023-08-21T02:30:01.600574Z"
    }
   },
   "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>Truth</th>\n",
       "      <th>1</th>\n",
       "      <th>2</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Predicted</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>69</td>\n",
       "      <td>6</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>6</td>\n",
       "      <td>19</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "Truth       1   2\n",
       "Predicted        \n",
       "1          69   6\n",
       "2           6  19"
      ]
     },
     "execution_count": 25,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "[encoded data, 51596 characters]",
      "text/plain": [
       "<Figure size 800x800 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "best_svm = grid.best_estimator_\n",
    "fig, ax = subplots(figsize=(8,8))\n",
    "plot_svm(X_train,\n",
    "         y_train,\n",
    "         best_svm,\n",
    "         ax=ax)\n",
    "\n",
    "y_hat_test = best_svm.predict(X_test)\n",
    "confusion_table(y_hat_test, y_test)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "48e671f4",
   "metadata": {},
   "source": [
    "With these parameters, 12% of test\n",
    "observations are misclassified by this SVM."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "eaed0a87",
   "metadata": {},
   "source": [
    "## ROC Curves\n",
    "\n",
    "SVMs and support vector classifiers output class labels for each\n",
    "observation. However, it is also possible to obtain *fitted values*\n",
    "for each observation, which are the numerical scores used to\n",
    "obtain the class labels. For instance, in the case of a support vector\n",
    "classifier, the fitted value for an observation $X= (X_1, X_2, \\ldots,\n",
    "X_p)^T$ takes the form $\\hat{\\beta}_0 + \\hat{\\beta}_1 X_1 +\n",
    "\\hat{\\beta}_2 X_2 + \\ldots + \\hat{\\beta}_p X_p$. For an SVM with a\n",
    "non-linear kernel, the equation that yields the fitted value is given\n",
    "in  (9.23). The sign of the fitted value\n",
    "determines on which side of the decision boundary the observation\n",
    "lies. Therefore, the relationship between the fitted value and the\n",
    "class prediction for a given observation is simple: if the fitted\n",
    "value exceeds zero then the observation is assigned to one class, and\n",
    "if it is less than zero then it is assigned to the other.\n",
    "By changing this threshold from zero to some positive value,\n",
    "we skew the classifications in favor of one class versus the other.\n",
    "By considering a range of these thresholds, positive and negative, we produce the ingredients for a ROC plot.\n",
    "We can access these values by calling the `decision_function()`\n",
    "method of a fitted SVM estimator.\n",
    "\n",
    "The function `ROCCurveDisplay.from_estimator()` (which we have abbreviated to `roc_curve()`) will produce a plot of a ROC curve. It takes a fitted estimator as its first argument, followed\n",
    "by a model matrix $X$ and labels $y$. The argument `name` is used in the legend,\n",
    "while `color` is used for the color of the line. Results are plotted\n",
    "on our axis object `ax`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "68ac9421",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-21T02:30:01.602740Z",
     "iopub.status.busy": "2023-08-21T02:30:01.602614Z",
     "iopub.status.idle": "2023-08-21T02:30:01.698620Z",
     "shell.execute_reply": "2023-08-21T02:30:01.698322Z"
    },
    "lines_to_next_cell": 0
   },
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 30520 characters]",
      "text/plain": [
       "<Figure size 800x800 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "fig, ax = subplots(figsize=(8,8))\n",
    "roc_curve(best_svm,\n",
    "          X_train,\n",
    "          y_train,\n",
    "          name='Training',\n",
    "          color='r',\n",
    "          ax=ax);\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0c35d32a",
   "metadata": {},
   "source": [
    " In this example, the SVM appears to provide accurate predictions. By increasing\n",
    "$\\gamma$ we can produce a more flexible fit and generate further\n",
    "improvements in accuracy."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "f79a9e0a",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-21T02:30:01.700479Z",
     "iopub.status.busy": "2023-08-21T02:30:01.700347Z",
     "iopub.status.idle": "2023-08-21T02:30:01.837479Z",
     "shell.execute_reply": "2023-08-21T02:30:01.837102Z"
    }
   },
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 30024 characters]",
      "text/plain": [
       "<Figure size 800x800 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "svm_flex = SVC(kernel=\"rbf\", \n",
    "              gamma=50,\n",
    "              C=1)\n",
    "svm_flex.fit(X_train, y_train)\n",
    "fig, ax = subplots(figsize=(8,8))\n",
    "roc_curve(svm_flex,\n",
    "          X_train,\n",
    "          y_train,\n",
    "          name='Training $\\gamma=50$',\n",
    "          color='r',\n",
    "          ax=ax);\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7bd1a22b",
   "metadata": {},
   "source": [
    "However, these ROC curves are all on the training data. We are really\n",
    "more interested in the level of prediction accuracy on the test\n",
    "data. When we compute the ROC curves on the test data, the model with\n",
    "$\\gamma=0.5$ appears to provide the most accurate results."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "id": "bdb9e503",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-21T02:30:01.839390Z",
     "iopub.status.busy": "2023-08-21T02:30:01.839243Z",
     "iopub.status.idle": "2023-08-21T02:30:01.843595Z",
     "shell.execute_reply": "2023-08-21T02:30:01.843287Z"
    }
   },
   "outputs": [],
   "source": [
    "roc_curve(svm_flex,\n",
    "          X_test,\n",
    "          y_test,\n",
    "          name='Test $\\gamma=50$',\n",
    "          color='b',\n",
    "          ax=ax)\n",
    "fig;\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8a42e924",
   "metadata": {},
   "source": [
    "Let’s look at our tuned SVM."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "329f5d2c",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-21T02:30:01.845300Z",
     "iopub.status.busy": "2023-08-21T02:30:01.845201Z",
     "iopub.status.idle": "2023-08-21T02:30:01.944073Z",
     "shell.execute_reply": "2023-08-21T02:30:01.943763Z"
    }
   },
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 37536 characters]",
      "text/plain": [
       "<Figure size 800x800 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "fig, ax = subplots(figsize=(8,8))\n",
    "for (X_, y_, c, name) in zip(\n",
    "     (X_train, X_test),\n",
    "     (y_train, y_test),\n",
    "     ('r', 'b'),\n",
    "     ('CV tuned on training',\n",
    "      'CV tuned on test')):\n",
    "    roc_curve(best_svm,\n",
    "              X_,\n",
    "              y_,\n",
    "              name=name,\n",
    "              ax=ax,\n",
    "              color=c)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bac19279",
   "metadata": {},
   "source": [
    "## SVM with Multiple Classes\n",
    "\n",
    "If the response is a factor containing more than two levels, then the\n",
    "`SVC()`  function will perform multi-class classification using\n",
    "either the one-versus-one approach (when `decision_function_shape=='ovo'`)\n",
    "or one-versus-rest {One-versus-rest is also known as one-versus-all.} (when `decision_function_shape=='ovr'`).\n",
    "We explore that setting briefly here by\n",
    "generating a third class of observations."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "id": "267e113d",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-21T02:30:01.945725Z",
     "iopub.status.busy": "2023-08-21T02:30:01.945611Z",
     "iopub.status.idle": "2023-08-21T02:30:02.034378Z",
     "shell.execute_reply": "2023-08-21T02:30:02.034069Z"
    }
   },
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 70000 characters]",
      "text/plain": [
       "<Figure size 800x800 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "rng = np.random.default_rng(123)\n",
    "X = np.vstack([X, rng.standard_normal((50, 2))])\n",
    "y = np.hstack([y, [0]*50])\n",
    "X[y==0,1] += 2\n",
    "fig, ax = subplots(figsize=(8,8))\n",
    "ax.scatter(X[:,0], X[:,1], c=y, cmap=cm.coolwarm);\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a9f4297c",
   "metadata": {},
   "source": [
    "We now fit an SVM to the data:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "64cbebd0",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-21T02:30:02.036083Z",
     "iopub.status.busy": "2023-08-21T02:30:02.035963Z",
     "iopub.status.idle": "2023-08-21T02:30:03.015535Z",
     "shell.execute_reply": "2023-08-21T02:30:03.014798Z"
    },
    "lines_to_next_cell": 0
   },
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 92936 characters]",
      "text/plain": [
       "<Figure size 800x800 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "svm_rbf_3 = SVC(kernel=\"rbf\",\n",
    "                C=10,\n",
    "                gamma=1,\n",
    "                decision_function_shape='ovo');\n",
    "svm_rbf_3.fit(X, y)\n",
    "fig, ax = subplots(figsize=(8,8))\n",
    "plot_svm(X,\n",
    "         y,\n",
    "         svm_rbf_3,\n",
    "         scatter_cmap=cm.tab10,\n",
    "         ax=ax)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "62c5d16e",
   "metadata": {},
   "source": [
    "The `sklearn.svm` library can also be used to perform support vector\n",
    "regression with a numerical response using the  estimator `SupportVectorRegression()`."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5c0824b6",
   "metadata": {},
   "source": [
    "## Application to Gene Expression Data\n",
    "\n",
    "We now examine the `Khan` data set, which consists of a number of\n",
    "tissue samples corresponding to four distinct types of small round\n",
    "blue cell tumors. For each tissue sample, gene expression measurements\n",
    "are available.  The data set consists of training data, `xtrain`\n",
    "and `ytrain`, and testing data, `xtest` and `ytest`.\n",
    "\n",
    "We examine the dimension of the data:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "id": "b6e6f12b",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-21T02:30:03.017430Z",
     "iopub.status.busy": "2023-08-21T02:30:03.017293Z",
     "iopub.status.idle": "2023-08-21T02:30:03.099156Z",
     "shell.execute_reply": "2023-08-21T02:30:03.098760Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "((63, 2308), (20, 2308))"
      ]
     },
     "execution_count": 32,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "Khan = load_data('Khan')\n",
    "Khan['xtrain'].shape, Khan['xtest'].shape\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e3fbaa58",
   "metadata": {},
   "source": [
    "This data set consists of expression measurements for 2,308\n",
    "genes. The training and test sets consist of 63 and 20\n",
    "observations, respectively.\n",
    "\n",
    "We will use a support vector approach to predict cancer subtype using\n",
    "gene expression measurements.  In this data set, there is a very\n",
    "large number of features relative to the number of observations. This\n",
    "suggests that we should use a linear kernel, because the additional\n",
    "flexibility that will result from using a polynomial or radial kernel \n",
    "is unnecessary. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "id": "273a10b2",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-21T02:30:03.101069Z",
     "iopub.status.busy": "2023-08-21T02:30:03.100881Z",
     "iopub.status.idle": "2023-08-21T02:30:03.130224Z",
     "shell.execute_reply": "2023-08-21T02:30:03.129845Z"
    }
   },
   "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>Truth</th>\n",
       "      <th>1</th>\n",
       "      <th>2</th>\n",
       "      <th>3</th>\n",
       "      <th>4</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Predicted</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>8</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>0</td>\n",
       "      <td>23</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>12</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>20</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "Truth      1   2   3   4\n",
       "Predicted               \n",
       "1          8   0   0   0\n",
       "2          0  23   0   0\n",
       "3          0   0  12   0\n",
       "4          0   0   0  20"
      ]
     },
     "execution_count": 33,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "khan_linear = SVC(kernel='linear', C=10)\n",
    "khan_linear.fit(Khan['xtrain'], Khan['ytrain'])\n",
    "confusion_table(khan_linear.predict(Khan['xtrain']),\n",
    "                Khan['ytrain'])\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "31cad43a",
   "metadata": {},
   "source": [
    "We  see that there are *no* training\n",
    "errors. In fact, this is not surprising, because the large number of\n",
    "variables relative to the number of observations implies that it is\n",
    "easy to find hyperplanes that fully separate the classes. We are more\n",
    "interested in the support vector classifier’s performance on the\n",
    "test observations."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "id": "bc3079a7",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-21T02:30:03.132111Z",
     "iopub.status.busy": "2023-08-21T02:30:03.131975Z",
     "iopub.status.idle": "2023-08-21T02:30:03.143298Z",
     "shell.execute_reply": "2023-08-21T02:30:03.142948Z"
    }
   },
   "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>Truth</th>\n",
       "      <th>1</th>\n",
       "      <th>2</th>\n",
       "      <th>3</th>\n",
       "      <th>4</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Predicted</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>3</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>0</td>\n",
       "      <td>6</td>\n",
       "      <td>2</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>4</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>5</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "Truth      1  2  3  4\n",
       "Predicted            \n",
       "1          3  0  0  0\n",
       "2          0  6  2  0\n",
       "3          0  0  4  0\n",
       "4          0  0  0  5"
      ]
     },
     "execution_count": 34,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "confusion_table(khan_linear.predict(Khan['xtest']),\n",
    "                Khan['ytest'])\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0d059312",
   "metadata": {},
   "source": [
    "We see that using `C=10` yields two test set errors on these data.\n",
    "\n"
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "cell_metadata_filter": "-all",
   "formats": "ipynb,Rmd",
   "main_language": "python"
  },
  "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.11.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
