14.2. Nearest Neighbors#

Hide code cell source

path_data = '../../data/'

import numpy as np
import pandas as pd

import matplotlib.pyplot as plt
%matplotlib inline

# Real data: 12,330 online shopping sessions (UCI Online Shoppers Purchasing Intention).
sessions = pd.read_csv(path_data + 'online_shoppers.csv')

# Colors used in every picture of this section.
colors = {'no purchase': 'tab:blue', 'purchase': 'tab:orange'}

def standard_units(x):
    """Convert values to standard units: the number of SDs above or below the average."""
    return (x - x.mean()) / x.std(ddof=0)

Suppose an online retailer wants to know, while a visitor is still browsing, whether the session will end in a purchase. It has a record of thousands of past sessions, and each one is labeled “purchase” or “no purchase”. The simplest way to use that record is to find the past session that looks most like the current one and guess that the current session will turn out the same way.

That idea is called the nearest neighbor method, and it is the first classifier in this chapter that learns its rule from labeled examples. This section builds it from the ground up: what “most like” means, what the method does across the whole space of possible sessions, how voting among several neighbors makes it steadier, and how to write the method as a short program. Section Classification introduced the data and the problem; Section Training, Testing, and Accuracy asks how well the method works on sessions it has not seen.

14.2.1. The Idea of a Nearest Neighbor#

The data come from a study of an online retailer’s website: 12,330 sessions over one year, each labeled by whether the session ended in a purchase. The study is real and public (Sakar and others, Neural Computing and Applications, 2019; UCI Machine Learning Repository, CC BY 4.0). This section uses two attributes from Section Classification:

  • page_value: how valuable the pages in the session tend to be, measured as the average dollar value of the pages the visitor saw, based on the sales that followed visits to them. Sessions that visit no valuable pages have a page value of 0. As Classification cautions, page value is only fully known after a visit, so read this chapter’s accuracies as a best case.

  • exit_rate: how often the pages in the session were the last page of a visit. A high exit rate means that visitors tend to leave from these pages.

Drawing 12,330 points would produce a blob, so the code draws a random sample of 300 sessions. These 300 sessions are the training set: the past cases, with known labels, that new sessions will be compared against. The code keeps the three columns it needs and converts the two attributes to standard units (explained again in the next subsection), so that both are measured on the same scale.

training_rows = sessions.sample(300, random_state=14).reset_index(drop=True)

sample = pd.DataFrame({
    'page_value': standard_units(training_rows['page_value']),
    'exit_rate': standard_units(training_rows['exit_rate']),
    'outcome': training_rows['outcome'],
})

print(sample['outcome'].value_counts().to_string())

print()

print('Sessions with a page value of 0:', (training_rows['page_value'] == 0).sum())
sample.head()


###
# print(sample['page_value'].max())
outcome
no purchase    269
purchase        31

Sessions with a page value of 0: 238
page_value exit_rate outcome
0 -0.253053 -0.801144 no purchase
1 -0.253053 2.993514 no purchase
2 -0.253053 1.500698 no purchase
3 0.235172 -0.560167 no purchase
4 -0.253053 -0.255101 no purchase

In this sample, 31 of the 300 sessions ended in a purchase, about 10% (all 12,330 sessions have 15.5% buyers, so this random sample happens to hold fewer). Now plot them. Of the 300 sessions, 238 have a page value of exactly 0, so their points sit on top of one another in a single vertical stripe. The points are drawn partly transparent, so that darker colors show where several sessions overlap.

def draw_sample(ax):
    """Scatter the training sample, one color per outcome."""
    for label in ['no purchase', 'purchase']:
        rows = sample[sample['outcome'] == label]
        ax.scatter(rows['page_value'], rows['exit_rate'], s=45, alpha=0.45,
                   color=colors[label], label=label)
    ax.set_xlabel('Page value (standard units)')
    ax.set_ylabel('Exit rate (standard units)')

fig, ax = plt.subplots(figsize=(7, 4.5))
draw_sample(ax)
ax.set_title('Buyers sit at higher page values and lower exit rates')
ax.legend(title='Outcome')
plt.show()
../../_images/695a2baa41f8d2da6264878227bc504b3c82365026dd2e18e4f4d84ed6867067.png

Two things in the picture matter. The purchases (orange) are concentrated toward the bottom and the right: lower exit rate, higher page value. Most buyers have a positive page value and a below-average exit rate. But the no-purchase sessions (blue) are everywhere, including at the right and bottom, so no simple line separates the two groups perfectly. One session has a page value about 13 SDs above average, far to the right of the rest.

