{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "1263abfc",
   "metadata": {},
   "source": [
    "# 🛡️ Support vector machines in Python\n",
    "\n",
    "In the chapter [Support Vector Machines](https://ai.kuleuven.be/aivooriedereen/en/support-vector-machines), a support vector machine looked for the straight boundary with the widest margin between two classes, and only a few points, the support vectors, decided where that boundary runs. This notebook shows what that looks like in code, with [scikit-learn](https://scikit-learn.org), the standard library for machine learning in Python.\n",
    "\n",
    "You will train three SVMs:\n",
    "\n",
    "1. 🍎 one that tells the apples from the pears of the chapter, with two features: width and height;\n",
    "2. ✍️ one that tells handwritten digits apart, with 784 features: one per pixel;\n",
    "3. 🌀 one with a kernel, which draws a curved boundary around the apples for the shop.\n",
    "\n",
    "The first two times, you read what the SVM learned from its **weights** and its **support vectors**. The third time, you see why you put your features on the same scale before you train.\n",
    "\n",
    "**Prior knowledge**: the chapter [Support Vector Machines](https://ai.kuleuven.be/aivooriedereen/en/support-vector-machines). You don't need any programming experience: you can run the whole notebook without changing a single line.\n",
    "\n",
    "**Estimated time**: about 30 minutes.\n",
    "\n",
    "*This notebook is part of [AI voor Iedereen](https://ai.kuleuven.be/aivooriedereen/en) (KU Leuven). The latest version is always at [ai.kuleuven.be/aivooriedereen/en/notebook/support-vector-machines](https://ai.kuleuven.be/aivooriedereen/en/notebook/support-vector-machines), and you can open it directly in [Google Colab](https://colab.research.google.com/drive/1hd6nFxcuzHSJA_bCJCaq0TlyEsNgmiUE?usp=sharing).*"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8bbd80e5",
   "metadata": {},
   "source": [
    "## 🚀 First time in a notebook?\n",
    "\n",
    "Then the short [introductory notebook](https://ai.kuleuven.be/aivooriedereen/en/notebook/python-basics) explains everything step by step. The most important things:\n",
    "\n",
    "1. **Make your own copy**: *File → Save a copy in Drive* (in the menu at the top left), and work in that copy.\n",
    "2. **Run a cell** by clicking in it and pressing **Shift+Enter**, or with the ▶ button to its left. The result appears below the cell.\n",
    "3. **Run the cells in order, from top to bottom**, because a cell uses what the cells above it made. Does something behave strangely? Choose *Runtime → Restart session* and run everything again from the top.\n",
    "\n",
    "**Prefer not to use Google?** Download [the notebook file](https://ai.kuleuven.be/aivooriedereen/notebooks/support-vector-machines.ipynb) and open it in [Jupyter](https://jupyter.org/install) or [Visual Studio Code](https://code.visualstudio.com/docs/datascience/jupyter-notebooks), with scikit-learn and matplotlib installed."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "08492714",
   "metadata": {},
   "source": [
    "## 🐍 Python in this notebook\n",
    "\n",
    "New to Python? The [introductory notebook](https://ai.kuleuven.be/aivooriedereen/en/notebook/python-basics) explains the basics: variables, lists, loops and functions. On top of those, this notebook uses:\n",
    "\n",
    "| Code | Meaning |\n",
    "| --- | --- |\n",
    "| `np.array(apples + pears)` | A **NumPy array**: a table of numbers that Python computes with all at once. `X[y == 0]` keeps only the rows where `y` is 0. |\n",
    "| `svm.fit(X, y)` | **Trains** the model on the examples in `X` (one row per example, one column per feature) and their labels in `y`. Every model in scikit-learn has this `fit`, and a `predict` that classifies new examples. |\n",
    "| `svm.coef_` | What the model learned. scikit-learn ends such names with an underscore: they only exist after `fit`. |\n",
    "| `[i for i in numbers if i > 0]` | A list built in one line: every `i` in `numbers`, but only those that pass the test after `if`. |\n",
    "| `make_pipeline(StandardScaler(), SVC())` | A **pipeline**: two steps in one model. `fit` first puts every feature on the same scale and then trains the SVM, and `predict` scales a new example the same way before it classifies it. |\n",
    "| `C = 1  # @param [...]` | A comment that Colab turns into an input next to the code, such as a dropdown menu. In other notebook programs, it is just a comment. |"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9432e934",
   "metadata": {},
   "source": [
    "## 🍎 Apples and pears\n",
    "\n",
    "These are the 19 pieces of fruit from the chapter: their width and height in millimeters. In `y`, a 0 stands for an apple and a 1 for a pear."
   ]
  },
  {
   "cell_type": "code",
   "id": "2c682848",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "from sklearn.svm import SVC\n",
    "\n",
    "# Width and height (mm) of the fruit in the chapter\n",
    "apples = [[57, 63], [74, 61], [83, 66], [62, 55], [66, 69],\n",
    "          [94, 74], [77, 75], [86, 73], [98, 83], [78, 80]]\n",
    "pears = [[61, 103], [62, 83], [74, 96], [72, 113], [78, 127],\n",
    "         [81, 114], [83, 139], [58, 81], [68, 92]]\n",
    "\n",
    "X = np.array(apples + pears)\n",
    "y = np.array([0] * len(apples) + [1] * len(pears))  # 0 = apple, 1 = pear"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "8c601650",
   "metadata": {},
   "source": [
    "`SVC`, short for *support vector classifier*, is the support vector machine of scikit-learn for classification. Without further settings, it draws a curved boundary with a kernel, as at the end of this notebook; `kernel=\"linear\"` asks for the straight boundary of the chapter. A huge `C` makes fruit inside the margin so expensive that none ends up there: the hard margin from the chapter."
   ]
  },
  {
   "cell_type": "code",
   "id": "5e865f42",
   "metadata": {},
   "source": [
    "svm = SVC(kernel=\"linear\", C=1e6, tol=1e-6)  # tol: compute a bit more precisely than the default\n",
    "svm.fit(X, y)\n",
    "\n",
    "print(\"Support vectors:\", svm.support_vectors_.astype(int).tolist())\n",
    "print(f\"Width of the margin: {2 / np.linalg.norm(svm.coef_):.1f} mm\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "fb91a51a",
   "metadata": {},
   "source": [
    "Below, a function that draws the fruit, the boundary (solid line) and the edges of the margin (dashed), with a black ring around every support vector. Inside the margin, the colors are lighter. You don't need to understand its code."
   ]
  },
  {
   "cell_type": "code",
   "id": "f5f959d1",
   "metadata": {},
   "source": [
    "def show_svm(model, X, y, names=(\"apple\", \"pear\")):\n",
    "    svm = model[-1] if hasattr(model, \"steps\") else model  # the SVM itself, also at the end of a pipeline\n",
    "    width, height = np.meshgrid(np.linspace(X[:, 0].min() - 10, X[:, 0].max() + 10, 300),\n",
    "                                np.linspace(X[:, 1].min() - 10, X[:, 1].max() + 10, 300))\n",
    "    f = model.decision_function(np.column_stack([width.ravel(), height.ravel()])).reshape(width.shape)\n",
    "    plt.figure(figsize=(5, 6))\n",
    "    plt.contourf(width, height, f, levels=[-1e9, -1, 0, 1, 1e9], colors=[\"#fecaca\", \"#fef2f2\", \"#f0fdf4\", \"#bbf7d0\"])\n",
    "    plt.contour(width, height, f, levels=[-1, 0, 1], colors=\"#334155\", linestyles=[\"--\", \"-\", \"--\"])\n",
    "    plt.scatter(*X[y == 0].T, color=\"#dc2626\", label=names[0])\n",
    "    plt.scatter(*X[y == 1].T, color=\"#22c55e\", label=names[1])\n",
    "    plt.scatter(*X[svm.support_].T, s=220, facecolors=\"none\", edgecolors=\"black\", label=\"support vector\")\n",
    "    plt.gca().set_aspect(\"equal\")\n",
    "    plt.xlabel(\"width (mm)\")\n",
    "    plt.ylabel(\"height (mm)\")\n",
    "    if svm is model and svm.kernel == \"linear\":\n",
    "        plt.title(f\"Margin: {2 / np.linalg.norm(svm.coef_):.1f} mm\")\n",
    "    else:\n",
    "        plt.title(f\"{len(svm.support_)} support vectors\")\n",
    "    plt.legend(loc=\"upper left\", bbox_to_anchor=(1.02, 1))\n",
    "    plt.show()\n",
    "\n",
    "\n",
    "show_svm(svm, X, y)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "8545ea56",
   "metadata": {},
   "source": [
    "### 🔍 What the line tells you\n",
    "\n",
    "The SVM stores its boundary as one **weight** per feature, in `svm.coef_`, plus a shift, in `svm.intercept_`. Together they give each piece of fruit a score: weight × width + weight × height + shift. A positive score means pear, a negative one apple, and the boundary is where the score is 0."
   ]
  },
  {
   "cell_type": "code",
   "id": "e76c02a1",
   "metadata": {},
   "source": [
    "w_width, w_height = svm.coef_[0]\n",
    "shift = svm.intercept_[0]\n",
    "print(f\"Weight of the width:  {w_width:+.3f} per mm\")\n",
    "print(f\"Weight of the height: {w_height:+.3f} per mm\")\n",
    "print(f\"Shift:                {shift:+.2f}\")\n",
    "\n",
    "new_fruit = [70, 85]  # width and height in mm\n",
    "print()\n",
    "print(\"Score of a fruit of 70 by 85 mm:\", round(svm.decision_function([new_fruit])[0], 2))\n",
    "print(\"Prediction:\", \"pear\" if svm.predict([new_fruit])[0] == 1 else \"apple\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "0fc8d47b",
   "metadata": {},
   "source": [
    "The weight of the height is positive: the taller, the more pear. The weight of the width is negative: the wider, the more apple. The two are about equally large, so the SVM mostly looks at how much taller than wide a piece of fruit is. The fruit of 70 by 85 mm scores just above 0: a pear, but only just.\n",
    "\n",
    "**Try it yourself**: change the numbers of an apple far from the boundary, such as `[98, 83]`, and run the cells again from 🍎 Apples and pears. The boundary stays where it is. Now change a support vector, such as `[78, 80]`: the boundary turns."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "aecfea14",
   "metadata": {},
   "source": [
    "### 🎚️ A round pear and the strictness C\n",
    "\n",
    "Now the round pear of the chapter joins the others: 60 mm wide and 72 mm high. With a hard margin, that one pear squeezes the margin from 12.4 to 5.1 mm. A lower `C` lets fruit inside the margin, and even onto the wrong side, at a cost. Pick a value for `C` (in Colab, with the menu next to the code) and run the cell."
   ]
  },
  {
   "cell_type": "code",
   "id": "5c5fb042",
   "metadata": {},
   "source": [
    "C = 1000000  # @param [1000000, 0.05, 0.03, 0.002] {type:\"raw\"}\n",
    "\n",
    "X_round = np.vstack([X, [60, 72]])\n",
    "y_round = np.append(y, 1)  # the round pear is a pear\n",
    "\n",
    "soft = SVC(kernel=\"linear\", C=C, tol=1e-6)\n",
    "soft.fit(X_round, y_round)\n",
    "\n",
    "score = soft.decision_function(X_round)\n",
    "own_side = np.where(y_round == 1, score, -score)  # 1 or more: on or beyond its edge of the margin; below 0: wrong side\n",
    "print(\"Inside the margin:\", np.sum((own_side >= 0) & (own_side < 0.999)))\n",
    "print(\"On the wrong side:\", np.sum(own_side < 0))\n",
    "show_svm(soft, X_round, y_round)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "f2f9076e",
   "metadata": {},
   "source": [
    "**Try it yourself**: at `C = 0.05`, the round pear lies inside the margin, which widens to 7.8 mm. At `C = 0.03`, the SVM gives up on it: the round pear ends up on the wrong side, and the margin is back to 12.4 mm. At `C = 0.002`, the margin is 19.7 mm wide, with six pieces of fruit inside it.\n",
    "\n",
    "These values are much smaller than in the demo of the chapter, which first rescales the fruit. `C` depends on the units of the features: in millimeters, the weights are small numbers, so the `C` that weighs the fines against them has to be small too. One more reason to put your features on a common scale first, and to choose `C` by testing on fruit the SVM didn't see."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "da666ec7",
   "metadata": {},
   "source": [
    "## ✍️ Handwritten digits\n",
    "\n",
    "An image is also just a list of numbers. Every image in [MNIST](https://en.wikipedia.org/wiki/MNIST_database), a classic collection of handwritten digits, has 28 × 28 pixels: 784 numbers from 0 (white) to 255 (black). To an SVM, such an image is a point with 784 features instead of 2.\n",
    "\n",
    "The cell below downloads a sample of 5,000 images, 500 of every digit (less than 1 MB), and shows the first ten.\n",
    "\n",
    "*The images are a sample of the [MNIST database](http://yann.lecun.com/exdb/mnist/) by Yann LeCun, Corinna Cortes and Christopher J. C. Burges.*"
   ]
  },
  {
   "cell_type": "code",
   "id": "edb84f53",
   "metadata": {},
   "source": [
    "import io\n",
    "import urllib.request\n",
    "\n",
    "DATA_URL = \"https://ai.kuleuven.be/aivooriedereen/notebooks/data/\"\n",
    "with urllib.request.urlopen(DATA_URL + \"mnist-sample.npz\") as response:\n",
    "    mnist = np.load(io.BytesIO(response.read()))\n",
    "images, labels = mnist[\"images\"], mnist[\"labels\"]\n",
    "print(len(images), \"images of\", images.shape[1], \"by\", images.shape[2], \"pixels\")\n",
    "\n",
    "fig, axes = plt.subplots(1, 10, figsize=(10, 1.4))\n",
    "for ax, image, label in zip(axes, images, labels):\n",
    "    ax.imshow(image, cmap=\"gray_r\")\n",
    "    ax.set_title(label)\n",
    "    ax.axis(\"off\")\n",
    "plt.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "ffb78153",
   "metadata": {},
   "source": [
    "### 0️⃣ 1️⃣ Two digits\n",
    "\n",
    "Pick two digits, and train an SVM that tells them apart: the same `SVC` as for the fruit, with a straight boundary. A quarter of their images stays aside as a test: images the SVM never sees during training. A low `C` gives a soft margin, which makes the weights below easier to read."
   ]
  },
  {
   "cell_type": "code",
   "id": "f97ccb5d",
   "metadata": {},
   "source": [
    "from sklearn.model_selection import train_test_split\n",
    "\n",
    "digit_a = 0  # @param {type:\"integer\"}\n",
    "digit_b = 1  # @param {type:\"integer\"}\n",
    "\n",
    "chosen = (labels == digit_a) | (labels == digit_b)\n",
    "X_digits = images[chosen].reshape(-1, 28 * 28) / 255  # every image as one row of 784 numbers between 0 and 1\n",
    "y_digits = labels[chosen]\n",
    "X_train, X_test, y_train, y_test = train_test_split(X_digits, y_digits, test_size=0.25, random_state=0)\n",
    "\n",
    "digit_svm = SVC(kernel=\"linear\", C=0.01)\n",
    "digit_svm.fit(X_train, y_train)\n",
    "print(f\"Correct on the test images: {digit_svm.score(X_test, y_test):.1%}\")\n",
    "print(\"Support vectors:\", len(digit_svm.support_), \"of the\", len(X_train), \"training images\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "04bccdad",
   "metadata": {},
   "source": [
    "### 🖼️ The weights as an image\n",
    "\n",
    "The SVM gives every pixel a weight. Put each weight back on its own pixel, and the weights form an image themselves: red pixels count for one digit, blue pixels for the other, and white pixels hardly matter."
   ]
  },
  {
   "cell_type": "code",
   "id": "e2b71aa4",
   "metadata": {},
   "source": [
    "low, high = digit_svm.classes_\n",
    "weights = digit_svm.coef_.reshape(28, 28)\n",
    "largest = np.abs(weights).max()\n",
    "\n",
    "plt.imshow(weights, cmap=\"RdBu_r\", vmin=-largest, vmax=largest)\n",
    "plt.title(f\"Red: more like a {high}. Blue: more like a {low}.\")\n",
    "plt.colorbar()\n",
    "plt.axis(\"off\")\n",
    "plt.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "cd01cf08",
   "metadata": {},
   "source": [
    "For zeros against ones, the middle is red: that is where a one has its stroke, and a zero its hole. Around it, the image is blue, where a zero has its ring. That is what makes a linear model so readable: for every input, you can see how much it counts and in which direction."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "09baef96",
   "metadata": {},
   "source": [
    "### 📊 The divide in one picture\n",
    "\n",
    "To classify an image, the SVM adds up weight × pixel for all 784 pixels, plus a shift: one score per image, as for the fruit. Below 0, it is one digit; above 0, the other. The histogram below shows the scores of the test images, with the boundary at 0 and the edges of the margin at −1 and 1."
   ]
  },
  {
   "cell_type": "code",
   "id": "9d99e556",
   "metadata": {},
   "source": [
    "test_score = digit_svm.decision_function(X_test)\n",
    "plt.figure(figsize=(8, 3))\n",
    "for digit, color in zip(digit_svm.classes_, [\"#2563eb\", \"#dc2626\"]):\n",
    "    plt.hist(test_score[y_test == digit], bins=30, color=color, alpha=0.6, label=f\"test images of a {digit}\")\n",
    "plt.axvline(0, color=\"black\", label=\"boundary\")\n",
    "plt.axvline(-1, color=\"black\", linestyle=\"--\", label=\"edges of the margin\")\n",
    "plt.axvline(1, color=\"black\", linestyle=\"--\")\n",
    "plt.xlabel(\"score\")\n",
    "plt.ylabel(\"number of test images\")\n",
    "plt.legend(loc=\"upper left\", bbox_to_anchor=(1.02, 1))\n",
    "plt.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "15fc74d5",
   "metadata": {},
   "source": [
    "The zeros and the ones form two hills, each on its own side of the margin. The few test images between the dashed lines lie inside the margin: borderline cases, like the support vectors below."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c65357ca",
   "metadata": {},
   "source": [
    "### 🛡️ The support vectors\n",
    "\n",
    "The support vectors are the borderline cases among the training images: the zeros that look most like a one, and the ones that look most like a zero. The cell below shows them, those closest to the boundary first."
   ]
  },
  {
   "cell_type": "code",
   "id": "7a8c34f7",
   "metadata": {},
   "source": [
    "train_score = digit_svm.decision_function(X_train)\n",
    "for digit in digit_svm.classes_:\n",
    "    support = [i for i in digit_svm.support_ if y_train[i] == digit]\n",
    "    support = sorted(support, key=lambda i: abs(train_score[i]))  # closest to the boundary first\n",
    "    fig, axes = plt.subplots(1, 10, figsize=(10, 1.4))\n",
    "    for ax in axes:\n",
    "        ax.axis(\"off\")\n",
    "    for ax, i in zip(axes, support):\n",
    "        ax.imshow(X_train[i].reshape(28, 28), cmap=\"gray_r\")\n",
    "    fig.suptitle(f\"Support vectors that are a {digit}\")\n",
    "    plt.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "bfae4653",
   "metadata": {},
   "source": [
    "**Try it yourself**\n",
    "\n",
    "- Pick two other digits, such as 3 and 8, or 4 and 9, and run the cells again from 0️⃣ 1️⃣ Two digits. Which pixels does the SVM look at now, does it need more support vectors, and do the two hills in the histogram still stay apart?\n",
    "- Which two digits are the hardest to tell apart? Compare the score on the test images for a few pairs.\n",
    "- Set `C=1` for zeros and ones: the SVM keeps fewer support vectors, and the image of the weights gets noisier."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e5960cc8",
   "metadata": {},
   "source": [
    "## 🌀 A curved boundary, and why you scale\n",
    "\n",
    "Not every problem has a straight boundary. In the chapter, a shop only takes nice, medium-sized apples: not too small, not too big, not too flat and not too tall. With width and height as features, the apples for the shop lie as an island among the apples for juice, and no straight line separates them.\n",
    "\n",
    "Without `kernel=\"linear\"`, an `SVC` uses the RBF kernel of the chapter: every support vector raises or lowers the landscape around it, and `gamma` (γ) sets how wide each of those hills is. The pipeline first puts both features on the same scale; below, you see why. Pick a value for `gamma` and run the cell."
   ]
  },
  {
   "cell_type": "code",
   "id": "7d29e38a",
   "metadata": {},
   "source": [
    "from sklearn.pipeline import make_pipeline\n",
    "from sklearn.preprocessing import StandardScaler\n",
    "\n",
    "gamma = 1  # @param [0.1, 1, 10, 100] {type:\"raw\"}\n",
    "\n",
    "# Width and height (mm) of the apples in the kernel demo of the chapter\n",
    "juice = [[93, 73], [93, 79], [89, 84], [86, 89], [78, 92], [72, 87], [67, 86], [65, 83], [61, 79],\n",
    "         [61, 73], [61, 66], [62, 59], [64, 55], [75, 57], [78, 55], [84, 58], [88, 61], [90, 67]]\n",
    "shop = [[75, 68], [77, 71], [70, 73], [71, 73], [70, 75], [80, 74], [82, 71],\n",
    "        [74, 76], [81, 74], [79, 77], [71, 68], [80, 69], [76, 70], [82, 74]]\n",
    "X_island = np.array(juice + shop)\n",
    "y_island = np.array([0] * len(juice) + [1] * len(shop))  # 0 = juice, 1 = shop\n",
    "\n",
    "island_svm = make_pipeline(StandardScaler(), SVC(kernel=\"rbf\", gamma=gamma, C=1e6))\n",
    "island_svm.fit(X_island, y_island)\n",
    "show_svm(island_svm, X_island, y_island, names=(\"juice\", \"shop\"))"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "9178b221",
   "metadata": {},
   "source": [
    "**Try it yourself**: at γ = 0.1, a handful of support vectors is enough for one smooth, round island. The larger γ, the narrower every hill, and the more apples become support vectors. At γ = 100, every apple is one, and every shop apple gets a small island of its own: overfitting, as with *k* = 1 for nearest neighbors. You choose γ, like `C`, by testing on apples the SVM didn't see. (The numbers differ a little from the demo in the chapter, which scales the apples in its own way.) And note: there is no weight per feature to read any more, because the boundary is no longer a line."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5210fe14",
   "metadata": {},
   "source": [
    "### 📏 Millimeters or centimeters?\n",
    "\n",
    "An RBF kernel measures how far apart apples are, so the units of the features matter. Suppose the machine had measured the height in centimeters instead of millimeters. The apples stay the same; only the numbers change. Compare an SVM without and with the scaler, both with the default settings of `SVC`:"
   ]
  },
  {
   "cell_type": "code",
   "id": "36ec2382",
   "metadata": {},
   "source": [
    "X_cm = X_island * [1, 0.1]  # width still in mm, height now in cm\n",
    "\n",
    "without_scaler = SVC().fit(X_cm, y_island)\n",
    "with_scaler = make_pipeline(StandardScaler(), SVC()).fit(X_cm, y_island)\n",
    "print(f\"Without the scaler: {without_scaler.score(X_cm, y_island):.0%} of the apples right\")\n",
    "print(f\"With the scaler:    {with_scaler.score(X_cm, y_island):.0%} of the apples right\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "18b12647",
   "metadata": {},
   "source": [
    "In centimeters, the heights only range from 5.5 to 9.2, against widths from 61 to 93 millimeters. To the kernel, all apples then lie close together in height, so it hardly sees the difference between tall and flat apples, and the SVM calls every apple juice: right for 18 of the 32. `StandardScaler` first gives every feature a mean of 0 and a standard deviation of 1, so the units you measured in no longer matter. It also makes the weights of a linear SVM comparable between features, as the chapter explained."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9ec196a9",
   "metadata": {},
   "source": [
    "## 🧰 An SVM for your own problem\n",
    "\n",
    "All three SVMs followed the same recipe:\n",
    "\n",
    "1. Put your examples in a table `X`, one row per example and one column per feature, and their labels in `y`.\n",
    "2. Put a scaler in front of the SVM, `make_pipeline(StandardScaler(), SVC(kernel=\"linear\"))`, and train with `fit(X, y)`. The apples and pears could do without, because both features were in millimeters, and so could the digits, whose pixels you divided by 255.\n",
    "3. Read what it learned: the weights in `coef_` and the support vectors in `support_` (in a pipeline: `model[-1].coef_`).\n",
    "\n",
    "Choose `C`, and for a kernel also `gamma`, on data the SVM didn't train on, for example with cross-validation. A straight boundary keeps one weight per feature to read; a kernel bends the boundary, but those weights are gone.\n",
    "\n",
    "In scikit-learn, an SVM is one model among many: `KNeighborsClassifier` and `DecisionTreeClassifier` have the same `fit` and `predict`, so you can try several on the same `X` and `y`."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2b4d8eca",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "*By [Thomas Winters](https://thomaswinters.be) for [AI voor Iedereen](https://ai.kuleuven.be/aivooriedereen/en), KU Leuven. The latest version of this notebook: [ai.kuleuven.be/aivooriedereen/en/notebook/support-vector-machines](https://ai.kuleuven.be/aivooriedereen/en/notebook/support-vector-machines).*"
   ]
  }
 ],
 "metadata": {
  "aivi": {
   "chapters": [
    "support-vector-machines"
   ],
   "language": "en",
   "title": "Support vector machines in Python"
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
