14.3. Training, Testing, and Accuracy#

Hide code cell source

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

import numpy as np
import pandas as pd

import matplotlib.pyplot as plt
%matplotlib inline

from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split

A classifier is only useful if it works on new cases: next month’s sessions, next quarter’s customers, tomorrow’s transactions. A classifier that looks accurate on the cases it was built from may still fail on cases it has never seen. This section shows why a classifier must be tested on data it was not built from, how to set aside a test set, how to scale the features without leaking information from the test set, how to read accuracy honestly when one class is rare, and how to choose \(k\) without touching the test set.

This section continues with the online shopping sessions from Sections Classification and Nearest Neighbors. The data come from the UCI Machine Learning Repository: 12,330 real sessions on an online retailer’s site over one year (Sakar and others, Neural Computing and Applications, 2019), licensed CC BY 4.0. Each session is labeled purchase or no purchase. The code keeps only the columns it needs and predicts the label from two features: page_value (how valuable the pages a visitor saw tend to be) and exit_rate (how often those pages were the last in a session).

sessions = pd.read_csv(path_data + 'online_shoppers.csv')
features = ['page_value', 'exit_rate']

print('Sessions:', len(sessions))
print(sessions['outcome'].value_counts())
sessions[features + ['outcome']].head()
Sessions: 12330
outcome
no purchase    10422
purchase        1908
Name: count, dtype: int64
page_value exit_rate outcome
0 0.0 0.20 no purchase
1 0.0 0.10 no purchase
2 0.0 0.20 no purchase
3 0.0 0.14 no purchase
4 0.0 0.05 no purchase

Here is the classifier to test, written with NumPy. It is the same idea as in Nearest Neighbors, \(k\) nearest neighbors by majority vote, but it classifies many sessions at once. For each new session it finds the distance to every training session, takes the k nearest, and predicts “purchase” when more than half of them are purchases. To keep memory small it handles the new sessions in batches of 500. The inputs are arrays: train_X and new_X hold the features, and train_y holds True for a purchase and False for no purchase.

Treat knn_predict as a tool: you will not be asked to write code like it, and the lab and homework use the step-by-step version from Nearest Neighbors. What you should be able to do is say what it does for one session, which the small example after the function traces by hand.

def knn_predict(train_X, train_y, new_X, k):
    """Predict True (purchase) or False for each row of new_X by majority vote of k nearest training rows."""
    predictions = []
    for start in range(0, len(new_X), 500):
        batch = new_X[start:start + 500]
        # distance from every session in the batch to every training session
        dist = np.sqrt(((batch[:, None, :] - train_X[None, :, :]) ** 2).sum(axis=2))
        nearest = np.argpartition(dist, k - 1, axis=1)[:, :k]   # indices of the k closest
        purchase_votes = train_y[nearest].sum(axis=1)
        predictions.append(purchase_votes * 2 > k)              # purchase if more than half
    return np.concatenate(predictions)

def accuracy(predicted, actual):
    """The proportion of predictions that match the actual labels."""
    return np.mean(predicted == actual)

Here is one new session and five training sessions, already in standard units. The table lists each training session’s distance to the new session. With \(k = 3\), the three closest are rows 2, 0, and 4, and two of the three are purchases, so the vote predicts “purchase”. knn_predict gives the same answer.

tiny_X = np.array([[0.2, 0.1], [1.5, -0.4], [0.6, -0.2], [-0.8, 0.9], [0.1, -0.3]])
tiny_y = np.array([True, True, False, False, True])        # True means purchase
new_session = np.array([[0.4, -0.1]])

trace = pd.DataFrame(tiny_X, columns=features)
trace['purchase'] = tiny_y
trace['distance'] = np.sqrt(((tiny_X - new_session) ** 2).sum(axis=1)).round(3)
print(trace.sort_values('distance').to_string())
print()
print('3-NN prediction (True = purchase):', knn_predict(tiny_X, tiny_y, new_session, 3)[0])
   page_value  exit_rate  purchase  distance
2         0.6       -0.2     False     0.224
0         0.2        0.1      True     0.283
4         0.1       -0.3      True     0.361
1         1.5       -0.4      True     1.140
3        -0.8        0.9     False     1.562

3-NN prediction (True = purchase): True

14.3.1. Overly Optimistic Testing#

The training set is the labeled data a classifier learns from. For a nearest-neighbor classifier, “learning” is just storing these sessions. The obvious way to check how well it works is to classify the sessions already in hand and count how often it is right. That proportion is the training accuracy.