Now a new session arrives. It has a page value of 8 and an exit rate of 0.02, and you do not yet know whether it will end in a purchase. Place it on the same picture by converting it to standard units, using the training set’s average and SD for each attribute. (Section Training, Testing, and Accuracy explains why the scaling must come from the training set and not from the new session.) Then look for the training session closest to it.

new_session = {'page_value': 8, 'exit_rate': 0.02}

new_x = (new_session['page_value'] - training_rows['page_value'].mean()) / training_rows['page_value'].std(ddof=0)
new_y = (new_session['exit_rate'] - training_rows['exit_rate'].mean()) / training_rows['exit_rate'].std(ddof=0)
print('New session in standard units:', round(new_x, 2), round(new_y, 2))

# Straight-line distance from the new session to every training session
dist = np.sqrt((sample['page_value'] - new_x) ** 2 + (sample['exit_rate'] - new_y) ** 2)
nearest = dist.idxmin()
print('Nearest training session: row', nearest, '(distance', round(dist[nearest], 3), ')')
print('Its outcome:', sample.loc[nearest, 'outcome'])
New session in standard units: 0.18 -0.51
Nearest training session: row 3 (distance 0.069 )
Its outcome: no purchase
fig, ax = plt.subplots(figsize=(7, 4.5))
draw_sample(ax)
ax.scatter(new_x, new_y, s=160, marker='*', color='black', label='new session', zorder=3)
ax.plot([new_x, sample.loc[nearest, 'page_value']],
        [new_y, sample.loc[nearest, 'exit_rate']], color='black', linewidth=1.5, zorder=2)
ax.set_xlim(-0.5, 3)
ax.set_ylim(-1.2, 1.5)
ax.set_title("The new session's nearest neighbor is a non-buyer")
ax.legend(title='Outcome')
plt.show()
../../_images/eb36dedb560524faa3acea999c2253fd557989362cc1a0c9d57bdbc5341ea6fa.png

The plot above shows the same training set, cropped to the region around the new session (the star). The closest point to the star is the blue one just to its right, a session that did not end in a purchase. The nearest neighbor classifier therefore predicts “no purchase” for the new session. In general, the method is:

  1. Measure the distance from the new case to every case in the training set.

  2. Find the training case with the smallest distance, its nearest neighbor.

  3. Predict the nearest neighbor’s label.

The method has no formula and no fitted line. The training set is the model. To make this precise, you need to say what “distance” means, which is the next subsection.

### Exercise: Find the Nearest Neighbor
# Four past sessions (page value, exit rate in standard units) and whether they bought.
#   1. Compute the straight-line distance from the new session to each past session.
#   2. Find the nearest session and print its index (counting from 0) and label.
#   3. Print the new session's predicted label.
# Print exactly:
# Nearest session: 2
# Its label: purchase
# Predicted: purchase
import numpy as np

past = np.array([[-0.5, 1.0], [0.0, 0.5], [1.5, -0.5], [2.0, -1.0]])
labels = ['no purchase', 'no purchase', 'purchase', 'purchase']
new = np.array([1.2, -0.2])
### Your code starts here.




### Your code ends here.

Hide code cell source

### Solution
import numpy as np

past = np.array([[-0.5, 1.0], [0.0, 0.5], [1.5, -0.5], [2.0, -1.0]])
labels = ['no purchase', 'no purchase', 'purchase', 'purchase']
new = np.array([1.2, -0.2])

distances = np.sqrt(((past - new) ** 2).sum(axis=1))
ex_nearest = distances.argmin()

print('Nearest session:', ex_nearest)
print('Its label:', labels[ex_nearest])
print('Predicted:', labels[ex_nearest])
Nearest session: 2
Its label: purchase
Predicted: purchase

14.2.2. Measuring Similarity#

Two sessions are “similar” when their attributes are close. Turning that into a number takes two things: attributes on comparable scales, and a way to combine the differences into one distance.

14.2.2.1. Standard Units#

A page value is a dollar amount, with an average of about 4.6 and a SD of about 18.4 in the sample. An exit rate is a fraction between 0 and 0.2, with an average of about 0.046 and a SD of about 0.051. A difference of 1 means something very different for the two. To put them on one scale, convert each attribute to standard units: the number of SDs a value is above (positive) or below (negative) the attribute’s average. This is the same conversion used for correlation in Chapter 12; see Section Correlation.

