{
 "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",
    "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": "code",
   "execution_count": 2,
   "metadata": {
    "tags": [
     "remove_input"
    ]
   },
   "outputs": [],
   "source": [
    "def standard_units(x):\n",
    "    return (x - np.mean(x))/np.std(x)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "# Rows of Tables\n",
    "Now that we have a qualitative understanding of nearest neighbor classification, it's time to implement our classifier.\n",
    "\n",
    "Until this chapter, we have worked mostly with single columns of tables. But now we have to see whether one *individual* is \"close\" to another. Data for individuals are contained in *rows* of tables.\n",
    "\n",
    "So let's start by taking a closer look at rows."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here is the original table `ckd` containing data on patients who were tested for chronic kidney disease."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "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>Age</th>\n",
       "      <th>Blood Pressure</th>\n",
       "      <th>Specific Gravity</th>\n",
       "      <th>Albumin</th>\n",
       "      <th>Sugar</th>\n",
       "      <th>Red Blood Cells</th>\n",
       "      <th>Pus Cell</th>\n",
       "      <th>Pus Cell clumps</th>\n",
       "      <th>Bacteria</th>\n",
       "      <th>Glucose</th>\n",
       "      <th>...</th>\n",
       "      <th>Packed Cell Volume</th>\n",
       "      <th>White Blood Cell Count</th>\n",
       "      <th>Red Blood Cell Count</th>\n",
       "      <th>Hypertension</th>\n",
       "      <th>Diabetes Mellitus</th>\n",
       "      <th>Coronary Artery Disease</th>\n",
       "      <th>Appetite</th>\n",
       "      <th>Pedal Edema</th>\n",
       "      <th>Anemia</th>\n",
       "      <th>Class</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>48</td>\n",
       "      <td>70</td>\n",
       "      <td>1.005</td>\n",
       "      <td>4</td>\n",
       "      <td>0</td>\n",
       "      <td>normal</td>\n",
       "      <td>abnormal</td>\n",
       "      <td>present</td>\n",
       "      <td>notpresent</td>\n",
       "      <td>117</td>\n",
       "      <td>...</td>\n",
       "      <td>32</td>\n",
       "      <td>6700</td>\n",
       "      <td>3.9</td>\n",
       "      <td>yes</td>\n",
       "      <td>no</td>\n",
       "      <td>no</td>\n",
       "      <td>poor</td>\n",
       "      <td>yes</td>\n",
       "      <td>yes</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>53</td>\n",
       "      <td>90</td>\n",
       "      <td>1.020</td>\n",
       "      <td>2</td>\n",
       "      <td>0</td>\n",
       "      <td>abnormal</td>\n",
       "      <td>abnormal</td>\n",
       "      <td>present</td>\n",
       "      <td>notpresent</td>\n",
       "      <td>70</td>\n",
       "      <td>...</td>\n",
       "      <td>29</td>\n",
       "      <td>12100</td>\n",
       "      <td>3.7</td>\n",
       "      <td>yes</td>\n",
       "      <td>yes</td>\n",
       "      <td>no</td>\n",
       "      <td>poor</td>\n",
       "      <td>no</td>\n",
       "      <td>yes</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>63</td>\n",
       "      <td>70</td>\n",
       "      <td>1.010</td>\n",
       "      <td>3</td>\n",
       "      <td>0</td>\n",
       "      <td>abnormal</td>\n",
       "      <td>abnormal</td>\n",
       "      <td>present</td>\n",
       "      <td>notpresent</td>\n",
       "      <td>380</td>\n",
       "      <td>...</td>\n",
       "      <td>32</td>\n",
       "      <td>4500</td>\n",
       "      <td>3.8</td>\n",
       "      <td>yes</td>\n",
       "      <td>yes</td>\n",
       "      <td>no</td>\n",
       "      <td>poor</td>\n",
       "      <td>yes</td>\n",
       "      <td>no</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>68</td>\n",
       "      <td>80</td>\n",
       "      <td>1.010</td>\n",
       "      <td>3</td>\n",
       "      <td>2</td>\n",
       "      <td>normal</td>\n",
       "      <td>abnormal</td>\n",
       "      <td>present</td>\n",
       "      <td>present</td>\n",
       "      <td>157</td>\n",
       "      <td>...</td>\n",
       "      <td>16</td>\n",
       "      <td>11000</td>\n",
       "      <td>2.6</td>\n",
       "      <td>yes</td>\n",
       "      <td>yes</td>\n",
       "      <td>yes</td>\n",
       "      <td>poor</td>\n",
       "      <td>yes</td>\n",
       "      <td>no</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>61</td>\n",
       "      <td>80</td>\n",
       "      <td>1.015</td>\n",
       "      <td>2</td>\n",
       "      <td>0</td>\n",
       "      <td>abnormal</td>\n",
       "      <td>abnormal</td>\n",
       "      <td>notpresent</td>\n",
       "      <td>notpresent</td>\n",
       "      <td>173</td>\n",
       "      <td>...</td>\n",
       "      <td>24</td>\n",
       "      <td>9200</td>\n",
       "      <td>3.2</td>\n",
       "      <td>yes</td>\n",
       "      <td>yes</td>\n",
       "      <td>yes</td>\n",
       "      <td>poor</td>\n",
       "      <td>yes</td>\n",
       "      <td>yes</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>5 rows × 25 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "   Age  Blood Pressure  Specific Gravity  Albumin  Sugar Red Blood Cells  \\\n",
       "0   48              70             1.005        4      0          normal   \n",
       "1   53              90             1.020        2      0        abnormal   \n",
       "2   63              70             1.010        3      0        abnormal   \n",
       "3   68              80             1.010        3      2          normal   \n",
       "4   61              80             1.015        2      0        abnormal   \n",
       "\n",
       "   Pus Cell Pus Cell clumps    Bacteria  Glucose  ...  Packed Cell Volume  \\\n",
       "0  abnormal         present  notpresent      117  ...                  32   \n",
       "1  abnormal         present  notpresent       70  ...                  29   \n",
       "2  abnormal         present  notpresent      380  ...                  32   \n",
       "3  abnormal         present     present      157  ...                  16   \n",
       "4  abnormal      notpresent  notpresent      173  ...                  24   \n",
       "\n",
       "   White Blood Cell Count  Red Blood Cell Count  Hypertension  \\\n",
       "0                    6700                   3.9           yes   \n",
       "1                   12100                   3.7           yes   \n",
       "2                    4500                   3.8           yes   \n",
       "3                   11000                   2.6           yes   \n",
       "4                    9200                   3.2           yes   \n",
       "\n",
       "   Diabetes Mellitus  Coronary Artery Disease  Appetite  Pedal Edema Anemia  \\\n",
       "0                 no                       no      poor          yes    yes   \n",
       "1                yes                       no      poor           no    yes   \n",
       "2                yes                       no      poor          yes     no   \n",
       "3                yes                      yes      poor          yes     no   \n",
       "4                yes                      yes      poor          yes    yes   \n",
       "\n",
       "  Class  \n",
       "0     1  \n",
       "1     1  \n",
       "2     1  \n",
       "3     1  \n",
       "4     1  \n",
       "\n",
       "[5 rows x 25 columns]"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "ckd = pd.read_csv(path_data + 'ckd.csv').rename(columns={'Blood Glucose Random': 'Glucose'})\n",
    "ckd.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The data corresponding to the first patient is in row 0 of the table, consistent with Python's indexing system. The Table method `row` accesses the row by taking the index of the row as its argument:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Age                                48\n",
       "Blood Pressure                     70\n",
       "Specific Gravity                1.005\n",
       "Albumin                             4\n",
       "Sugar                               0\n",
       "Red Blood Cells                normal\n",
       "Pus Cell                     abnormal\n",
       "Pus Cell clumps               present\n",
       "Bacteria                   notpresent\n",
       "Glucose                           117\n",
       "Blood Urea                         56\n",
       "Serum Creatinine                  3.8\n",
       "Sodium                            111\n",
       "Potassium                         2.5\n",
       "Hemoglobin                       11.2\n",
       "Packed Cell Volume                 32\n",
       "White Blood Cell Count           6700\n",
       "Red Blood Cell Count              3.9\n",
       "Hypertension                      yes\n",
       "Diabetes Mellitus                  no\n",
       "Coronary Artery Disease            no\n",
       "Appetite                         poor\n",
       "Pedal Edema                       yes\n",
       "Anemia                            yes\n",
       "Class                               1\n",
       "Name: 0, dtype: object"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "ckd.iloc[0]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Or, as an array"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([48, 70, 1.005, 4, 0, 'normal', 'abnormal', 'present', 'notpresent',\n",
       "       117, 56, 3.8, 111, 2.5, 11.2, 32, 6700, 3.9, 'yes', 'no', 'no',\n",
       "       'poor', 'yes', 'yes', 1], dtype=object)"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.array(ckd.loc[0])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Rows have their very own data type: they are *row objects*. Notice how when using the pandas `df.loc[row]` the display shows not only the values in the row but also the labels of the corresponding columns.\n",
    "\n",
    "Rows are in general **not arrays**, as their elements can be of different types. For example, some of the elements of the row above are strings (like `'abnormal'`) and some are numerical.\n",
    "\n",
    "However, rows share some characteristics with arrays.  You can use `.iloc[row:column]` to access a particular element of a row. For example, to access the Albumin level of Patient 0, we can look at the labels in the printout of the row above to find that it's the column 'Albumin' is column index 3 i.e. `.iloc[row_number,3:`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "4"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "ckd.iloc[0,3]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "numpy.int64"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "type(ckd['Class'].iloc[0])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Converting Rows to Arrays (When Possible)\n",
    "Rows whose elements are all numerical (or all strings) can be converted to arrays.  Converting a row to an array gives us access to arithmetic operations and other nice NumPy functions, so it is often useful.\n",
    "\n",
    "Recall that in the previous section we tried to classify the patients as 'CKD' or 'not CKD', based on two attributes `Hemoglobin` and `Glucose`, both measured in standard units. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "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>Hemoglobin</th>\n",
       "      <th>Glucose</th>\n",
       "      <th>Class</th>\n",
       "      <th>Color</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>-0.865744</td>\n",
       "      <td>-0.221549</td>\n",
       "      <td>1</td>\n",
       "      <td>darkblue</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>-1.457446</td>\n",
       "      <td>-0.947597</td>\n",
       "      <td>1</td>\n",
       "      <td>darkblue</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>-1.004968</td>\n",
       "      <td>3.841231</td>\n",
       "      <td>1</td>\n",
       "      <td>darkblue</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>-2.814879</td>\n",
       "      <td>0.396364</td>\n",
       "      <td>1</td>\n",
       "      <td>darkblue</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>-2.083954</td>\n",
       "      <td>0.643529</td>\n",
       "      <td>1</td>\n",
       "      <td>darkblue</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>...</th>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>153</th>\n",
       "      <td>0.700526</td>\n",
       "      <td>0.133751</td>\n",
       "      <td>0</td>\n",
       "      <td>gold</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>154</th>\n",
       "      <td>0.978974</td>\n",
       "      <td>-0.870358</td>\n",
       "      <td>0</td>\n",
       "      <td>gold</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>155</th>\n",
       "      <td>0.735332</td>\n",
       "      <td>-0.484162</td>\n",
       "      <td>0</td>\n",
       "      <td>gold</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>156</th>\n",
       "      <td>0.178436</td>\n",
       "      <td>-0.267893</td>\n",
       "      <td>0</td>\n",
       "      <td>gold</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>157</th>\n",
       "      <td>0.735332</td>\n",
       "      <td>-0.005280</td>\n",
       "      <td>0</td>\n",
       "      <td>gold</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>158 rows × 4 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "     Hemoglobin   Glucose  Class     Color\n",
       "0     -0.865744 -0.221549      1  darkblue\n",
       "1     -1.457446 -0.947597      1  darkblue\n",
       "2     -1.004968  3.841231      1  darkblue\n",
       "3     -2.814879  0.396364      1  darkblue\n",
       "4     -2.083954  0.643529      1  darkblue\n",
       "..          ...       ...    ...       ...\n",
       "153    0.700526  0.133751      0      gold\n",
       "154    0.978974 -0.870358      0      gold\n",
       "155    0.735332 -0.484162      0      gold\n",
       "156    0.178436 -0.267893      0      gold\n",
       "157    0.735332 -0.005280      0      gold\n",
       "\n",
       "[158 rows x 4 columns]"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "ckd = pd.DataFrame(\n",
    "    {'Hemoglobin':standard_units(ckd['Hemoglobin']),\n",
    "    'Glucose':standard_units(ckd['Glucose']),  \n",
    "    'Class':ckd['Class']}\n",
    ")\n",
    "\n",
    "color_table = pd.DataFrame(\n",
    "    {'Class':np.array([1, 0]),\n",
    "    'Color':np.array(['darkblue', 'gold'])}\n",
    ")\n",
    "\n",
    "ckd = pd.merge(ckd, color_table, on='Class')\n",
    "\n",
    "ckd"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here is a scatter plot of the two attributes, along with a red point corresponding to Alice, a new patient. Her value of hemoglobin is 0 (that is, at the average) and glucose 1.1 (that is, 1.1 SDs above average)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 28676 characters]\n",
      "text/plain": [
       "<Figure size 432x432 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "alice = np.array([0, 1.1])\n",
    "\n",
    "ckd_darkblue = ckd[ckd['Color'] == 'darkblue']\n",
    "ckd_gold = ckd[ckd['Color'] == 'gold']\n",
    "\n",
    "\n",
    "fig, ax = plt.subplots(figsize=(6,6))\n",
    "\n",
    "ax.scatter(ckd_darkblue['Hemoglobin'], \n",
    "           ckd_darkblue['Glucose'],  \n",
    "           label='Color=darkblue', \n",
    "           color='darkblue')\n",
    "\n",
    "ax.scatter(ckd_gold['Hemoglobin'], \n",
    "           ckd_gold['Glucose'],  \n",
    "           label='Color=gold', \n",
    "           color='gold')\n",
    "\n",
    "ax.scatter(alice[0], \n",
    "           alice[1],   \n",
    "           color='red', \n",
    "           s=30)\n",
    "\n",
    "x_label = 'White Blood Cell Count'\n",
    "\n",
    "y_label = 'Glucose'\n",
    "\n",
    "y_vals = ax.get_yticks()\n",
    "\n",
    "plt.ylabel(y_label)\n",
    "\n",
    "ax.legend(bbox_to_anchor=(1.04,1), loc=\"upper left\")\n",
    "\n",
    "plt.xlabel(x_label)\n",
    "\n",
    "plt.xlim(-4, 2)\n",
    "plt.ylim(-2, 6);\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To find the distance between Alice's point and any of the other points, we only need the values of the attributes:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "ckd_attributes = ckd[['Hemoglobin', 'Glucose']]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "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>Hemoglobin</th>\n",
       "      <th>Glucose</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>-0.865744</td>\n",
       "      <td>-0.221549</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>-1.457446</td>\n",
       "      <td>-0.947597</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>-1.004968</td>\n",
       "      <td>3.841231</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>-2.814879</td>\n",
       "      <td>0.396364</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>-2.083954</td>\n",
       "      <td>0.643529</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>...</th>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>153</th>\n",
       "      <td>0.700526</td>\n",
       "      <td>0.133751</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>154</th>\n",
       "      <td>0.978974</td>\n",
       "      <td>-0.870358</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>155</th>\n",
       "      <td>0.735332</td>\n",
       "      <td>-0.484162</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>156</th>\n",
       "      <td>0.178436</td>\n",
       "      <td>-0.267893</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>157</th>\n",
       "      <td>0.735332</td>\n",
       "      <td>-0.005280</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>158 rows × 2 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "     Hemoglobin   Glucose\n",
       "0     -0.865744 -0.221549\n",
       "1     -1.457446 -0.947597\n",
       "2     -1.004968  3.841231\n",
       "3     -2.814879  0.396364\n",
       "4     -2.083954  0.643529\n",
       "..          ...       ...\n",
       "153    0.700526  0.133751\n",
       "154    0.978974 -0.870358\n",
       "155    0.735332 -0.484162\n",
       "156    0.178436 -0.267893\n",
       "157    0.735332 -0.005280\n",
       "\n",
       "[158 rows x 2 columns]"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "ckd_attributes"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Each row consists of the coordinates of one point in our training sample. **Because the rows now consist only of numerical values**, it is possible to convert them to arrays.  For this, we use the function `np.array`, which converts any kind of sequential object, like a row, to an array. (Our old friend `make_array` is for *creating* arrays, not for *converting* other kinds of sequences to arrays.)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Hemoglobin   -2.814879\n",
       "Glucose       0.396364\n",
       "Name: 3, dtype: float64"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "ckd_attributes.iloc[3]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([-2.81487943,  0.39636401])"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.array(ckd_attributes.iloc[3])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This is very handy because we can now use array operations on the data in each row."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Distance Between Points When There are Two Attributes\n",
    "The main calculation we need to do is to find the distance between Alice's point and any other point. For this, the first thing we need is a way to compute the distance between any pair of points. \n",
    "\n",
    "How do we do this?  In 2-dimensional space, it's pretty easy.  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",
    "$$\n",
    "D = \\sqrt{(x_0-x_1)^2 + (y_0-y_1)^2}\n",
    "$$\n",
    "\n",
    "(Where did this come from?  It comes from the Pythogorean theorem: we have a right triangle with side lengths $x_0-x_1$ and $y_0-y_1$, and we want to find the length of the hypotenuse.)\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In the next section we'll see that this formula has a straightforward extension when there are more than two attributes. For now, let's use the formula and array operations to find the distance between Alice and the patient in Row 3."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(array([0. , 1.1]), array([-2.81487943,  0.39636401]))"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "patient3 = np.array(ckd_attributes.iloc[3])\n",
    "alice, patient3"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "2.9014909651272616"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "distance = np.sqrt(np.sum((alice - patient3)**2))\n",
    "distance"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We're going to need the distance between Alice and a bunch of points, so let's write a function called `distance` that computes the distance between any pair of points. The function will take two arrays, each containing the $(x, y)$ coordinates of a point.  (Remember, those are really the Hemoglobin and Glucose levels of a patient.)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [],
   "source": [
    "def distance(point1, point2):\n",
    "    \"\"\"Returns the Euclidean distance between point1 and point2.\n",
    "    \n",
    "    Each argument is an array containing the coordinates of a point.\"\"\"\n",
    "    return np.sqrt(np.sum((point1 - point2)**2))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "2.9014909651272616"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "distance(alice, patient3)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We have begun to build our classifier: the `distance` function is the first building block. Now let's work on the next piece."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "### Using `apply` on an Entire Row\n",
    "Recall that if you want to apply a function to each element of a column of a table, one way to do that is by the call `table_name.apply(function_name, column_label)`. This evaluates to an array consisting of the values of the function when we call it on each element of the column. So each entry of the array is based on the corresponding row of the table.\n",
    "\n",
    "If you use `apply` without specifying a column label, then the entire row is passed to the function. Let's see how this works on a very small table `t` containing the information about the first five patients in the training sample."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "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>Hemoglobin</th>\n",
       "      <th>Glucose</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>-0.865744</td>\n",
       "      <td>-0.221549</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>-1.457446</td>\n",
       "      <td>-0.947597</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>-1.004968</td>\n",
       "      <td>3.841231</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>-2.814879</td>\n",
       "      <td>0.396364</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>-2.083954</td>\n",
       "      <td>0.643529</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   Hemoglobin   Glucose\n",
       "0   -0.865744 -0.221549\n",
       "1   -1.457446 -0.947597\n",
       "2   -1.004968  3.841231\n",
       "3   -2.814879  0.396364\n",
       "4   -2.083954  0.643529"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "t = ckd_attributes.take(np.arange(5))\n",
    "t"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Just as an example, suppose that for each patient we want to know how unusual their most unusual attribute is.  Concretely, if a patient's hemoglobin level is further from the average than her glucose level, we want to know how far it is from the average.  If her glucose level is further from the average than her hemoglobin level, we want to know how far that is from the average instead.\n",
    "\n",
    "That's the same as taking the maximum of the absolute values of the two quantities. To do this for a particular row, we can convert the row to an array and use array operations."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [],
   "source": [
    "def max_abs(row):\n",
    "    return np.max(np.abs(np.array(row)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.8657439478031919"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "max_abs(t.iloc[0])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "And now we can apply `max_abs` to each row of the table `t`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0    0.865744\n",
       "1    1.457446\n",
       "2    3.841231\n",
       "3    2.814879\n",
       "4    2.083954\n",
       "dtype: float64"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "t.apply(max_abs, axis=1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This way of using `apply` will help us create the next building block of our classifier."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Alice's $k$ Nearest Neighbors\n",
    "If we want to classify Alice using a k-nearest neighbor classifier, we have to identify her $k$ nearest neighbors. What are the steps in this process? Suppose $k = 5$. Then the steps are:\n",
    "- **Step 1.** Find the distance between Alice and each point in the training sample.\n",
    "- **Step 2.** Sort the data table in increasing order of the distances.\n",
    "- **Step 3.** Take the top 5 rows of the sorted table.\n",
    "\n",
    "Steps 2 and 3 seem straightforward, provided we have the distances. So let's focus on Step 1.\n",
    "\n",
    "Here's Alice:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([0. , 1.1])"
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "alice"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "What we need is a function that finds the distance between Alice and another point whose coordinates are contained in a row. The function `distance` returns the distance between any two points whose coordinates are in arrays. We can use that to define `distance_from_alice`, which takes a row as its argument and returns the distance between that row and Alice."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [],
   "source": [
    "def distance_from_alice(row):\n",
    "    \"\"\"Returns distance between Alice and a row of the attributes table\"\"\"\n",
    "    return distance(alice, np.array([row]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "2.9014909651272616"
      ]
     },
     "execution_count": 24,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "distance_from_alice(ckd_attributes.iloc[3])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now we can `apply` the function `distance_from_alice` to each row of `ckd_attributes`, and augment the table `ckd` with the distances. Step 1 is complete!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [],
   "source": [
    "distances = ckd_attributes.apply(distance_from_alice, axis=1)\n",
    "ckd_with_distances = ckd.copy()\n",
    "ckd_with_distances['Distance from Alice'] = distances"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "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>Hemoglobin</th>\n",
       "      <th>Glucose</th>\n",
       "      <th>Class</th>\n",
       "      <th>Color</th>\n",
       "      <th>Distance from Alice</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>-0.865744</td>\n",
       "      <td>-0.221549</td>\n",
       "      <td>1</td>\n",
       "      <td>darkblue</td>\n",
       "      <td>1.579875</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>-1.457446</td>\n",
       "      <td>-0.947597</td>\n",
       "      <td>1</td>\n",
       "      <td>darkblue</td>\n",
       "      <td>2.513325</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>-1.004968</td>\n",
       "      <td>3.841231</td>\n",
       "      <td>1</td>\n",
       "      <td>darkblue</td>\n",
       "      <td>2.919641</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>-2.814879</td>\n",
       "      <td>0.396364</td>\n",
       "      <td>1</td>\n",
       "      <td>darkblue</td>\n",
       "      <td>2.901491</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>-2.083954</td>\n",
       "      <td>0.643529</td>\n",
       "      <td>1</td>\n",
       "      <td>darkblue</td>\n",
       "      <td>2.133361</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>153</th>\n",
       "      <td>0.700526</td>\n",
       "      <td>0.133751</td>\n",
       "      <td>0</td>\n",
       "      <td>gold</td>\n",
       "      <td>1.193471</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>154</th>\n",
       "      <td>0.978974</td>\n",
       "      <td>-0.870358</td>\n",
       "      <td>0</td>\n",
       "      <td>gold</td>\n",
       "      <td>2.200159</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>155</th>\n",
       "      <td>0.735332</td>\n",
       "      <td>-0.484162</td>\n",
       "      <td>0</td>\n",
       "      <td>gold</td>\n",
       "      <td>1.746506</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>156</th>\n",
       "      <td>0.178436</td>\n",
       "      <td>-0.267893</td>\n",
       "      <td>0</td>\n",
       "      <td>gold</td>\n",
       "      <td>1.379482</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>157</th>\n",
       "      <td>0.735332</td>\n",
       "      <td>-0.005280</td>\n",
       "      <td>0</td>\n",
       "      <td>gold</td>\n",
       "      <td>1.327537</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>158 rows × 5 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "     Hemoglobin   Glucose  Class     Color  Distance from Alice\n",
       "0     -0.865744 -0.221549      1  darkblue             1.579875\n",
       "1     -1.457446 -0.947597      1  darkblue             2.513325\n",
       "2     -1.004968  3.841231      1  darkblue             2.919641\n",
       "3     -2.814879  0.396364      1  darkblue             2.901491\n",
       "4     -2.083954  0.643529      1  darkblue             2.133361\n",
       "..          ...       ...    ...       ...                  ...\n",
       "153    0.700526  0.133751      0      gold             1.193471\n",
       "154    0.978974 -0.870358      0      gold             2.200159\n",
       "155    0.735332 -0.484162      0      gold             1.746506\n",
       "156    0.178436 -0.267893      0      gold             1.379482\n",
       "157    0.735332 -0.005280      0      gold             1.327537\n",
       "\n",
       "[158 rows x 5 columns]"
      ]
     },
     "execution_count": 26,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "ckd_with_distances"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For Step 2, let's sort the table in increasing order of distance:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "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>Hemoglobin</th>\n",
       "      <th>Glucose</th>\n",
       "      <th>Class</th>\n",
       "      <th>Color</th>\n",
       "      <th>Distance from Alice</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>14</th>\n",
       "      <td>0.839750</td>\n",
       "      <td>1.215099</td>\n",
       "      <td>1</td>\n",
       "      <td>darkblue</td>\n",
       "      <td>0.847601</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>35</th>\n",
       "      <td>-0.970162</td>\n",
       "      <td>1.276890</td>\n",
       "      <td>1</td>\n",
       "      <td>darkblue</td>\n",
       "      <td>0.986156</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>84</th>\n",
       "      <td>-0.030400</td>\n",
       "      <td>0.087407</td>\n",
       "      <td>0</td>\n",
       "      <td>gold</td>\n",
       "      <td>1.013049</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>152</th>\n",
       "      <td>0.143630</td>\n",
       "      <td>0.087407</td>\n",
       "      <td>0</td>\n",
       "      <td>gold</td>\n",
       "      <td>1.022728</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>-0.413266</td>\n",
       "      <td>2.049282</td>\n",
       "      <td>1</td>\n",
       "      <td>darkblue</td>\n",
       "      <td>1.035338</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>2</th>\n",
       "      <td>-1.004968</td>\n",
       "      <td>3.841231</td>\n",
       "      <td>1</td>\n",
       "      <td>darkblue</td>\n",
       "      <td>2.919641</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>12</th>\n",
       "      <td>-2.292790</td>\n",
       "      <td>-0.854910</td>\n",
       "      <td>1</td>\n",
       "      <td>darkblue</td>\n",
       "      <td>3.013065</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>41</th>\n",
       "      <td>-0.378460</td>\n",
       "      <td>4.520935</td>\n",
       "      <td>1</td>\n",
       "      <td>darkblue</td>\n",
       "      <td>3.441806</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>42</th>\n",
       "      <td>-3.685029</td>\n",
       "      <td>0.689873</td>\n",
       "      <td>1</td>\n",
       "      <td>darkblue</td>\n",
       "      <td>3.707782</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>36</th>\n",
       "      <td>-0.761326</td>\n",
       "      <td>5.540492</td>\n",
       "      <td>1</td>\n",
       "      <td>darkblue</td>\n",
       "      <td>4.505285</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>158 rows × 5 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "     Hemoglobin   Glucose  Class     Color  Distance from Alice\n",
       "14     0.839750  1.215099      1  darkblue             0.847601\n",
       "35    -0.970162  1.276890      1  darkblue             0.986156\n",
       "84    -0.030400  0.087407      0      gold             1.013049\n",
       "152    0.143630  0.087407      0      gold             1.022728\n",
       "6     -0.413266  2.049282      1  darkblue             1.035338\n",
       "..          ...       ...    ...       ...                  ...\n",
       "2     -1.004968  3.841231      1  darkblue             2.919641\n",
       "12    -2.292790 -0.854910      1  darkblue             3.013065\n",
       "41    -0.378460  4.520935      1  darkblue             3.441806\n",
       "42    -3.685029  0.689873      1  darkblue             3.707782\n",
       "36    -0.761326  5.540492      1  darkblue             4.505285\n",
       "\n",
       "[158 rows x 5 columns]"
      ]
     },
     "execution_count": 27,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "sorted_by_distance = ckd_with_distances.sort_values(by=['Distance from Alice'])\n",
    "sorted_by_distance"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Step 3: The top 5 rows correspond to Alice's 5 nearest neighbors; you can replace 5 by any other positive integer."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "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>Hemoglobin</th>\n",
       "      <th>Glucose</th>\n",
       "      <th>Class</th>\n",
       "      <th>Color</th>\n",
       "      <th>Distance from Alice</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>14</th>\n",
       "      <td>0.839750</td>\n",
       "      <td>1.215099</td>\n",
       "      <td>1</td>\n",
       "      <td>darkblue</td>\n",
       "      <td>0.847601</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>35</th>\n",
       "      <td>-0.970162</td>\n",
       "      <td>1.276890</td>\n",
       "      <td>1</td>\n",
       "      <td>darkblue</td>\n",
       "      <td>0.986156</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>84</th>\n",
       "      <td>-0.030400</td>\n",
       "      <td>0.087407</td>\n",
       "      <td>0</td>\n",
       "      <td>gold</td>\n",
       "      <td>1.013049</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>152</th>\n",
       "      <td>0.143630</td>\n",
       "      <td>0.087407</td>\n",
       "      <td>0</td>\n",
       "      <td>gold</td>\n",
       "      <td>1.022728</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>-0.413266</td>\n",
       "      <td>2.049282</td>\n",
       "      <td>1</td>\n",
       "      <td>darkblue</td>\n",
       "      <td>1.035338</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "     Hemoglobin   Glucose  Class     Color  Distance from Alice\n",
       "14     0.839750  1.215099      1  darkblue             0.847601\n",
       "35    -0.970162  1.276890      1  darkblue             0.986156\n",
       "84    -0.030400  0.087407      0      gold             1.013049\n",
       "152    0.143630  0.087407      0      gold             1.022728\n",
       "6     -0.413266  2.049282      1  darkblue             1.035338"
      ]
     },
     "execution_count": 28,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "alice_5_nearest_neighbors = sorted_by_distance.take(np.arange(5))\n",
    "alice_5_nearest_neighbors"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Three of Alice's five nearest neighbors are blue points and two are gold. So a 5-nearest neighbor classifier would classify Alice as blue: it would predict that Alice has chronic kidney disease.\n",
    "\n",
    "The graph below zooms in on Alice and her five nearest neighbors. The two gold ones just inside the circle directly below the red point. The classifier says Alice is more like the three blue ones around her."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {
    "tags": [
     "remove_input"
    ]
   },
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 34996 characters]\n",
      "text/plain": [
       "<Figure size 576x576 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "radius = sorted_by_distance['Distance from Alice'].iloc[4]+0.014\n",
    "theta = np.arange(0, 2*np.pi+1, 2*np.pi/200)\n",
    "\n",
    "alice = np.array([0, 1.1])\n",
    "\n",
    "ckd_darkblue = ckd[ckd['Color'] == 'darkblue']\n",
    "ckd_gold = ckd[ckd['Color'] == 'gold']\n",
    "\n",
    "fig, ax = plt.subplots(figsize=(8,8))\n",
    "\n",
    "ax.scatter(ckd_darkblue['Hemoglobin'], \n",
    "           ckd_darkblue['Glucose'],   \n",
    "           color='darkblue')\n",
    "\n",
    "ax.scatter(ckd_gold['Hemoglobin'], \n",
    "           ckd_gold['Glucose'],   \n",
    "           color='gold')\n",
    "\n",
    "ax.scatter(alice[0], \n",
    "           alice[1],   \n",
    "           color='red', \n",
    "           s=30)\n",
    "\n",
    "ax.plot(radius*np.cos(theta)+alice.item(0), radius*np.sin(theta)+alice.item(1), color='g', lw=1.5, zorder=10);\n",
    "\n",
    "plt.xlim(-2, 2.5)\n",
    "plt.ylim(-2, 2.5);\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We are well on our way to implementing our k-nearest neighbor classifier. In the next two sections we will put it together and assess its accuracy."
   ]
  }
 ],
 "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
}