Standardize the features first (see Nearest Neighbors: without this, one attribute can swamp the other), then classify every session with 1 nearest neighbor and compare with the actual labels. The first run uses all 12,330 sessions as the training set.

all_X = ((sessions[features] - sessions[features].mean()) / sessions[features].std(ddof=0)).values
all_y = (sessions['outcome'] == 'purchase').values

predicted_all = knn_predict(all_X, all_y, all_X, 1)
print('1-NN accuracy on its own training sessions:', round(accuracy(predicted_all, all_y), 3))
1-NN accuracy on its own training sessions: 0.98

Almost every session (98.3%) is classified correctly. This looks impressive, but it says very little. When you ask the classifier about a session that is already in the training set, that session is its own nearest neighbor, at distance 0. The classifier “predicts” the label it was just given. The accuracy is not exactly 1 only because some different sessions share identical feature values but have different outcomes, so one of them wins the tie.

The problem is general. A flexible classifier such as 1-NN can reproduce the labels of the data it has seen, including their chance quirks, without learning anything that carries over. Fitting the training data too closely is called overfitting (Section Choosing Features and Avoiding Overfitting showed the same trap in regression). What a business needs to know is how the classifier will do on new sessions, and training accuracy cannot answer that question. The classifier must be tested on sessions it has not seen.

### Exercise: Training Accuracy of a Tiny 1-NN Classifier
# Six past sessions (features in standard units) and four new ones are below.
# A 1-NN classifier is built from the six past sessions.
#   1. For every past session, find its nearest neighbor among the six past sessions
#      (including itself) and predict that session's label. Compute the accuracy.
#   2. For every new session, find its nearest neighbor among the six past sessions
#      and compute the accuracy against new_label.
#   3. Print both accuracies.
# Print exactly:
# Training accuracy: 1.0
# New-session accuracy: 0.25
import numpy as np

past_X = np.array([[1.5, -0.5], [1.0, -1.0], [-0.5, 0.5], [-1.0, 0.0], [0.2, 0.9], [0.0, -0.3]])
past_label = np.array(['purchase', 'purchase', 'no purchase', 'no purchase', 'purchase', 'no purchase'])
new_X = np.array([[0.1, 0.8], [1.2, -0.2], [-0.2, 0.4], [0.9, -0.9]])
new_label = np.array(['no purchase', 'purchase', 'purchase', 'no purchase'])

### Your code starts here.




### Your code ends here.

Hide code cell source

### Solution
import numpy as np

past_X = np.array([[1.5, -0.5], [1.0, -1.0], [-0.5, 0.5], [-1.0, 0.0], [0.2, 0.9], [0.0, -0.3]])
past_label = np.array(['purchase', 'purchase', 'no purchase', 'no purchase', 'purchase', 'no purchase'])
new_X = np.array([[0.1, 0.8], [1.2, -0.2], [-0.2, 0.4], [0.9, -0.9]])
new_label = np.array(['no purchase', 'purchase', 'purchase', 'no purchase'])

def nearest_label(point):
    distances = np.sqrt(((past_X - point) ** 2).sum(axis=1))
    return past_label[np.argmin(distances)]

train_pred = np.array([nearest_label(p) for p in past_X])
new_pred = np.array([nearest_label(p) for p in new_X])

print('Training accuracy:', np.mean(train_pred == past_label))
print('New-session accuracy:', np.mean(new_pred == new_label))
Training accuracy: 1.0
New-session accuracy: 0.25

14.3.2. Splitting Into Training and Test Sets#

The remedy is to hold some labeled sessions back. Split the data into two parts:

  • the training set, used to build the classifier (for 1-NN, the sessions searched for neighbors), and

  • the test set, kept out of sight, used only to check the classifier afterward.

The sessions in the training set are also called the training data, and those in the test set the test data.

Because the test sessions have known labels, you can compare the classifier’s predictions with the truth, but the classifier never used those labels. The accuracy on the test set is called the test accuracy, and it is an honest estimate of how the classifier performs on new sessions (as long as the new sessions resemble the old ones).

The split should be random. The rows of a data file are often in some order, such as by month, and a test set made of the last rows would be a different kind of session from the training set. The code shuffles the row numbers with a seeded generator, so the split is the same every time, and puts 70% of the rows in the training set and 30% in the test set.