\[\text{standard units} = \frac{\text{value} - \text{average}}{\text{SD}}\]

The code cell near the top of this page defines standard_units, and sample was built with it. Here are the first three training sessions in original units and in standard units.

comparison = pd.DataFrame({
    'page_value': training_rows['page_value'].head(3).round(2),
    'exit_rate': training_rows['exit_rate'].head(3).round(3),
    'page_value (su)': sample['page_value'].head(3).round(2),
    'exit_rate (su)': sample['exit_rate'].head(3).round(2),
})
print('Average page value:', round(training_rows['page_value'].mean(), 2),
      ' SD:', round(training_rows['page_value'].std(ddof=0), 2))
print('Average exit rate: ', round(training_rows['exit_rate'].mean(), 3),
      ' SD:', round(training_rows['exit_rate'].std(ddof=0), 3))
comparison
Average page value: 4.64  SD: 18.35
Average exit rate:  0.046  SD: 0.051
page_value exit_rate page_value (su) exit_rate (su)
0 0.0 0.005 -0.25 -0.80
1 0.0 0.200 -0.25 2.99
2 0.0 0.123 -0.25 1.50

In standard units, a value of 0 means “average,” 1 means “one SD above average,” and -1 means “one SD below.” A page value and an exit rate can now be compared directly: a session at +2 on both is unusually high on both.

14.2.2.2. Distance in Two Attributes#

Once two attributes share a scale, each session is a point on the plot, and the distance between two sessions is the straight-line distance between their points. If one session has standard-unit values \((x_0, y_0)\) and another has \((x_1, y_1)\), the Pythagorean theorem gives the Euclidean distance:

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

Take training sessions 0 and 1.

a = sample.loc[0, ['page_value', 'exit_rate']].astype(float)
b = sample.loc[1, ['page_value', 'exit_rate']].astype(float)
print('Session 0:', a.round(2).tolist())
print('Session 1:', b.round(2).tolist())

by_hand = np.sqrt((a['page_value'] - b['page_value']) ** 2 + (a['exit_rate'] - b['exit_rate']) ** 2)
print('Distance:', round(by_hand, 3))
Session 0: [-0.25, -0.8]
Session 1: [-0.25, 2.99]
Distance: 3.795

Session 1 has a much higher exit rate than session 0 (nearly 4 SDs), and nearly the same page value, so nearly all of the distance comes from the exit rate. Small distances mean similar sessions; the nearest neighbor of a new session is the training session at the smallest distance.

14.2.2.3. Why Scale Matters#

Distance adds up squared differences across attributes, so an attribute with large numbers can drown out the others. Consider product_duration, the seconds a visitor spent on product pages. Its SD in the sample is about 1,563, while the SD of the exit rate is about 0.05. A difference of one SD is about 1,563 seconds in one attribute and 0.05 in the other.

To see the damage, look for the 5 sessions nearest to a new session in the plane of exit rate and product duration, once with the original units and once with standard units. The new session spent 600 seconds on product pages and has an exit rate of 0.02.

raw = training_rows[['exit_rate', 'product_duration']]
new_raw = np.array([0.02, 600])

# Five nearest sessions in original units
d_raw = np.sqrt(((raw - new_raw) ** 2).sum(axis=1))
print('Original units:')
print(raw.loc[d_raw.sort_values().index[:5]].round(3).to_string())

# Five nearest sessions in standard units (scaled with the training set's average and SD)
new_su = (new_raw - raw.mean().values) / raw.std(ddof=0).values
d_su = np.sqrt(((raw.apply(standard_units) - new_su) ** 2).sum(axis=1))
print()
print('Standard units:')
print(raw.loc[d_su.sort_values().index[:5]].round(3).to_string())
Original units:
     exit_rate  product_duration
96       0.034             603.3
64       0.011             606.0
80       0.004             593.3
269      0.053             585.6
193      0.011             576.3

Standard units:
     exit_rate  product_duration
12       0.020             535.2
235      0.016             552.3
215      0.024             570.5
259      0.018             710.0
260      0.017             725.3

In original units, the five “nearest” sessions all spent between 576 and 606 seconds, but their exit rates range from 0.004 to 0.053, nearly one SD of the exit rate, because a difference of 0.05 is invisible next to a difference of 30 seconds. Only the duration decided who the neighbors were. In standard units, both attributes count: the five neighbors have exit rates between 0.016 and 0.024, close to the new session’s 0.02, and durations between 535 and 725 seconds, which are close in SDs. The lesson: before measuring distance, convert every attribute to standard units. Otherwise, whichever attribute has the biggest numbers decides who the neighbors are.

