{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "tags": [
     "remove_input"
    ]
   },
   "outputs": [],
   "source": [
    "path_data = '../../data/'\n",
    "\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "import math\n",
    "import scipy.stats as stats\n",
    "\n",
    "%matplotlib inline\n",
    "import matplotlib.pyplot as plt\n",
    "from mpl_toolkits.mplot3d import Axes3D\n",
    "plt.style.use('fivethirtyeight')\n",
    "\n",
    "import warnings\n",
    "warnings.filterwarnings('ignore')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Implementing the Classifier\n",
    "We are now ready to implement a $k$-nearest neighbor classifier based on multiple attributes. We have used only two attributes so far, for ease of visualization. But usually predictions will be based on many attributes. Here is an example that shows how multiple attributes can be better than pairs."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Banknote authentication\n",
    "\n",
    "This time we'll look at predicting whether a banknote (e.g., a \\$20 bill) is counterfeit or legitimate.  Researchers have put together a data set for us, based on photographs of many individual banknotes: some counterfeit, some legitimate.  They computed a few numbers from each image, using techniques that we won't worry about for this course.  So, for each banknote, we know a few numbers that were computed from a photograph of it as well as its class (whether it is counterfeit or not).  Let's load it into a table and take a look."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "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>WaveletVar</th>\n",
       "      <th>WaveletSkew</th>\n",
       "      <th>WaveletCurt</th>\n",
       "      <th>Entropy</th>\n",
       "      <th>Class</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>3.62160</td>\n",
       "      <td>8.66610</td>\n",
       "      <td>-2.8073</td>\n",
       "      <td>-0.44699</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>4.54590</td>\n",
       "      <td>8.16740</td>\n",
       "      <td>-2.4586</td>\n",
       "      <td>-1.46210</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>3.86600</td>\n",
       "      <td>-2.63830</td>\n",
       "      <td>1.9242</td>\n",
       "      <td>0.10645</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>3.45660</td>\n",
       "      <td>9.52280</td>\n",
       "      <td>-4.0112</td>\n",
       "      <td>-3.59440</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>0.32924</td>\n",
       "      <td>-4.45520</td>\n",
       "      <td>4.5718</td>\n",
       "      <td>-0.98880</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>...</th>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1367</th>\n",
       "      <td>0.40614</td>\n",
       "      <td>1.34920</td>\n",
       "      <td>-1.4501</td>\n",
       "      <td>-0.55949</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1368</th>\n",
       "      <td>-1.38870</td>\n",
       "      <td>-4.87730</td>\n",
       "      <td>6.4774</td>\n",
       "      <td>0.34179</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1369</th>\n",
       "      <td>-3.75030</td>\n",
       "      <td>-13.45860</td>\n",
       "      <td>17.5932</td>\n",
       "      <td>-2.77710</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1370</th>\n",
       "      <td>-3.56370</td>\n",
       "      <td>-8.38270</td>\n",
       "      <td>12.3930</td>\n",
       "      <td>-1.28230</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1371</th>\n",
       "      <td>-2.54190</td>\n",
       "      <td>-0.65804</td>\n",
       "      <td>2.6842</td>\n",
       "      <td>1.19520</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>1372 rows × 5 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "      WaveletVar  WaveletSkew  WaveletCurt  Entropy  Class\n",
       "0        3.62160      8.66610      -2.8073 -0.44699      0\n",
       "1        4.54590      8.16740      -2.4586 -1.46210      0\n",
       "2        3.86600     -2.63830       1.9242  0.10645      0\n",
       "3        3.45660      9.52280      -4.0112 -3.59440      0\n",
       "4        0.32924     -4.45520       4.5718 -0.98880      0\n",
       "...          ...          ...          ...      ...    ...\n",
       "1367     0.40614      1.34920      -1.4501 -0.55949      1\n",
       "1368    -1.38870     -4.87730       6.4774  0.34179      1\n",
       "1369    -3.75030    -13.45860      17.5932 -2.77710      1\n",
       "1370    -3.56370     -8.38270      12.3930 -1.28230      1\n",
       "1371    -2.54190     -0.65804       2.6842  1.19520      1\n",
       "\n",
       "[1372 rows x 5 columns]"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "banknotes = pd.read_csv(path_data + 'banknote.csv')\n",
    "banknotes"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's look at whether the first two numbers tell us anything about whether the banknote is counterfeit or not.  Here's a scatterplot:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "color_table = pd.DataFrame(\n",
    "    {'Class':np.array([1, 0]),\n",
    "    'Color':np.array(['darkblue', 'gold'])}\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "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>WaveletVar</th>\n",
       "      <th>WaveletSkew</th>\n",
       "      <th>WaveletCurt</th>\n",
       "      <th>Entropy</th>\n",
       "      <th>Class</th>\n",
       "      <th>Color</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>3.62160</td>\n",
       "      <td>8.66610</td>\n",
       "      <td>-2.8073</td>\n",
       "      <td>-0.44699</td>\n",
       "      <td>0</td>\n",
       "      <td>gold</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>4.54590</td>\n",
       "      <td>8.16740</td>\n",
       "      <td>-2.4586</td>\n",
       "      <td>-1.46210</td>\n",
       "      <td>0</td>\n",
       "      <td>gold</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>3.86600</td>\n",
       "      <td>-2.63830</td>\n",
       "      <td>1.9242</td>\n",
       "      <td>0.10645</td>\n",
       "      <td>0</td>\n",
       "      <td>gold</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>3.45660</td>\n",
       "      <td>9.52280</td>\n",
       "      <td>-4.0112</td>\n",
       "      <td>-3.59440</td>\n",
       "      <td>0</td>\n",
       "      <td>gold</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>0.32924</td>\n",
       "      <td>-4.45520</td>\n",
       "      <td>4.5718</td>\n",
       "      <td>-0.98880</td>\n",
       "      <td>0</td>\n",
       "      <td>gold</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>...</th>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1367</th>\n",
       "      <td>0.40614</td>\n",
       "      <td>1.34920</td>\n",
       "      <td>-1.4501</td>\n",
       "      <td>-0.55949</td>\n",
       "      <td>1</td>\n",
       "      <td>darkblue</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1368</th>\n",
       "      <td>-1.38870</td>\n",
       "      <td>-4.87730</td>\n",
       "      <td>6.4774</td>\n",
       "      <td>0.34179</td>\n",
       "      <td>1</td>\n",
       "      <td>darkblue</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1369</th>\n",
       "      <td>-3.75030</td>\n",
       "      <td>-13.45860</td>\n",
       "      <td>17.5932</td>\n",
       "      <td>-2.77710</td>\n",
       "      <td>1</td>\n",
       "      <td>darkblue</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1370</th>\n",
       "      <td>-3.56370</td>\n",
       "      <td>-8.38270</td>\n",
       "      <td>12.3930</td>\n",
       "      <td>-1.28230</td>\n",
       "      <td>1</td>\n",
       "      <td>darkblue</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1371</th>\n",
       "      <td>-2.54190</td>\n",
       "      <td>-0.65804</td>\n",
       "      <td>2.6842</td>\n",
       "      <td>1.19520</td>\n",
       "      <td>1</td>\n",
       "      <td>darkblue</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>1372 rows × 6 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "      WaveletVar  WaveletSkew  WaveletCurt  Entropy  Class     Color\n",
       "0        3.62160      8.66610      -2.8073 -0.44699      0      gold\n",
       "1        4.54590      8.16740      -2.4586 -1.46210      0      gold\n",
       "2        3.86600     -2.63830       1.9242  0.10645      0      gold\n",
       "3        3.45660      9.52280      -4.0112 -3.59440      0      gold\n",
       "4        0.32924     -4.45520       4.5718 -0.98880      0      gold\n",
       "...          ...          ...          ...      ...    ...       ...\n",
       "1367     0.40614      1.34920      -1.4501 -0.55949      1  darkblue\n",
       "1368    -1.38870     -4.87730       6.4774  0.34179      1  darkblue\n",
       "1369    -3.75030    -13.45860      17.5932 -2.77710      1  darkblue\n",
       "1370    -3.56370     -8.38270      12.3930 -1.28230      1  darkblue\n",
       "1371    -2.54190     -0.65804       2.6842  1.19520      1  darkblue\n",
       "\n",
       "[1372 rows x 6 columns]"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "banknotes = pd.merge(banknotes, color_table, on='Class')\n",
    "banknotes"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 75188 characters]\n",
      "text/plain": [
       "<Figure size 432x432 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "banknotes_darkblue = banknotes[banknotes['Color'] == 'darkblue']\n",
    "banknotes_gold = banknotes[banknotes['Color'] == 'gold']\n",
    "\n",
    "\n",
    "fig, ax = plt.subplots(figsize=(6,6))\n",
    "\n",
    "ax.scatter(banknotes_darkblue['WaveletVar'], \n",
    "           banknotes_darkblue['WaveletCurt'],  \n",
    "           label='Color=darkblue', \n",
    "           color='darkblue')\n",
    "\n",
    "ax.scatter(banknotes_gold['WaveletVar'], \n",
    "           banknotes_gold['WaveletCurt'],  \n",
    "           label='Color=gold', \n",
    "           color='gold')\n",
    "\n",
    "\n",
    "x_label = 'WaveletVar'\n",
    "\n",
    "y_label = 'WaveletCurt'\n",
    "\n",
    "y_vals = ax.get_yticks()\n",
    "\n",
    "plt.ylabel(y_label)\n",
    "\n",
    "plt.xlabel(x_label)\n",
    "\n",
    "ax.legend(bbox_to_anchor=(1.04,1), loc=\"upper left\")\n",
    "\n",
    "plt.xlim(-7.5, 7.5)\n",
    "plt.ylim(-6, 16)\n",
    "\n",
    "plt.show()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Pretty interesting!  Those two measurements do seem helpful for predicting whether the banknote is counterfeit or not.  However, in this example you can now see that there is some overlap between the blue cluster and the gold cluster.  This indicates that there will be some images where it's hard to tell whether the banknote is legitimate based on just these two numbers.  Still, you could use a $k$-nearest neighbor classifier to predict the legitimacy of a banknote.\n",
    "\n",
    "Take a minute and think it through: Suppose we used $k=11$ (say).  What parts of the plot would the classifier get right, and what parts would it make errors on?  What would the decision boundary look like?\n",
    "\n",
    "The patterns that show up in the data can get pretty wild.  For instance, here's what we'd get if used a different pair of measurements from the images:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 58880 characters]\n",
      "text/plain": [
       "<Figure size 432x432 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "banknotes_darkblue = banknotes[banknotes['Color'] == 'darkblue']\n",
    "banknotes_gold = banknotes[banknotes['Color'] == 'gold']\n",
    "\n",
    "\n",
    "fig, ax = plt.subplots(figsize=(6,6))\n",
    "\n",
    "ax.scatter(banknotes_darkblue['WaveletSkew'], \n",
    "           banknotes_darkblue['Entropy'],  \n",
    "           label='Color=darkblue', \n",
    "           color='darkblue')\n",
    "\n",
    "ax.scatter(banknotes_gold['WaveletSkew'], \n",
    "           banknotes_gold['Entropy'],  \n",
    "           label='Color=gold', \n",
    "           color='gold')\n",
    "\n",
    "\n",
    "x_label = 'WaveletSkew'\n",
    "\n",
    "y_label = 'Entropy'\n",
    "\n",
    "y_vals = ax.get_yticks()\n",
    "\n",
    "plt.ylabel(y_label)\n",
    "\n",
    "plt.xlabel(x_label)\n",
    "\n",
    "ax.legend(bbox_to_anchor=(1.04,1), loc=\"upper left\")\n",
    "\n",
    "plt.xlim(-16, 16)\n",
    "plt.ylim(-10, 3)\n",
    "\n",
    "plt.show()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "There does seem to be a pattern, but it's a pretty complex one.  Nonetheless, the $k$-nearest neighbors classifier can still be used and will effectively \"discover\" patterns out of this.  This illustrates how powerful machine learning can be: it can effectively take advantage of even patterns that we would not have anticipated, or that we would have thought to \"program into\" the computer."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Multiple attributes\n",
    "So far I've been assuming that we have exactly 2 attributes that we can use to help us make our prediction.  What if we have more than 2?  For instance, what if we have 3 attributes?\n",
    "\n",
    "Here's the cool part: you can use the same ideas for this case, too.  All you have to do is make a 3-dimensional scatterplot, instead of a 2-dimensional plot.  You can still use the $k$-nearest neighbors classifier, but now computing distances in 3 dimensions instead of just 2.  It just works.  Very cool!\n",
    "\n",
    "In fact, there's nothing special about 2 or 3.  If you have 4 attributes, you can use the $k$-nearest neighbors classifier in 4 dimensions.  5 attributes?  Work in 5-dimensional space.  And no need to stop there!  This all works for arbitrarily many attributes; you just work in a very high dimensional space.  It gets wicked-impossible to visualize, but that's OK.  The computer algorithm generalizes very nicely: all you need is the ability to compute the distance, and that's not hard.  Mind-blowing stuff!\n",
    "\n",
    "For instance, let's see what happens if we try to predict whether a banknote is counterfeit or not using 3 of the measurements, instead of just 2.  Here's what you get:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 108008 characters]\n",
      "text/plain": [
       "<Figure size 576x576 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "ax = plt.figure(figsize=(8,8)).add_subplot(111, projection='3d')\n",
    "ax.scatter(banknotes['WaveletSkew'], \n",
    "           banknotes['WaveletVar'], \n",
    "           banknotes['WaveletCurt'], \n",
    "           c=banknotes['Color']);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Awesome!  With just 2 attributes, there was some overlap between the two clusters (which means that the classifier was bound to make some mistakes for pointers in the overlap).  But when we use these 3 attributes, the two clusters have almost no overlap.  In other words, a classifier that uses these 3 attributes will be more accurate than one that only uses the 2 attributes.\n",
    "\n",
    "This is a general phenomenom in classification.  Each attribute can potentially give you new information, so more attributes sometimes helps you build a better classifier.  Of course, the cost is that now we have to gather more information to measure the value of each attribute, but this cost may be well worth it if it significantly improves the accuracy of our classifier.\n",
    "\n",
    "To sum up: you now know how to use $k$-nearest neighbor classification to predict the answer to a yes/no question, based on the values of some attributes, assuming you have a training set with examples where the correct prediction is known.  The general roadmap is this:\n",
    "\n",
    "1. identify some attributes that you think might help you predict the answer to the question.\n",
    "2. Gather a training set of examples where you know the values of the attributes as well as the correct prediction.\n",
    "3. To make predictions in the future, measure the value of the attributes and then use $k$-nearest neighbor classification to predict the answer to the question."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "### Distance in Multiple Dimensions\n",
    "We know how to compute distance in 2-dimensional space. If we have a point at coordinates $(x_0,y_0)$ and another at $(x_1,y_1)$, the distance between them is\n",
    "\n",
    "$$D = \\sqrt{(x_0-x_1)^2 + (y_0-y_1)^2}.$$\n",
    "\n",
    "In 3-dimensional space, the points are $(x_0, y_0, z_0)$ and $(x_1, y_1, z_1)$, and the formula for the distance between them is\n",
    "\n",
    "$$\n",
    "D = \\sqrt{(x_0-x_1)^2 + (y_0-y_1)^2 + (z_0-z_1)^2}\n",
    "$$\n",
    "\n",
    "In $n$-dimensional space, things are a bit harder to visualize, but I think you can see how the formula generalized: we sum up the squares of the differences between each individual coordinate, and then take the square root of that.  "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In the last section, we defined the function `distance` which returned the distance between two points. We used it in two-dimensions, but the great news is that the function doesn't care how many dimensions there are! It just subtracts the two arrays of coordinates (no matter how long the arrays are), squares the differences and adds up, and then takes the square root. To work in multiple dimensions, we don't have to change the code at all."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "def distance(point1, point2):\n",
    "    \"\"\"Returns the distance between point1 and point2\n",
    "    where each argument is an array \n",
    "    consisting of the coordinates of the point\"\"\"\n",
    "    return np.sqrt(np.sum((point1 - point2)**2))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's use this on a [new dataset](https://archive.ics.uci.edu/ml/datasets/Wine). The table `wine` contains the chemical composition of 178 different Italian wines. The classes are the grape species, called cultivars. There are three classes but let's just see whether we can tell Class 1 apart from the other two."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "wine = pd.read_csv(path_data + 'wine.csv')\n",
    "\n",
    "# For converting Class to binary\n",
    "\n",
    "def is_one(x):\n",
    "    if x == 1:\n",
    "        return 1\n",
    "    else:\n",
    "        return 0\n",
    "\n",
    "wine['Class1'] = wine['Class'].apply(is_one)\n",
    "\n",
    "# This creates a column 'Class1' - we drop the 'Class' column, rename 'Class1' as 'Class'\n",
    "# then move the column to the first position using 'pop' and 'insert'\n",
    "\n",
    "wine = wine.drop(columns=['Class'])\n",
    "\n",
    "wine = wine.rename(columns={'Class1': 'Class'})\n",
    "\n",
    "class_label = wine.pop('Class')\n",
    "\n",
    "wine.insert(0, 'Class', class_label)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "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>Class</th>\n",
       "      <th>Alcohol</th>\n",
       "      <th>Malic Acid</th>\n",
       "      <th>Ash</th>\n",
       "      <th>Alcalinity of Ash</th>\n",
       "      <th>Magnesium</th>\n",
       "      <th>Total Phenols</th>\n",
       "      <th>Flavanoids</th>\n",
       "      <th>Nonflavanoid phenols</th>\n",
       "      <th>Proanthocyanins</th>\n",
       "      <th>Color Intensity</th>\n",
       "      <th>Hue</th>\n",
       "      <th>OD280/OD315 of diulted wines</th>\n",
       "      <th>Proline</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>1</td>\n",
       "      <td>14.23</td>\n",
       "      <td>1.71</td>\n",
       "      <td>2.43</td>\n",
       "      <td>15.6</td>\n",
       "      <td>127</td>\n",
       "      <td>2.80</td>\n",
       "      <td>3.06</td>\n",
       "      <td>0.28</td>\n",
       "      <td>2.29</td>\n",
       "      <td>5.64</td>\n",
       "      <td>1.04</td>\n",
       "      <td>3.92</td>\n",
       "      <td>1065</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>1</td>\n",
       "      <td>13.20</td>\n",
       "      <td>1.78</td>\n",
       "      <td>2.14</td>\n",
       "      <td>11.2</td>\n",
       "      <td>100</td>\n",
       "      <td>2.65</td>\n",
       "      <td>2.76</td>\n",
       "      <td>0.26</td>\n",
       "      <td>1.28</td>\n",
       "      <td>4.38</td>\n",
       "      <td>1.05</td>\n",
       "      <td>3.40</td>\n",
       "      <td>1050</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>1</td>\n",
       "      <td>13.16</td>\n",
       "      <td>2.36</td>\n",
       "      <td>2.67</td>\n",
       "      <td>18.6</td>\n",
       "      <td>101</td>\n",
       "      <td>2.80</td>\n",
       "      <td>3.24</td>\n",
       "      <td>0.30</td>\n",
       "      <td>2.81</td>\n",
       "      <td>5.68</td>\n",
       "      <td>1.03</td>\n",
       "      <td>3.17</td>\n",
       "      <td>1185</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>1</td>\n",
       "      <td>14.37</td>\n",
       "      <td>1.95</td>\n",
       "      <td>2.50</td>\n",
       "      <td>16.8</td>\n",
       "      <td>113</td>\n",
       "      <td>3.85</td>\n",
       "      <td>3.49</td>\n",
       "      <td>0.24</td>\n",
       "      <td>2.18</td>\n",
       "      <td>7.80</td>\n",
       "      <td>0.86</td>\n",
       "      <td>3.45</td>\n",
       "      <td>1480</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>1</td>\n",
       "      <td>13.24</td>\n",
       "      <td>2.59</td>\n",
       "      <td>2.87</td>\n",
       "      <td>21.0</td>\n",
       "      <td>118</td>\n",
       "      <td>2.80</td>\n",
       "      <td>2.69</td>\n",
       "      <td>0.39</td>\n",
       "      <td>1.82</td>\n",
       "      <td>4.32</td>\n",
       "      <td>1.04</td>\n",
       "      <td>2.93</td>\n",
       "      <td>735</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>...</th>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>173</th>\n",
       "      <td>0</td>\n",
       "      <td>13.71</td>\n",
       "      <td>5.65</td>\n",
       "      <td>2.45</td>\n",
       "      <td>20.5</td>\n",
       "      <td>95</td>\n",
       "      <td>1.68</td>\n",
       "      <td>0.61</td>\n",
       "      <td>0.52</td>\n",
       "      <td>1.06</td>\n",
       "      <td>7.70</td>\n",
       "      <td>0.64</td>\n",
       "      <td>1.74</td>\n",
       "      <td>740</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>174</th>\n",
       "      <td>0</td>\n",
       "      <td>13.40</td>\n",
       "      <td>3.91</td>\n",
       "      <td>2.48</td>\n",
       "      <td>23.0</td>\n",
       "      <td>102</td>\n",
       "      <td>1.80</td>\n",
       "      <td>0.75</td>\n",
       "      <td>0.43</td>\n",
       "      <td>1.41</td>\n",
       "      <td>7.30</td>\n",
       "      <td>0.70</td>\n",
       "      <td>1.56</td>\n",
       "      <td>750</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>175</th>\n",
       "      <td>0</td>\n",
       "      <td>13.27</td>\n",
       "      <td>4.28</td>\n",
       "      <td>2.26</td>\n",
       "      <td>20.0</td>\n",
       "      <td>120</td>\n",
       "      <td>1.59</td>\n",
       "      <td>0.69</td>\n",
       "      <td>0.43</td>\n",
       "      <td>1.35</td>\n",
       "      <td>10.20</td>\n",
       "      <td>0.59</td>\n",
       "      <td>1.56</td>\n",
       "      <td>835</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>176</th>\n",
       "      <td>0</td>\n",
       "      <td>13.17</td>\n",
       "      <td>2.59</td>\n",
       "      <td>2.37</td>\n",
       "      <td>20.0</td>\n",
       "      <td>120</td>\n",
       "      <td>1.65</td>\n",
       "      <td>0.68</td>\n",
       "      <td>0.53</td>\n",
       "      <td>1.46</td>\n",
       "      <td>9.30</td>\n",
       "      <td>0.60</td>\n",
       "      <td>1.62</td>\n",
       "      <td>840</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>177</th>\n",
       "      <td>0</td>\n",
       "      <td>14.13</td>\n",
       "      <td>4.10</td>\n",
       "      <td>2.74</td>\n",
       "      <td>24.5</td>\n",
       "      <td>96</td>\n",
       "      <td>2.05</td>\n",
       "      <td>0.76</td>\n",
       "      <td>0.56</td>\n",
       "      <td>1.35</td>\n",
       "      <td>9.20</td>\n",
       "      <td>0.61</td>\n",
       "      <td>1.60</td>\n",
       "      <td>560</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>178 rows × 14 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "     Class  Alcohol  Malic Acid   Ash  Alcalinity of Ash  Magnesium  \\\n",
       "0        1    14.23        1.71  2.43               15.6        127   \n",
       "1        1    13.20        1.78  2.14               11.2        100   \n",
       "2        1    13.16        2.36  2.67               18.6        101   \n",
       "3        1    14.37        1.95  2.50               16.8        113   \n",
       "4        1    13.24        2.59  2.87               21.0        118   \n",
       "..     ...      ...         ...   ...                ...        ...   \n",
       "173      0    13.71        5.65  2.45               20.5         95   \n",
       "174      0    13.40        3.91  2.48               23.0        102   \n",
       "175      0    13.27        4.28  2.26               20.0        120   \n",
       "176      0    13.17        2.59  2.37               20.0        120   \n",
       "177      0    14.13        4.10  2.74               24.5         96   \n",
       "\n",
       "     Total Phenols  Flavanoids  Nonflavanoid phenols  Proanthocyanins  \\\n",
       "0             2.80        3.06                  0.28             2.29   \n",
       "1             2.65        2.76                  0.26             1.28   \n",
       "2             2.80        3.24                  0.30             2.81   \n",
       "3             3.85        3.49                  0.24             2.18   \n",
       "4             2.80        2.69                  0.39             1.82   \n",
       "..             ...         ...                   ...              ...   \n",
       "173           1.68        0.61                  0.52             1.06   \n",
       "174           1.80        0.75                  0.43             1.41   \n",
       "175           1.59        0.69                  0.43             1.35   \n",
       "176           1.65        0.68                  0.53             1.46   \n",
       "177           2.05        0.76                  0.56             1.35   \n",
       "\n",
       "     Color Intensity   Hue  OD280/OD315 of diulted wines  Proline  \n",
       "0               5.64  1.04                          3.92     1065  \n",
       "1               4.38  1.05                          3.40     1050  \n",
       "2               5.68  1.03                          3.17     1185  \n",
       "3               7.80  0.86                          3.45     1480  \n",
       "4               4.32  1.04                          2.93      735  \n",
       "..               ...   ...                           ...      ...  \n",
       "173             7.70  0.64                          1.74      740  \n",
       "174             7.30  0.70                          1.56      750  \n",
       "175            10.20  0.59                          1.56      835  \n",
       "176             9.30  0.60                          1.62      840  \n",
       "177             9.20  0.61                          1.60      560  \n",
       "\n",
       "[178 rows x 14 columns]"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "wine"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The first two wines are both in Class 1. To find the distance between them, we first need a table of just the attributes:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "wine_attributes = wine.copy()\n",
    "\n",
    "wine_attributes = wine_attributes.drop(columns=['Class'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "31.265012394048398"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "distance(np.array(wine_attributes.iloc[0]), np.array(wine_attributes.iloc[1]))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The last wine in the table is of Class 0. Its distance from the first wine is:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "506.05936766351834"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "distance(np.array(wine_attributes.iloc[0]), np.array(wine_attributes.iloc[177]))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "That's quite a bit bigger! Let's do some visualization to see if Class 1 really looks different from Class 0. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "wine_with_colors = pd.merge(wine, color_table, on='Class')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 33156 characters]\n",
      "text/plain": [
       "<Figure size 432x432 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "wine_darkblue = wine_with_colors[wine_with_colors['Color'] == 'darkblue']\n",
    "wine_gold = wine_with_colors[wine_with_colors['Color'] == 'gold']\n",
    "\n",
    "fig, ax = plt.subplots(figsize=(6,6))\n",
    "\n",
    "ax.scatter(wine_darkblue['Flavanoids'], \n",
    "           wine_darkblue['Alcohol'],  \n",
    "           label='Color=darkblue', \n",
    "           color='darkblue')\n",
    "\n",
    "ax.scatter(wine_gold['Flavanoids'], \n",
    "           wine_gold['Alcohol'],  \n",
    "           label='Color=gold', \n",
    "           color='gold')\n",
    "\n",
    "\n",
    "x_label = 'Flavanoids'\n",
    "\n",
    "y_label = 'Alcohol'\n",
    "\n",
    "#y_vals = ax.get_yticks()\n",
    "\n",
    "plt.ylabel(y_label)\n",
    "\n",
    "plt.xlabel(x_label)\n",
    "\n",
    "ax.legend(bbox_to_anchor=(1.04,1), loc=\"upper left\")\n",
    "\n",
    "plt.xlim(0, 5)\n",
    "plt.ylim(10.8, 15)\n",
    "\n",
    "plt.show()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The blue points (Class 1) are almost entirely separate from the gold ones. That is one indication of why the distance between two Class 1 wines would be smaller than the distance between wines of two different classes. We can see a similar phenomenon with a different pair of attributes too:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 34204 characters]\n",
      "text/plain": [
       "<Figure size 432x432 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "wine_darkblue = wine_with_colors[wine_with_colors['Color'] == 'darkblue']\n",
    "wine_gold = wine_with_colors[wine_with_colors['Color'] == 'gold']\n",
    "\n",
    "fig, ax = plt.subplots(figsize=(6,6))\n",
    "\n",
    "ax.scatter(wine_darkblue['Alcalinity of Ash'], \n",
    "           wine_darkblue['Ash'],  \n",
    "           label='Color=darkblue', \n",
    "           color='darkblue')\n",
    "\n",
    "ax.scatter(wine_gold['Alcalinity of Ash'], \n",
    "           wine_gold['Ash'],  \n",
    "           label='Color=gold', \n",
    "           color='gold')\n",
    "\n",
    "\n",
    "x_label = 'Alcalinity of Ash'\n",
    "\n",
    "y_label = 'Ash'\n",
    "\n",
    "#y_vals = ax.get_yticks()\n",
    "\n",
    "plt.ylabel(y_label)\n",
    "\n",
    "plt.xlabel(x_label)\n",
    "\n",
    "ax.legend(bbox_to_anchor=(1.04,1), loc=\"upper left\")\n",
    "\n",
    "plt.xlim(10, 30.2)\n",
    "plt.ylim(1.25, 3.5)\n",
    "\n",
    "plt.show()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "But for some pairs the picture is more murky."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 31524 characters]\n",
      "text/plain": [
       "<Figure size 432x432 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "wine_darkblue = wine_with_colors[wine_with_colors['Color'] == 'darkblue']\n",
    "wine_gold = wine_with_colors[wine_with_colors['Color'] == 'gold']\n",
    "\n",
    "fig, ax = plt.subplots(figsize=(6,6))\n",
    "\n",
    "ax.scatter(wine_darkblue['Magnesium'], \n",
    "           wine_darkblue['Total Phenols'],  \n",
    "           label='Color=darkblue', \n",
    "           color='darkblue')\n",
    "\n",
    "ax.scatter(wine_gold['Magnesium'], \n",
    "           wine_gold['Total Phenols'],  \n",
    "           label='Color=gold', \n",
    "           color='gold')\n",
    "\n",
    "\n",
    "x_label = 'Magnesium'\n",
    "\n",
    "y_label = 'Total Phenols'\n",
    "\n",
    "#y_vals = ax.get_yticks()\n",
    "\n",
    "plt.ylabel(y_label)\n",
    "\n",
    "plt.xlabel(x_label)\n",
    "\n",
    "ax.legend(bbox_to_anchor=(1.04,1), loc=\"upper left\")\n",
    "\n",
    "plt.xlim(70, 165)\n",
    "plt.ylim(0.9, 4)\n",
    "\n",
    "plt.show()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's see if we can implement a classifier based on all of the attributes. After that, we'll see how accurate it is."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## A Plan for the Implementation\n",
    "It's time to write some code to implement the classifier.  The input is a `point` that we want to classify.  The classifier works by finding the $k$ nearest neighbors of `point` from the training set.  So, our approach will go like this:\n",
    "\n",
    "1. Find the closest $k$ neighbors of `point`, i.e., the $k$ wines from the training set that are most similar to `point`.\n",
    "\n",
    "2. Look at the classes of those $k$ neighbors, and take the majority vote to find the most-common class of wine.  Use that as our predicted class for `point`.\n",
    "\n",
    "So that will guide the structure of our Python code."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [],
   "source": [
    "def closest(training, p, k):\n",
    "    ...\n",
    "\n",
    "def majority(topkclasses):\n",
    "    ...\n",
    "\n",
    "def classify(training, p, k):\n",
    "    kclosest = closest(training, p, k)\n",
    "    kclosest.classes = kclosest.select('Class')\n",
    "    return majority(kclosest)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Implementation Step 1\n",
    "To implement the first step for the kidney disease data, we had to compute the distance from each patient in the training set to `point`, sort them by distance, and take the $k$ closest patients in the training set.  \n",
    "\n",
    "That's what we did in the previous section with the point corresponding to Alice. Let's generalize that code. We'll redefine `distance` here, just for convenience."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [],
   "source": [
    "def distance(point1, point2):\n",
    "    \"\"\"Returns the distance between point1 and point2\n",
    "    where each argument is an array \n",
    "    consisting of the coordinates of the point\"\"\"\n",
    "    return np.sqrt(np.sum((point1 - point2)**2))\n",
    "\n",
    "def all_distances(training, point):\n",
    "    \"\"\"The distance between p (an array of numbers) and the numbers in row i of attribute_table.\"\"\"\n",
    "    attributes = training.drop(columns=['Class'])\n",
    "    def distance_from_point(row):\n",
    "        return distance(point, np.array(row))\n",
    "    return attributes.apply(distance_from_point, axis=1)\n",
    "\n",
    "def table_with_distances(training, point):\n",
    "    \"\"\"A copy of the training table with the distance from each row to array p.\"\"\"\n",
    "    training1 = training.copy()\n",
    "    training1['Distance'] = all_distances(training1, point)\n",
    "\n",
    "    return training1\n",
    "\n",
    "def closest(training, new_point, k):\n",
    "    \"\"\"Returns a table of the k rows of the augmented table\n",
    "    corresponding to the k smallest distances\"\"\"\n",
    "    with_dists = table_with_distances(training, new_point)\n",
    "    sorted_by_distance = with_dists.sort_values(by=['Distance'])\n",
    "    topk = sorted_by_distance.take(np.arange(k))\n",
    "    return topk\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's see how this works on our `wine` data. We'll just take the first wine and find its five nearest neighbors among all the wines. Remember that since this wine is part of the dataset, it is its own nearest neighbor. So we should expect to see it at the top of the list, followed by four others.\n",
    "\n",
    "First let's extract its attributes:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Alcohol                           14.23\n",
       "Malic Acid                         1.71\n",
       "Ash                                2.43\n",
       "Alcalinity of Ash                 15.60\n",
       "Magnesium                        127.00\n",
       "Total Phenols                      2.80\n",
       "Flavanoids                         3.06\n",
       "Nonflavanoid phenols               0.28\n",
       "Proanthocyanins                    2.29\n",
       "Color Intensity                    5.64\n",
       "Hue                                1.04\n",
       "OD280/OD315 of diulted wines       3.92\n",
       "Proline                         1065.00\n",
       "Name: 0, dtype: float64"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "special_wine = wine.drop(columns=['Class']).iloc[0]\n",
    "special_wine"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "And now let's find its 5 nearest neighbors."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "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>Class</th>\n",
       "      <th>Alcohol</th>\n",
       "      <th>Malic Acid</th>\n",
       "      <th>Ash</th>\n",
       "      <th>Alcalinity of Ash</th>\n",
       "      <th>Magnesium</th>\n",
       "      <th>Total Phenols</th>\n",
       "      <th>Flavanoids</th>\n",
       "      <th>Nonflavanoid phenols</th>\n",
       "      <th>Proanthocyanins</th>\n",
       "      <th>Color Intensity</th>\n",
       "      <th>Hue</th>\n",
       "      <th>OD280/OD315 of diulted wines</th>\n",
       "      <th>Proline</th>\n",
       "      <th>Distance</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>1</td>\n",
       "      <td>14.23</td>\n",
       "      <td>1.71</td>\n",
       "      <td>2.43</td>\n",
       "      <td>15.6</td>\n",
       "      <td>127</td>\n",
       "      <td>2.80</td>\n",
       "      <td>3.06</td>\n",
       "      <td>0.28</td>\n",
       "      <td>2.29</td>\n",
       "      <td>5.64</td>\n",
       "      <td>1.04</td>\n",
       "      <td>3.92</td>\n",
       "      <td>1065</td>\n",
       "      <td>0.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>54</th>\n",
       "      <td>1</td>\n",
       "      <td>13.74</td>\n",
       "      <td>1.67</td>\n",
       "      <td>2.25</td>\n",
       "      <td>16.4</td>\n",
       "      <td>118</td>\n",
       "      <td>2.60</td>\n",
       "      <td>2.90</td>\n",
       "      <td>0.21</td>\n",
       "      <td>1.62</td>\n",
       "      <td>5.85</td>\n",
       "      <td>0.92</td>\n",
       "      <td>3.20</td>\n",
       "      <td>1060</td>\n",
       "      <td>10.392805</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>45</th>\n",
       "      <td>1</td>\n",
       "      <td>14.21</td>\n",
       "      <td>4.04</td>\n",
       "      <td>2.44</td>\n",
       "      <td>18.9</td>\n",
       "      <td>111</td>\n",
       "      <td>2.85</td>\n",
       "      <td>2.65</td>\n",
       "      <td>0.30</td>\n",
       "      <td>1.25</td>\n",
       "      <td>5.24</td>\n",
       "      <td>0.87</td>\n",
       "      <td>3.33</td>\n",
       "      <td>1080</td>\n",
       "      <td>22.340748</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>48</th>\n",
       "      <td>1</td>\n",
       "      <td>14.10</td>\n",
       "      <td>2.02</td>\n",
       "      <td>2.40</td>\n",
       "      <td>18.8</td>\n",
       "      <td>103</td>\n",
       "      <td>2.75</td>\n",
       "      <td>2.92</td>\n",
       "      <td>0.32</td>\n",
       "      <td>2.38</td>\n",
       "      <td>6.20</td>\n",
       "      <td>1.07</td>\n",
       "      <td>2.75</td>\n",
       "      <td>1060</td>\n",
       "      <td>24.760232</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>46</th>\n",
       "      <td>1</td>\n",
       "      <td>14.38</td>\n",
       "      <td>3.59</td>\n",
       "      <td>2.28</td>\n",
       "      <td>16.0</td>\n",
       "      <td>102</td>\n",
       "      <td>3.25</td>\n",
       "      <td>3.17</td>\n",
       "      <td>0.27</td>\n",
       "      <td>2.19</td>\n",
       "      <td>4.90</td>\n",
       "      <td>1.04</td>\n",
       "      <td>3.44</td>\n",
       "      <td>1065</td>\n",
       "      <td>25.094663</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "    Class  Alcohol  Malic Acid   Ash  Alcalinity of Ash  Magnesium  \\\n",
       "0       1    14.23        1.71  2.43               15.6        127   \n",
       "54      1    13.74        1.67  2.25               16.4        118   \n",
       "45      1    14.21        4.04  2.44               18.9        111   \n",
       "48      1    14.10        2.02  2.40               18.8        103   \n",
       "46      1    14.38        3.59  2.28               16.0        102   \n",
       "\n",
       "    Total Phenols  Flavanoids  Nonflavanoid phenols  Proanthocyanins  \\\n",
       "0            2.80        3.06                  0.28             2.29   \n",
       "54           2.60        2.90                  0.21             1.62   \n",
       "45           2.85        2.65                  0.30             1.25   \n",
       "48           2.75        2.92                  0.32             2.38   \n",
       "46           3.25        3.17                  0.27             2.19   \n",
       "\n",
       "    Color Intensity   Hue  OD280/OD315 of diulted wines  Proline   Distance  \n",
       "0              5.64  1.04                          3.92     1065   0.000000  \n",
       "54             5.85  0.92                          3.20     1060  10.392805  \n",
       "45             5.24  0.87                          3.33     1080  22.340748  \n",
       "48             6.20  1.07                          2.75     1060  24.760232  \n",
       "46             4.90  1.04                          3.44     1065  25.094663  "
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "closest(wine, special_wine, 5)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Bingo! The first row is the nearest neighbor, which is itself – there's a 0 in the `Distance` column as expected. All five nearest neighbors are of Class 1, which is consistent with our earlier observation that Class 1 wines appear to be clumped together in some dimensions."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Implementation Steps 2 and 3\n",
    "Next we need to take a \"majority vote\" of the nearest neighbors and assign our point the same class as the majority."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [],
   "source": [
    "def majority(topkclasses):\n",
    "    ones = len(topkclasses[topkclasses['Class'] == 1])\n",
    "    zeros = len(topkclasses[topkclasses['Class'] == 0])\n",
    "    if ones > zeros:\n",
    "        return 1\n",
    "    else:\n",
    "        return 0\n",
    "\n",
    "def classify(training, new_point, k):\n",
    "    closestk = closest(training, new_point, k)\n",
    "    topkclasses = closestk[['Class']]\n",
    "    return majority(topkclasses)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "classify(wine, special_wine, 5)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If we change `special_wine` to be the last one in the dataset, is our classifier able to tell that it's in Class 0?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0"
      ]
     },
     "execution_count": 24,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "special_wine = wine.drop(columns=['Class']).iloc[177]\n",
    "classify(wine, special_wine, 5)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Yes! The classifier gets this one right too.\n",
    "\n",
    "But we don't yet know how it does with all the other wines, and in any case we know that testing on wines that are already part of the training set might be over-optimistic. In the final section of this chapter, we will separate the wines into a training and test set and then measure the accuracy of our classifier on the test set. "
   ]
  }
 ],
 "metadata": {
  "anaconda-cloud": {},
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