rng = np.random.default_rng(39)
shuffled = rng.permutation(len(sessions))        # the row numbers in random order
n_train = int(0.7 * len(sessions))

training = sessions.iloc[shuffled[:n_train]]
test = sessions.iloc[shuffled[n_train:]]
print('Training sessions:', len(training))
print('Test sessions:    ', len(test))
Training sessions: 8631
Test sessions:     3699

Next, scale the features. Page value and exit rate are on different scales, so convert each to standard units (Section Correlation). The key rule is that the mean and SD come from the training set only. Then use those same two numbers to convert the test set.

train_mean = training[features].mean()
train_sd = training[features].std(ddof=0)

train_X = ((training[features] - train_mean) / train_sd).values
test_X = ((test[features] - train_mean) / train_sd).values     # training mean and SD, not the test set's own
train_y = (training['outcome'] == 'purchase').values
test_y = (test['outcome'] == 'purchase').values

print('Training mean of page_value, exit_rate:', train_mean.round(3).values)
print('Training SD of page_value, exit_rate:  ', train_sd.round(3).values)
print('Test set in standard units, column means:', test_X.mean(axis=0).round(3))
Training mean of page_value, exit_rate: [5.88  0.043]
Training SD of page_value, exit_rate:   [18.461  0.049]
Test set in standard units, column means: [ 0.002 -0.004]

Why not use all the data to compute the mean and SD? Because the test set is supposed to stand in for sessions that do not exist yet. When a classifier is used for real, next month’s sessions arrive one at a time, and a mean cannot be computed over sessions not yet seen. Letting the test set influence the scaling lets information about the test sessions leak into the classifier, a mistake called data leakage. The effect on the test accuracy is usually small, but it makes the test less honest, and the habit matters more with complex methods. The rule is the same for any step that learns something from data: learn it from the training set, then apply it unchanged to the test set. Leakage can also come from the features themselves: an attribute that is known only after the outcome, as Classification discusses for page value, leaks the answer however carefully the scaling is done.

The test sessions in standard units have column means that are close to, but not exactly, 0, which is as expected: they were scaled with the training set’s mean and SD, not their own.

### Exercise: Split and Scale
# Ten past orders have a basket size (items). Split them and scale with the training set only.
#   1. Shuffle the row numbers 0..9 with np.random.default_rng(5) (use the permutation method).
#   2. The first 7 shuffled rows are the training set and the last 3 are the test set.
#   3. Compute the training mean and SD (np.std) of basket, and convert the test baskets
#      to standard units with those two numbers. Round to 2 decimals.
#   4. Print the number of training and test rows and the scaled test baskets.
# Print exactly:
# Training rows: 7
# Test rows: 3
# Scaled test baskets: [-0.21, 0.52, 0.88]
import numpy as np

ex_basket = np.array([3, 5, 2, 8, 4, 6, 1, 9, 7, 4])

### Your code starts here.




### Your code ends here.

Hide code cell source

### Solution
import numpy as np

ex_basket = np.array([3, 5, 2, 8, 4, 6, 1, 9, 7, 4])

ex_rng = np.random.default_rng(5)
ex_order = ex_rng.permutation(len(ex_basket))
ex_train = ex_basket[ex_order[:7]]
ex_test = ex_basket[ex_order[7:]]

ex_scaled = (ex_test - ex_train.mean()) / ex_train.std()
print('Training rows:', len(ex_train))
print('Test rows:', len(ex_test))
print('Scaled test baskets:', [float(v) for v in ex_scaled.round(2)])
Training rows: 7
Test rows: 3
Scaled test baskets: [-0.21, 0.52, 0.88]

14.3.3. Accuracy and the Baseline#

Now you can test honestly. Classify every test session using only the training set, then report the proportion classified correctly. The tests below use 1 neighbor and 15 neighbors.

for k in [1, 15]:
    predicted = knn_predict(train_X, train_y, test_X, k)
    print(f'k = {k:2d}: test accuracy =', round(accuracy(predicted, test_y), 3),
          '  training accuracy =', round(accuracy(knn_predict(train_X, train_y, train_X, k), train_y), 3))
k =  1: test accuracy = 0.856   training accuracy = 0.977
k = 15: test accuracy = 0.889   training accuracy = 0.9