### Exercise: Standardize, Then Measure
# A retailer compares two sessions on page value (dollars) and exit rate.
# The training sessions have an average page value of 5 with SD 20,
# and an average exit rate of 0.05 with SD 0.05.
#   1. Convert each session's page value and exit rate to standard units.
#   2. Compute the distance between the two sessions in standard units,
#      rounded to 3 decimals.
# Print exactly:
# Session A (su): [1.0, -1.0]
# Session B (su): [0.0, 1.0]
# Distance: 2.236
import numpy as np

avg = np.array([5, 0.05])
sd = np.array([20, 0.05])
session_a = np.array([25, 0.0])
session_b = np.array([5, 0.10])
### Your code starts here.




### Your code ends here.

Hide code cell source

### Solution
import numpy as np

avg = np.array([5, 0.05])
sd = np.array([20, 0.05])
session_a = np.array([25, 0.0])
session_b = np.array([5, 0.10])

a_su = (session_a - avg) / sd
b_su = (session_b - avg) / sd

print('Session A (su):', a_su.round(2).tolist())
print('Session B (su):', b_su.round(2).tolist())
print('Distance:', round(np.sqrt(np.sum((a_su - b_su) ** 2)), 3))
Session A (su): [1.0, -1.0]
Session B (su): [0.0, 1.0]
Distance: 2.236

14.2.3. Decision Boundaries#

So far you have classified one new session. Think of each session as a point in a feature space, where each attribute is one axis. A classifier is useful because it can classify any session. To see what the nearest neighbor method does everywhere at once, ask it to classify a grid of hypothetical sessions that covers the whole picture, 160 values of page value by 120 values of exit rate, and color each grid point by the prediction. The function nearest_labels below finds, for each grid point, the closest of the 300 training sessions and returns its label.

nearest_labels and draw_regions are plotting helpers. They do for 19,200 grid points at once what classify in Nearest Neighbors by Hand (later in this section) does for one session: compute distances, take the nearest, and vote. The NumPy array tricks that make this fast are not something you need to learn; read the comments for the steps and focus on the picture.

def nearest_labels(points, k=1):
    """Predicted outcome for each row of points (n x 2) by majority vote of the k nearest training sessions."""
    train = sample[['page_value', 'exit_rate']].to_numpy()
    is_buyer = (sample['outcome'] == 'purchase').to_numpy()
    # distance from every point to every training session: an n x 300 table
    diff = points[:, None, :] - train[None, :, :]
    dist = np.sqrt((diff ** 2).sum(axis=2))
    nearest_k = np.argsort(dist, axis=1)[:, :k]
    buyer_votes = is_buyer[nearest_k].sum(axis=1)
    return buyer_votes > k / 2          # True means "purchase"

xs = np.linspace(-0.5, 4, 160)
ys = np.linspace(-1.2, 3.2, 120)
gx, gy = np.meshgrid(xs, ys)
grid = np.column_stack([gx.ravel(), gy.ravel()])

pred_1 = nearest_labels(grid, k=1).reshape(gx.shape)
print('Share of the grid predicted to purchase (1-NN):', round(pred_1.mean(), 3))
Share of the grid predicted to purchase (1-NN): 0.144
from matplotlib.colors import ListedColormap
region_colors = ListedColormap(['#cfe2f3', '#fde0c5'])    # light blue, light orange

def draw_regions(ax, pred, title):
    ax.pcolormesh(gx, gy, pred.astype(int), cmap=region_colors, shading='auto')
    ax.grid(False)
    draw_sample(ax)
    ax.set_xlim(-0.5, 4)
    ax.set_ylim(-1.2, 3.2)
    ax.set_title(title)

fig, ax = plt.subplots(figsize=(7, 4.5))
draw_regions(ax, pred_1, '1-NN: every training session claims the area around it')
ax.legend(title='Outcome', loc='upper right')
plt.show()
../../_images/29ec6150843d4dba438ba57f5617e13b7549182e7264d3386e8f8dd329377fc7.png

The light-orange area is the decision region where the classifier predicts “purchase”, and the light-blue area is the region where it predicts “no purchase”. The edge between the two areas is the decision boundary: cross it and the prediction changes. Each training session claims the area closer to it than to any other session, so the boundary is jagged. A single buyer in a mostly blue neighborhood claims an orange patch around it, and a single non-buyer in an orange area does the same in reverse.

