---
jupyter:
  anaconda-cloud: {}
  jupytext:
    notebook_metadata_filter: all,-language_info
    text_representation:
      extension: .Rmd
      format_name: rmarkdown
      format_version: '1.2'
      jupytext_version: 1.5.1
  kernelspec:
    display_name: Python 3
    language: python
    name: python3
---

# Rows of tables

```{python tags=c("hide-cell")}
# HIDDEN
import numpy as np
# %matplotlib inline
import matplotlib.pyplot as plt
plt.style.use('fivethirtyeight')
import pandas as pd
```

```{python tags=c("hide-cell")}
# HIDDEN

def standard_units(x):
    return (x - np.mean(x))/np.std(x)
```

Now that we have a qualitative understanding of nearest neighbor classification, it's time to implement our classifier.

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.

So let's start by taking a closer look at rows.

Here is the original table `ckd` containing data on patients who were tested for chronic kidney disease.

The data file is {download}`ckd.csv <../data/ckd.csv>`.

```{python}
ckd_full = pd.read_csv('ckd.csv')
ckd_full.head()
```

The data corresponding to the first patient is in row 0 of the table, consistent with Python's indexing system.

We want to fetch the data for this row.

You have already seen how to select rows with boolean arrays, and the `loc` attribute of the data frame.

Now we need to select a row by *index* \- 0, 1, 2 etc.

We do this with Pandas' *indexing* selection, attached to the `iloc` attribute of the data frame, for Indexed LOCate, like this:

```{python}
first_row = ckd_full.iloc[0]
first_row
```

If the display for this row looks suspiciously like the display you see when fetching a single column from a data frame, this is not a co-incidence.  The row is also a Pandas `Series`:

```{python}
type(first_row)
```

Notice that the data type (`dtype`) of the row is `object`, and
not something simpler, like a floating point or integer. This
is because the elements can be of different types, so the
Series needs to use the very general `object` type to store all
the values. For example, some of the elements of the row above
are strings (like `'abnormal'`) and some are numerical. So the
row can't be converted into floating point values or integers.

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 item at index position 3. We can fetch the value with indexing. Again, we use `iloc`, this time indexing into the `Series`.

```{python}
first_row.iloc[3]
```

## Converting Rows to Numpy arrays

Rows whose elements are all numerical can be converted to numerical Numpy arrays.  Converting a row to a numerical array gives us access to arithmetic operations and other nice NumPy functions, so it is often useful.

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.

```{python}
ckd = pd.DataFrame()
ckd['Hemoglobin'] = standard_units(ckd_full['Hemoglobin'])
ckd['Glucose'] = standard_units(ckd_full['Blood Glucose Random'])
ckd['Class'] = ckd_full['Class']
ckd.head()
```

We add the colors for each point, to reflect the Class (with kidney disease or without).

```{python}
ckd['Color'] = 'darkblue'
ckd.loc[ckd['Class'] == 0, 'Color'] = 'gold'
ckd.head()
```

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).

```{python}
alice = np.array([0, 1.1])
ckd.plot.scatter('Hemoglobin', 'Glucose',
                 c=ckd['Color'])
plt.scatter(alice[0], alice[1], color='red', s=30);
```

To find the distance between Alice's point and any of the other points, we only need the values of the attributes:

```{python}
# Select Hemoglobin and Glucose columns from the data frame
ckd_attributes = ckd.loc[:, ['Hemoglobin', 'Glucose']]
ckd_attributes.head()
```

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 numerical arrays.  For this, we use the function `np.array`, which converts any kind of sequential object, like a row, to an array.

```{python}
ckd_attributes.iloc[3]
```

```{python}
np.array(ckd_attributes.iloc[3])
```

This is very handy because we can now use array operations on the data in each row.


## Distance Between Points When There are Two Attributes

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.

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

$$
D = \sqrt{(x_0-x_1)^2 + (y_0-y_1)^2}
$$

(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.)


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.

```{python}
patient3 = np.array(ckd_attributes.iloc[3])
alice, patient3
```

```{python}
distance = np.sqrt(np.sum((alice - patient3)**2))
distance
```

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.)

```{python}
def distance(point1, point2):
    """Returns the Euclidean distance between point1 and point2.

    Each argument is an array containing the coordinates of a point."""
    return np.sqrt(np.sum((point1 - point2)**2))
```

```{python}
distance(alice, patient3)
```

We have begun to build our classifier: the `distance` function is the first building block. Now let's work on the next piece.


## Using `apply` on an Entire Row

Sometimes we want to be able to *apply* some function to a whole row of a data frame.

You won't be surprised to learn that Pandas has an `apply` method that can do this.

Let's see how this works on a very small table `t` containing the information about the first five patients in the training sample.  Here we are using `iloc` again, to get values from the data frame by index.  In this case, we want the first five rows.

```{python}
t = ckd_attributes.iloc[0:5]
t
```

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.

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.

```{python}
def max_abs(row):
    return np.max(np.abs(np.array(row)))
```

```{python}
max_abs(t.iloc[4])
```

And now we can apply `max_abs` to each row of the table `t`. We pass the `axis` argument to tell Pandas to apply the function along the *rows* (and therefore along the second axis).

```{python}
t.apply(max_abs, axis=1)
```

This way of using `apply` will help us create the next building block of our classifier.


## Alice's $k$ Nearest Neighbors

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:

- **Step 1.** Find the distance between Alice and each point in the training sample.
- **Step 2.** Sort the data table in increasing order of the distances.
- **Step 3.** Take the top 5 rows of the sorted table.

Steps 2 and 3 seem straightforward, provided we have the distances. So let's focus on Step 1.

Here's Alice:

```{python}
alice
```

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.

```{python}
def distance_from_alice(row):
    """Returns distance between Alice and a row of the attributes table"""
    return distance(alice, np.array(row))
```

```{python}
distance_from_alice(ckd_attributes.iloc[3])
```

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!

```{python}
distances = ckd_attributes.apply(distance_from_alice, axis=1)
ckd_with_distances = ckd.copy()
ckd_with_distances['Distance from Alice'] = distances
ckd_with_distances.head()
```

For Step 2, let's sort the table in increasing order of distance:

```{python}
sorted_by_distance = ckd_with_distances.sort_values('Distance from Alice')
sorted_by_distance.head()
```

Step 3: The top 5 rows correspond to Alice's 5 nearest neighbors; you can replace 5 by any other positive integer.

```{python}
alice_5_nearest_neighbors = sorted_by_distance.iloc[:5]
alice_5_nearest_neighbors
```

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.

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.

```{python tags=c("remove-input")}
# NO CODE
plt.figure(figsize=(8,8))
plt.scatter(ckd['Hemoglobin'], ckd['Glucose'],
            c=ckd['Color'], s=40)
plt.scatter(alice[0], alice[1], color='red', s=40)
radius = sorted_by_distance['Distance from Alice'].iloc[4]+0.014
theta = np.arange(0, 2*np.pi+1, 2*np.pi/200)
plt.plot(radius * np.cos(theta) + alice[0],
         radius * np.sin(theta) + alice[1],
         color='g', lw=1.5);
plt.xlim(-2, 2.5)
plt.ylim(-2, 2.5);
```

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.

{ucb-page}`Rows_of_Tables`