For 1 neighbor the training accuracy is about 0.96 but the test accuracy is only about 0.84, a large gap: the optimism seen at the start of this section. How well a classifier does on new data is its generalization, and the test accuracy measures it. For 15 neighbors the two numbers are close (about 0.90 and 0.89), because averaging over 15 sessions keeps the classifier from memorizing individual ones.

An accuracy near 0.89 sounds good, and its complement, the error rate, is the share of sessions classified wrongly (about 0.11). Whether it is good depends on what a classifier with no skill would score. Only about 15% of the sessions end in a purchase, so a “classifier” that ignores the features and always predicts the majority class, “no purchase”, is right for every non-buyer. Its accuracy is the baseline accuracy from Classification.

baseline = np.mean(~test_y)       # proportion of test sessions that are not purchases
print('Baseline (always "no purchase"):', round(baseline, 3))
print('1-NN test accuracy: ', round(accuracy(knn_predict(train_X, train_y, test_X, 1), test_y), 3))
print('15-NN test accuracy:', round(accuracy(knn_predict(train_X, train_y, test_X, 15), test_y), 3))
Baseline (always "no purchase"): 0.845
1-NN test accuracy:  0.856
15-NN test accuracy: 0.889

The baseline is 0.845. The 1-NN classifier, at 0.843, is slightly below the classifier that never looks at a session; on this split it adds nothing over no model at all. The 15-NN classifier, at 0.889, beats the baseline by about 4.4 percentage points. That is a real but modest gain, and it is the gain over the baseline, not the distance from 0, that measures what the features add.

You can check the NumPy function against scikit-learn’s KNeighborsClassifier, which Section Nearest Neighbors with scikit-learn introduces. The code also repeats the whole split with five other seeds. Test accuracy depends on which sessions land in the test set, so it moves around a little from split to split.

check = KNeighborsClassifier(n_neighbors=15).fit(train_X, train_y)
print('scikit-learn 15-NN test accuracy:', round(check.score(test_X, test_y), 3))

print('seed  baseline  1-NN   15-NN')
for seed in [1, 2, 3, 4, 5]:
    a_train, a_test = train_test_split(sessions, test_size=0.3, random_state=seed)
    mean, sd = a_train[features].mean(), a_train[features].std(ddof=0)
    aX, bX = ((a_train[features] - mean) / sd), ((a_test[features] - mean) / sd)
    ay, by = a_train['outcome'] == 'purchase', a_test['outcome'] == 'purchase'
    scores = [KNeighborsClassifier(n_neighbors=k).fit(aX, ay).score(bX, by) for k in [1, 15]]
    print(f'{seed:4d}  {np.mean(~by):.3f}     {scores[0]:.3f}  {scores[1]:.3f}')
scikit-learn 15-NN test accuracy: 0.889
seed  baseline  1-NN   15-NN
   1  0.851     0.855  0.889
   2  0.857     0.853  0.892
   3  0.849     0.840  0.893
   4  0.846     0.838  0.884
   5  0.849     0.845  0.888

The scikit-learn result matches the NumPy function. Across the five other splits the baseline is about 0.85 to 0.86, 1-NN is within two points of it (below it in the original split and with seed 5, a little above it with the other four seeds), and 15-NN is between 0.884 and 0.893, about 3.5 to 4.5 points above the baseline every time. The conclusion does not depend on one split: 1-NN is barely better than guessing “no purchase”, and a larger \(k\) is clearly better.

Accuracy can mislead when one class is rare. If 99 of 100 transactions are legitimate, a rule that approves everything is 99% accurate and catches no fraud. Here the shopper data are not that extreme, but the baseline already takes up 84.5 of the 89 points. Accuracy also treats all errors alike, yet missing a buyer and wrongly flagging a browser can cost the business very different amounts. Section Evaluating Classifiers shows how to count the two kinds of errors separately.

### Exercise: Beat the Baseline?
# A retailer tested two classifiers on 500 new sessions, of which 60 ended in a purchase.
# Classifier A was right on 435 sessions; classifier B was right on 452.
#   1. Compute the baseline accuracy of always predicting "no purchase".
#   2. Compute each classifier's accuracy.
#   3. Print the baseline and each accuracy, then whether each beats the baseline.
# Print exactly:
# Baseline: 0.88
# A: 0.87 beats baseline: False
# B: 0.904 beats baseline: True
ex_sessions = 500
ex_purchases = 60
ex_correct_a = 435
ex_correct_b = 452

### Your code starts here.




### Your code ends here.

Hide code cell source