Those isolated patches are the weakness of 1-nearest neighbor. The classifier trusts every training label completely, including labels that are partly luck: a visitor with promising pages may leave without buying that day. A new session that lands next to such a case is classified on the basis of one session’s behavior. Using more neighbors makes the decision steadier.

### Exercise: Where the Prediction Changes
# Three past sessions (page value, exit rate in standard units) and their outcomes.
#   1. For each new session below (exit rate -0.5), find its nearest past session.
#   2. Print the 1-nearest neighbor prediction for each page value.
# Print exactly:
# Page value 0.5: no purchase
# Page value 0.8: no purchase
# Page value 1.1: purchase
# Page value 1.5: purchase
import numpy as np

ex_past = np.array([[0.0, 0.0], [2.0, -0.5], [1.0, 1.5]])
ex_labels = ['no purchase', 'purchase', 'no purchase']
ex_page_values = [0.5, 0.8, 1.1, 1.5]
### Your code starts here.




### Your code ends here.

Hide code cell source

### Solution
import numpy as np

ex_past = np.array([[0.0, 0.0], [2.0, -0.5], [1.0, 1.5]])
ex_labels = ['no purchase', 'purchase', 'no purchase']
ex_page_values = [0.5, 0.8, 1.1, 1.5]

for ex_x in ex_page_values:
    ex_point = np.array([ex_x, -0.5])
    ex_d = np.sqrt(((ex_past - ex_point) ** 2).sum(axis=1))
    print('Page value ' + str(ex_x) + ':', ex_labels[ex_d.argmin()])
# The prediction changes between 0.8 and 1.1: the decision boundary
# crosses this line at a page value of about 0.94.
Page value 0.5: no purchase
Page value 0.8: no purchase
Page value 1.1: purchase
Page value 1.5: purchase

14.2.4. k Nearest Neighbors#

Instead of relying on one neighbor, the k-nearest neighbor classifier finds the \(k\) training sessions closest to the new session and takes a majority vote of their labels: the prediction is whichever label is more common among the \(k\) neighbors. With \(k = 1\), this is the nearest neighbor method. Here is the new session again, with its 1, 3, 5, and 7 nearest neighbors.

order = dist.sort_values().index[:7]
nearest_7 = sample.loc[order, ['page_value', 'exit_rate', 'outcome']].round(2)
nearest_7['distance'] = dist[order].round(3).values
print(nearest_7.to_string())
print()

for k in [1, 3, 5, 7]:
    votes = sample.loc[order[:k], 'outcome'].value_counts()
    print(f'k = {k}: purchase {votes.get("purchase", 0)}, no purchase {votes.get("no purchase", 0)}'
          f' -> predict {votes.idxmax()}')
     page_value  exit_rate      outcome  distance
3          0.24      -0.56  no purchase     0.069
145        0.08      -0.49     purchase     0.101
94         0.19      -0.63     purchase     0.120
231        0.21      -0.64  no purchase     0.125
248        0.08      -0.60  no purchase     0.138
36         0.04      -0.53  no purchase     0.143
213        0.03      -0.49     purchase     0.149

k = 1: purchase 0, no purchase 1 -> predict no purchase
k = 3: purchase 2, no purchase 1 -> predict purchase
k = 5: purchase 2, no purchase 3 -> predict no purchase
k = 7: purchase 3, no purchase 4 -> predict no purchase

The prediction changes with \(k\): the nearest session is a non-buyer, but the second and third nearest are buyers, so with three neighbors the vote is 2 to 1 for “purchase”. Looking at five neighbors, the vote goes back to “no purchase”. When the closest sessions disagree this much, the new session sits in a mixed neighborhood, and no choice of \(k\) will make the prediction certain. Section Training, Testing, and Accuracy picks \(k\) with a validation set: sessions held back from the training data, so the test set can stay untouched until the end.

For two classes, choose an odd \(k\) (1, 3, 5, …). With an even \(k\), such as 4, the vote can be a tie, 2 to 2, and the method needs an extra rule for breaking it. An odd \(k\) cannot tie when there are only two classes.

Larger \(k\) also smooths the decision boundary. The next picture shows the regions for \(k = 1\), \(k = 5\), and \(k = 15\) on the same training sample.