### Solution
ex_sessions = 500
ex_purchases = 60
ex_correct_a = 435
ex_correct_b = 452

ex_baseline = (ex_sessions - ex_purchases) / ex_sessions
ex_acc_a = ex_correct_a / ex_sessions
ex_acc_b = ex_correct_b / ex_sessions

print('Baseline:', ex_baseline)
print('A:', ex_acc_a, 'beats baseline:', ex_acc_a > ex_baseline)
print('B:', ex_acc_b, 'beats baseline:', ex_acc_b > ex_baseline)
Baseline: 0.88
A: 0.87 beats baseline: False
B: 0.904 beats baseline: True

14.3.4. Choosing k#

The number of neighbors, \(k\), is a choice you make before looking at the test set. Small \(k\) follows the training data closely (a jagged boundary, Nearest Neighbors) and large \(k\) smooths it. How do you choose? You might try several values on the test set and keep the best one. That quietly turns the test set into part of the training process: the chosen \(k\) has been picked because it did well on those particular test sessions, so its test accuracy is slightly optimistic, the same kind of leak as before.

The cleaner approach is a third piece of data. A validation set is a part of the training set held back to compare choices such as \(k\). The plan has three steps:

  1. Split the training set into a smaller training part and a validation part, and put both in standard units with the mean and SD of the smaller training part. The validation part now plays the role of the test set, so it must not influence the scaling either.

  2. For each candidate \(k\), build the classifier on the smaller training part and measure accuracy on the validation part.

  3. Pick the \(k\) with the best validation accuracy, rebuild the classifier on the whole training set, and use the test set once to report its accuracy.

The training set is already in random order, so its first 1,727 sessions (20%) serve as the validation set. They are scaled with the mean and SD of the other 6,904 training sessions, not with train_X, which was scaled using all of the training set, validation sessions included.

n_valid = 1727
valid_part, small_part = training.iloc[:n_valid], training.iloc[n_valid:]

# Scale with the smaller training part only, as with the test set
small_mean = small_part[features].mean()
small_sd = small_part[features].std(ddof=0)
small_X = ((small_part[features] - small_mean) / small_sd).values
valid_X = ((valid_part[features] - small_mean) / small_sd).values
small_y = (small_part['outcome'] == 'purchase').values
valid_y = (valid_part['outcome'] == 'purchase').values

print('Validation baseline:', round(np.mean(~valid_y), 3))
valid_accuracy = {}
for k in [1, 5, 15, 51]:
    valid_accuracy[k] = accuracy(knn_predict(small_X, small_y, valid_X, k), valid_y)
    print(f'k = {k:2d}: validation accuracy =', round(valid_accuracy[k], 3))

best_k = max(valid_accuracy, key=valid_accuracy.get)
print('Best k on the validation set:', best_k)
Validation baseline: 0.836
k =  1: validation accuracy = 0.863
k =  5: validation accuracy = 0.878
k = 15: validation accuracy = 0.877
k = 51: validation accuracy = 0.881
Best k on the validation set: 51

Validation accuracy is 0.870 for \(k = 1\), then 0.878, 0.877, and 0.881 for \(k = 5\), 15, and 51, against a validation baseline of 0.836. The differences among \(k = 5\), 15, and 51 are well under a percentage point, smaller than the split-to-split movement seen above, so do not read much into which one wins; the clearer result is that 1 neighbor is the weakest choice. Following the rule, take \(k = 51\), rebuild on the whole training set, and use the test set once.

final_predicted = knn_predict(train_X, train_y, test_X, best_k)
print(f'Test accuracy with k = {best_k}:', round(accuracy(final_predicted, test_y), 3))
print('Test baseline:', round(baseline, 3))
Test accuracy with k = 51: 0.892
Test baseline: 0.845

The test accuracy for \(k = 51\) is 0.892, about 4.7 points above the test baseline of 0.845. This is the number to report, and you report it once; if the result disappoints, going back to adjust \(k\) and testing again would make the test set part of the selection.

A chart shows the pattern for many values of \(k\). The code uses scikit-learn to compute training and validation accuracy for odd \(k\) from 1 to 101 quickly.

ks = list(range(1, 102, 2))
train_acc, valid_acc = [], []
for k in ks:
    model = KNeighborsClassifier(n_neighbors=k).fit(small_X, small_y)
    train_acc.append(model.score(small_X, small_y))
    valid_acc.append(model.score(valid_X, valid_y))

fig, ax = plt.subplots(figsize=(7, 4))
ax.plot(ks, train_acc, label='Training accuracy', color='tab:blue')
ax.plot(ks, valid_acc, label='Validation accuracy', color='tab:orange')
ax.axhline(np.mean(~valid_y), color='gray', linestyle='--', label='Baseline (always "no purchase")')
ax.set_xlabel('Number of neighbors, k')
ax.set_ylabel('Accuracy')
ax.set_title('Training accuracy falls with k; validation accuracy levels off above the baseline')
ax.title.set_fontsize(10)
ax.legend()
plt.show()
../../_images/86fa7d6309ce8b531c5ef61288cf744a292d365b0da61e581088de738e154d32.png

Training accuracy is highest at \(k = 1\) and falls as \(k\) grows, while validation accuracy climbs and then flattens, well above the baseline. The gap between the two curves at small \(k\) is overfitting. The opposite problem appears if \(k\) grows far beyond this range. If \(k\) were the whole training set, every session would get the same majority vote, “no purchase”, and the classifier would be no better than the baseline. A classifier too simple to capture the pattern in the data is underfitting. A good \(k\) sits between the two. (The \(k = 1\) validation point here, about 0.85, is lower than the 0.870 printed above. Many sessions are identical in page value and exit rate, so for \(k = 1\) several training sessions can tie for nearest, and the two programs break the ties differently. With larger \(k\) the tie hardly matters, which is another sign that 1 neighbor is unstable.) Section Nearest Neighbors with scikit-learn repeats this workflow with scikit-learn, which handles the splitting and scaling for you.

### Exercise: Pick k by Validation
# A lender compared a loan classifier for four values of k on a validation set.
# The validation accuracies are in the dictionary below.
#   1. Find the k with the highest validation accuracy.
#   2. The classifier with that k was then tested once on the test set: 168 of 200 loans correct.
#      Compute the test accuracy.
#   3. Print both.
# Print exactly:
# Best k: 9
# Test accuracy: 0.84
ex_valid = {1: 0.780, 3: 0.815, 9: 0.842, 25: 0.836}
ex_test_correct = 168
ex_test_total = 200

### Your code starts here.




### Your code ends here.

Hide code cell source

### Solution
ex_valid = {1: 0.780, 3: 0.815, 9: 0.842, 25: 0.836}
ex_test_correct = 168
ex_test_total = 200

ex_best_k = max(ex_valid, key=ex_valid.get)
print('Best k:', ex_best_k)
print('Test accuracy:', ex_test_correct / ex_test_total)
Best k: 9
Test accuracy: 0.84

14.3.5. Section Practice#

The exercise below practices the central idea of this section: accuracy measured on the training set is optimistic, and accuracy measured on a separate test set is the honest estimate.

### Exercise: Practice Training, Testing, and Accuracy
# A 1-nearest neighbor classifier was checked twice: on its own training set
# and on a separate test set. Its predictions and the actual labels are below.
#   1. Compute the accuracy (proportion of correct predictions) on each set.
#   2. Print both.
# Print exactly:
# Training accuracy: 1.0
# Test accuracy: 0.75
train_predicted = ['yes', 'no', 'no', 'yes', 'no', 'yes']
train_actual = ['yes', 'no', 'no', 'yes', 'no', 'yes']
test_predicted = ['yes', 'no', 'yes', 'no', 'no', 'yes', 'no', 'yes']
test_actual = ['yes', 'no', 'no', 'no', 'yes', 'yes', 'no', 'yes']
### Your code starts here.


### Your code ends here.

Hide code cell source

### Solution
train_predicted = ['yes', 'no', 'no', 'yes', 'no', 'yes']
train_actual = ['yes', 'no', 'no', 'yes', 'no', 'yes']
test_predicted = ['yes', 'no', 'yes', 'no', 'no', 'yes', 'no', 'yes']
test_actual = ['yes', 'no', 'no', 'no', 'yes', 'yes', 'no', 'yes']

def pct_correct(predicted, actual):
    correct = sum(p == a for p, a in zip(predicted, actual))
    return correct / len(actual)

print('Training accuracy:', pct_correct(train_predicted, train_actual))
print('Test accuracy:', pct_correct(test_predicted, test_actual))
# The test accuracy is the honest estimate: a 1-NN classifier always gets its own
# training points right, because each point is its own nearest neighbor.
Training accuracy: 1.0
Test accuracy: 0.75