fig, axes = plt.subplots(1, 3, figsize=(13, 4), sharey=True)
shares = {}
for ax, k in zip(axes, [1, 5, 15]):
    pred = nearest_labels(grid, k=k).reshape(gx.shape)
    shares[k] = pred.mean()
    draw_regions(ax, pred, f'k = {k}')
    ax.set_xticks(range(0, 5))
    ax.set_xlabel('Page value (su)')
axes[0].set_ylabel('Exit rate (su)')
axes[1].set_ylabel('')
axes[2].set_ylabel('')
plt.tight_layout()
plt.show()

for k, share in shares.items():
    print(f'k = {k:>2}: {share:.1%} of the grid is predicted "purchase"')
../../_images/10861a51f8c4630fef39c0e9d39bdb1b68cc86143d24711195eef4af09f8affe.png
k =  1: 14.4% of the grid is predicted "purchase"
k =  5: 11.9% of the grid is predicted "purchase"
k = 15: 13.1% of the grid is predicted "purchase"

With \(k = 1\) the boundary is made of sharp wedges and patches, one for each isolated buyer. With \(k = 5\) several of them have vanished, and with \(k = 15\) the area predicted “purchase” is mostly a single band along the bottom of the picture, where the exit rate is low, to the right of the stripe of sessions with a page value of 0. In all three pictures the orange area covers a small part of the grid (the printed shares are between 12% and 15%): buyers are few, and with \(k\) above 1 a buyer needs fellow buyers nearby to carry a vote. This is a first sign of the problem taken up in Sections Training, Testing, and Accuracy and Evaluating Classifiers: when buyers are rare, a classifier can look accurate while rarely predicting a purchase.

The choice of \(k\) is a tradeoff. A small \(k\) follows the training data closely and can chase noise; a large \(k\) is steady but can overlook real local patterns. This is the same idea as overfitting in regression; see Section Choosing Features and Avoiding Overfitting.

### Exercise: Majority Vote and Odd k
# The 7 nearest past sessions to a new session, nearest first, had these outcomes.
#   1. For k = 1, 3, 5, and 7, count the 'purchase' labels among the first k neighbors.
#   2. Predict 'purchase' if more than half of the k neighbors are purchases,
#      and 'no purchase' otherwise.
# Print exactly:
# k = 1: 1 purchase of 1 -> purchase
# k = 3: 1 purchase of 3 -> no purchase
# k = 5: 3 purchase of 5 -> purchase
# k = 7: 3 purchase of 7 -> no purchase
neighbors = ['purchase', 'no purchase', 'no purchase', 'purchase', 'purchase',
             'no purchase', 'no purchase']
### Your code starts here.




### Your code ends here.

Hide code cell source

### Solution
neighbors = ['purchase', 'no purchase', 'no purchase', 'purchase', 'purchase',
             'no purchase', 'no purchase']

for ex_k in [1, 3, 5, 7]:
    first_k = neighbors[:ex_k]
    n_purchase = first_k.count('purchase')
    prediction = 'purchase' if n_purchase > ex_k / 2 else 'no purchase'
    print(f'k = {ex_k}: {n_purchase} purchase of {ex_k} -> {prediction}')
k = 1: 1 purchase of 1 -> purchase
k = 3: 1 purchase of 3 -> no purchase
k = 5: 3 purchase of 5 -> purchase
k = 7: 3 purchase of 7 -> no purchase

14.2.5. Nearest Neighbors by Hand#

The pictures used two attributes so that you could see them. The method itself does not care how many attributes there are, and it is short enough to write as a few functions. The two subsections below do that with three attributes of a session: page value, exit rate, and product duration, all in standard units.

14.2.5.1. Distance Between Rows#

The nearest neighbor classifier needs one calculation over and over: the distance between two cases. Each case is a row of a table, and its attribute values are the coordinates of a point.

With two attributes, the straight-line (Euclidean) distance is the formula from Distance in Two Attributes. With three attributes, add a third squared difference, and with any number of attributes the rule is the same: subtract the coordinates, square the differences, add them up, and take the square root. A scatter plot cannot be drawn in 5 or 10 dimensions, but the computer has no trouble computing the distance.

To compute with a row, convert it to a NumPy array. A row of a DataFrame is a pandas Series; np.array turns it into an array of numbers, as long as every attribute in the row is numeric. Here are the first two sessions in the training table training, using all three attributes in standard units.

features = ['page_value', 'exit_rate', 'product_duration']

training = training_rows[features].apply(standard_units)
training['outcome'] = training_rows['outcome']

attributes = training.drop(columns=['outcome'])

session0 = np.array(attributes.iloc[0])
session1 = np.array(attributes.iloc[1])
session0.round(2), session1.round(2)
(array([-0.25, -0.8 , -0.35]), array([-0.25,  2.99, -0.78]))
round(float(np.sqrt(np.sum((session0 - session1) ** 2))), 3)
3.818

Why standard units? As in Why Scale Matters, now with three attributes: distance adds up the squared differences of all attributes, so an attribute measured on a large scale can drown out the others. In the original data, product duration is in seconds and often runs to thousands, while the exit rate never exceeds 0.2. Compare the squared differences between the same two sessions in original units and in standard units.

pd.DataFrame({
    'squared difference, original units': (training_rows[features].iloc[0] - training_rows[features].iloc[1]) ** 2,
    'squared difference, standard units': (training[features].iloc[0] - training[features].iloc[1]) ** 2,
}).round(3)
squared difference, original units squared difference, standard units
page_value 0.000 0.000
exit_rate 0.038 14.399
product_duration 440232.250 0.180

In original units, the squared difference in product duration (about 440,000 seconds squared) is more than ten million times the squared difference in exit rate (0.038), so the distance would be almost entirely about duration. In standard units, each attribute is measured in SDs from its average, so the three terms are on one scale. Here the two sessions differ most in exit rate (nearly 4 SDs) and only a little in duration (0.4 SD), and the distance reflects that. That is why training was built from the attributes in standard units before any distance was computed.

### Exercise: Distance Between Two Stores
# A retailer describes each store by three attributes in standard units.
#   1. Convert the rows for 'Downtown' and 'Airport' to arrays with np.array(stores.loc[...]).
#   2. Compute the distance between them, rounded to 3 decimals.
# Print exactly:
# Distance: 1.952
import numpy as np
import pandas as pd

stores = pd.DataFrame({
    'sales': [1.2, -0.4, 0.3],
    'foot_traffic': [0.8, 1.0, -1.1],
    'floor_area': [-0.5, 0.6, 0.9],
}, index=['Downtown', 'Airport', 'Mall'])
### Your code starts here.




### Your code ends here.

Hide code cell source

### Solution
import numpy as np
import pandas as pd

stores = pd.DataFrame({
    'sales': [1.2, -0.4, 0.3],
    'foot_traffic': [0.8, 1.0, -1.1],
    'floor_area': [-0.5, 0.6, 0.9],
}, index=['Downtown', 'Airport', 'Mall'])

downtown = np.array(stores.loc['Downtown'])
airport = np.array(stores.loc['Airport'])

print('Distance:', round(np.sqrt(np.sum((downtown - airport) ** 2)), 3))
Distance: 1.952

14.2.5.2. A Classifier by Hand#

Now put the pieces together as four small functions. To classify a new point with \(k\) neighbors:

  1. all_distances(training, point) computes the distance from the point to every row of the training table (leaving out the outcome column).

  2. closest(training, point, k) adds those distances as a column, sorts by distance, and keeps the first \(k\) rows.

  3. majority(nearest) returns the most common outcome among those \(k\) rows.

  4. classify(training, point, k) runs steps 1 to 3 and returns the prediction.

def all_distances(training, point):
    """Distance from point to every row of training, leaving out the outcome column."""
    attributes = training.drop(columns=['outcome'])
    return np.sqrt(((attributes - point) ** 2).sum(axis=1))

def closest(training, point, k):
    """The k rows of training nearest to point, with a Distance column."""
    with_distance = training.assign(Distance=all_distances(training, point))
    return with_distance.sort_values('Distance').head(k)

def majority(nearest):
    """The most common outcome among the rows in nearest."""
    return nearest['outcome'].value_counts().idxmax()

def classify(training, point, k):
    """Predict the outcome of point by a majority vote of its k nearest rows."""
    return majority(closest(training, point, k))

Suppose a new visitor’s session has a page value, exit rate, and product duration of 0.4, -0.7, and 0.3 in standard units. Here are the visitor’s 5 nearest neighbors among the training sessions.

visitor = np.array([0.4, -0.7, 0.3])
closest(training, visitor, 5).round(2)
page_value exit_rate product_duration outcome Distance
154 0.39 -0.80 0.08 purchase 0.24
109 0.46 -0.49 0.49 purchase 0.29
231 0.21 -0.64 0.02 no purchase 0.34
248 0.08 -0.60 0.14 no purchase 0.37
36 0.04 -0.53 0.38 no purchase 0.41
print('1-NN prediction:', classify(training, visitor, 1))
print('5-NN prediction:', classify(training, visitor, 5))
1-NN prediction: purchase
5-NN prediction: no purchase

The visitor’s single nearest neighbor ended in a purchase, so the 1-nearest neighbor classifier predicts “purchase”. But three of the next four neighbors, nearly as close, did not buy, so the 5-nearest neighbor classifier predicts “no purchase”. The choice of \(k\) can change the prediction; Sections Training, Testing, and Accuracy and Nearest Neighbors with scikit-learn show how to pick \(k\) with data the classifier has not seen.

### Exercise: Write ex_classify
# A subscription service labels past customers 'churn' or 'stay'. Both attributes are in
# standard units.
#   1. Write ex_classify(ex_training, point, k): compute the distance from point to every row
#      of ex_training (leave out 'Class'), take the k closest rows, and return the most
#      common Class among them.
#   2. Classify new_customer with k = 1 and with k = 3.
# Print exactly:
# k = 1: stay
# k = 3: churn
import numpy as np
import pandas as pd

ex_training = pd.DataFrame({
    'tenure': [-1.2, -0.8, 0.9, 1.4, -0.2, 0.0],
    'calls': [1.5, 0.9, -0.7, -1.1, 0.6, 0.35],
    'Class': ['churn', 'churn', 'stay', 'stay', 'churn', 'stay'],
})
new_customer = np.array([-0.1, 0.4])
### Your code starts here.




### Your code ends here.

Hide code cell source

### Solution
import numpy as np
import pandas as pd

ex_training = pd.DataFrame({
    'tenure': [-1.2, -0.8, 0.9, 1.4, -0.2, 0.0],
    'calls': [1.5, 0.9, -0.7, -1.1, 0.6, 0.35],
    'Class': ['churn', 'churn', 'stay', 'stay', 'churn', 'stay'],
})
new_customer = np.array([-0.1, 0.4])

def ex_classify(ex_training, point, k):
    ex_attributes = ex_training.drop(columns=['Class'])
    distances = np.sqrt(((ex_attributes - point) ** 2).sum(axis=1))
    ex_nearest = ex_training.assign(Distance=distances).sort_values('Distance').head(k)
    return ex_nearest['Class'].value_counts().idxmax()

print('k = 1:', ex_classify(ex_training, new_customer, 1))
print('k = 3:', ex_classify(ex_training, new_customer, 3))
k = 1: stay
k = 3: churn

14.2.6. Section Practice#

Use the ideas of this section to work through one more case from start to finish.

### Exercise: Practice Nearest Neighbors
# A subscription service wants to predict whether a new customer will renew.
# Each past customer has two attributes in standard units and a known label.
#   1. Compute the distance from new_customer to each past customer.
#   2. Predict with the single nearest neighbor (1-NN).
#   3. Predict by majority vote of the 3 nearest neighbors (3-NN).
# Print exactly:
# Nearest neighbor: C
# 1-NN prediction: churn
# 3-NN prediction: renew
import numpy as np
import pandas as pd

customers = pd.DataFrame({
    'name': ['A', 'B', 'C', 'D', 'E'],
    'visits': [1.2, 0.8, -0.1, -1.0, 0.3],
    'spend': [0.9, 1.1, 0.4, -1.2, 0.1],
    'label': ['renew', 'renew', 'churn', 'churn', 'renew'],
})
new_customer = np.array([0.2, 0.5])
### Your code starts here.




### Your code ends here.

Hide code cell source

### Solution
import numpy as np
import pandas as pd

customers = pd.DataFrame({
    'name': ['A', 'B', 'C', 'D', 'E'],
    'visits': [1.2, 0.8, -0.1, -1.0, 0.3],
    'spend': [0.9, 1.1, 0.4, -1.2, 0.1],
    'label': ['renew', 'renew', 'churn', 'churn', 'renew'],
})
new_customer = np.array([0.2, 0.5])

ex_attributes = customers[['visits', 'spend']]
customers['distance'] = np.sqrt(((ex_attributes - new_customer) ** 2).sum(axis=1))
ex_nearest = customers.sort_values('distance')

print('Nearest neighbor:', ex_nearest['name'].iloc[0])
print('1-NN prediction:', ex_nearest['label'].iloc[0])
print('3-NN prediction:', ex_nearest['label'].head(3).value_counts().idxmax())
Nearest neighbor: C
1-NN prediction: churn
3-NN prediction: renew