14.1. Classification#

Hide code cell source

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

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline

Ideas from Chapter 13 Used in This Chapter

This chapter builds on a few ideas from Chapter 13. If you have not read it, here is what you need.

  • Predicting from several features. Chapter 12 predicted a number from one feature, such as a store’s sales from its ad spending. Chapter 13 used several features at once: a home’s sale price from its living area, overall quality, year built, and garage size. A classifier also uses several features, but it predicts a category instead of a number.

  • Training and test data. A model is built from one part of the data (the training data) and checked on another part it has never seen (the test data). How well a model fits its own training data is too optimistic; how well it does on the test data estimates how it will do on new cases. Section Training, Testing, and Accuracy works through this for classifiers.

  • Overfitting. Giving a model more features or more flexibility always makes it fit the training data better. Past some point it starts fitting noise, and it does worse on new data. In this chapter, a nearest neighbor classifier that looks at only one neighbor overfits in the same way.

  • scikit-learn. A few code cells in Section Training, Testing, and Accuracy use scikit-learn, a Python library for building models, to check the NumPy code. Its train_test_split() function splits a table into a training part and a test part at random.

For the full treatment, see Regression with scikit-learn and Choosing Features and Avoiding Overfitting.

Every day a business makes decisions about one customer at a time. Should you call this lead? Will this subscriber cancel? Is this payment fraudulent? Each decision is a guess about a category, and a good guess saves money. This chapter shows how to build a method that makes such guesses from past data and how to tell whether the method is any good.

This section sets up the vocabulary and the running case, a year of visits to an online store. You will look at what buyers and non-buyers do differently, write a one-line rule that predicts who will buy, and see why a rule written by hand is not enough. The next section, Nearest Neighbors, builds a classifier that learns from the data instead.

14.1.1. Predicting a Category#

In Chapters 12 and 13 you predicted a number: a store’s sales from its ad spending, a sales rep’s next-quarter sales, a home’s sale price. That is regression. Regression and classification are both supervised learning: the data include the right answer for past cases, and the model learns from them. Classification predicts a category instead: whether a customer will cancel, whether an applicant will repay a loan, whether a payment is fraud.

Many management decisions are classification questions:

  • Will this subscriber cancel next quarter? Predicting customer churn lets a retention team contact likely leavers first.

  • Will this applicant repay the loan? Lenders predict default from income, debt, and payment history.

  • Is this card transaction fraudulent? Banks score each transaction and hold the suspicious ones for review.

  • Will this visitor to the website buy something? An online store can show a discount only to visitors who seem unlikely to buy.

The same words describe all of these problems.

  • An observation is one case: one session, one customer, one transaction.

  • The label is the category to predict, such as purchase or no purchase.

  • A class is one of the possible values of the label. Here there are two classes.

  • An attribute, also called a feature, is a measured fact about the observation that might help predict the label, such as how long the visitor stayed.

  • A classifier is a rule, or a method for building a rule, that takes an observation’s attributes and returns a predicted label.

When the label has two classes, as with churn or fraud, the problem is binary classification. When it has more than two, such as sorting support tickets into billing, shipping, and technical, it is multiclass classification. In multi-label classification, one observation can have several labels at once, such as a support ticket tagged both billing and urgent; it is usually handled as a separate yes-or-no classifier for each label. This chapter uses binary examples. The ideas carry over to more classes with little change.

Fig. 14.1 shows how these pieces fit together in three steps.

  1. First, a learning method, such as the nearest neighbor method in Section Nearest Neighbors, builds a classifier from labeled sessions: their features and the label for each.

  2. Second, the classifier predicts the label of a new session from its features alone.

  3. Third, to see whether the predictions can be trusted, the classifier labels sessions that were held out from training, and its predictions are compared with their true labels. The classifier never sees those labels; they are used only for the check. Section Training, Testing, and Accuracy covers this step.

Three rows. Train: labeled sessions with features page_value and exit_rate and the label outcome go into a learning method, such as nearest neighbors, which builds a classifier. Predict: a new session's features go into the same classifier, which returns a predicted label. Test: held-out sessions' features go into the classifier, and its predictions are compared with the true labels, which the classifier never saw, to give the test accuracy.

Fig. 14.1 Supervised learning in three steps: train a classifier on labeled data, use it to predict, and test it on held-out data. The numbers are illustrative.#

Clustering, which Chapter 16 covers, is different from both regression and classification: it works without labels. It groups observations without labels, so there is no correct answer to learn from.

Fig. 14.2 puts the two kinds of learning side by side. Classification follows the left column: a classifier learns from known labels and is checked on held-out sessions. Clustering follows the right: with no labels, the method produces groups, and the analyst decides what they mean.

Two columns. Supervised learning, Chapters 12 to 15: labeled data, then a learning method such as nearest neighbors or regression, then a model, which predicts new cases and is checked on held-out data. Unsupervised learning, Chapter 16: unlabeled data, then a clustering method such as k-means, then numbered groups, then the analyst interprets and names the groups, with no test accuracy.

Fig. 14.2 Supervised and unsupervised learning workflows.#

### Exercise: Classification or Regression?
# Each business question is paired with three past values of what it predicts.
# Decide by what the values mean, not by their type: a number can be a category code.
#   1. Make a list ex_kinds with 'classification' or 'regression' for each question,
#      in the order the questions appear.
#   2. Print each question followed by its kind.
# Print exactly:
# Will this subscriber cancel? classification
# What will this home sell for? regression
# Which department will handle this support ticket? classification
# Is this payment fraud? classification
# How many units will the store sell? regression
ex_targets = {
    'Will this subscriber cancel?': ['stays', 'cancels', 'stays'],
    'What will this home sell for?': [215000, 189500, 342000],
    'Which department will handle this support ticket?': [40, 12, 55],   # 12 billing, 40 technical, 55 shipping
    'Is this payment fraud?': ['fraud', 'not fraud', 'not fraud'],
    'How many units will the store sell?': [130, 98, 154],
}
### Your code starts here.




### Your code ends here.

Hide code cell source

### Solution
ex_targets = {
    'Will this subscriber cancel?': ['stays', 'cancels', 'stays'],
    'What will this home sell for?': [215000, 189500, 342000],
    'Which department will handle this support ticket?': [40, 12, 55],   # 12 billing, 40 technical, 55 shipping
    'Is this payment fraud?': ['fraud', 'not fraud', 'not fraud'],
    'How many units will the store sell?': [130, 98, 154],
}

ex_kinds = ['classification', 'regression', 'classification', 'classification', 'regression']
for ex_question, ex_kind in zip(ex_targets, ex_kinds):
    print(ex_question, ex_kind)
# Department codes are numbers, but they name categories: department 40 is not
# "more" than department 12, and an average code of 35.7 means nothing.
Will this subscriber cancel? classification
What will this home sell for? regression
Which department will handle this support ticket? classification
Is this payment fraud? classification
How many units will the store sell? regression

14.1.2. A First Look at Shopping Sessions#

The running case is real. The Online Shoppers Purchasing Intention data come from the UCI Machine Learning Repository (Sakar and others, Neural Computing and Applications, 2019, licensed CC BY 4.0). They describe 12,330 sessions on an online retailer’s website over one year, and each session belongs to a different user. This book keeps ten of the original columns and gives them shorter names. It also rounds product_duration to one decimal and recodes the original True/False Revenue column as the label outcome (purchase or no purchase); the other values are unchanged. The label is outcome: did the session end in a purchase?

shoppers = pd.read_csv(path_data + 'online_shoppers.csv')
print(len(shoppers), 'sessions')
shoppers.head()
12330 sessions
product_pages product_duration bounce_rate exit_rate page_value special_day month visitor_type weekend outcome
0 1 0.0 0.20 0.20 0.0 0.0 Feb Returning_Visitor False no purchase
1 2 64.0 0.00 0.10 0.0 0.0 Feb Returning_Visitor False no purchase
2 1 0.0 0.20 0.20 0.0 0.0 Feb Returning_Visitor False no purchase
3 2 2.7 0.05 0.14 0.0 0.0 Feb Returning_Visitor False no purchase
4 10 627.5 0.02 0.05 0.0 0.0 Feb Returning_Visitor True no purchase

Each row is one observation. The attributes include:

  • product_pages (product pages viewed),

  • product_duration (seconds on those pages),

  • bounce_rate (how often visitors who arrived on the pages left without viewing another),

  • exit_rate (how often a view of the pages was the last in the session), and

  • page_value, which the retailer’s analytics tool computes as the average dollar value of the pages the visitor saw, based on the sales that followed visits to them.

The other columns indicate the month, whether the visit was on a weekend, whether the visitor was new or returning (visitor_type), and how close the date was to a holiday such as Mother’s Day (special_day), with values from 0 to 1.

The outcome label has two classes: purchase and no purchase. How many sessions fall into each, and what share ended in a purchase?

counts = shoppers['outcome'].value_counts()
print(counts)
print('Share ending in a purchase:', round((shoppers['outcome'] == 'purchase').mean(), 3))
outcome
no purchase    10422
purchase        1908
Name: count, dtype: int64
Share ending in a purchase: 0.155

About one session in six ends in a purchase. The classes are imbalanced: one class is much more common than the other, which matters when you judge a classifier’s accuracy. To see which attributes might help predict the label, compare the average of three attributes for buyers and non-buyers.

group_means = shoppers.groupby('outcome')[['page_value', 'exit_rate', 'product_pages']].mean()
group_means.round(3)
page_value exit_rate product_pages
outcome
no purchase 1.976 0.047 28.715
purchase 27.265 0.020 48.210

Buyers’ sessions have a far higher average page value, a lower exit rate, and more product pages viewed. A histogram shows whether the difference is more than a few extreme sessions. The two groups are drawn side by side on the same scale.

fig, axes = plt.subplots(1, 2, figsize=(9, 3.5))
for label, color in [('no purchase', 'tab:blue'), ('purchase', 'tab:orange')]:
    group = shoppers[shoppers['outcome'] == label]
    axes[0].hist(group['exit_rate'], bins=np.arange(0, 0.21, 0.01), alpha=0.6,
                 color=color, label=label, density=True)
    axes[1].hist(group['page_value'], bins=np.arange(0, 101, 5), alpha=0.6,
                 color=color, label=label, density=True)
axes[0].set_xlabel('Exit rate')
axes[0].set_ylabel('Density')
axes[0].set_title('Buyers\' sessions have lower exit rates')
axes[1].set_xlabel('Page value (dollars, sessions up to 100)')
axes[1].set_title('Most non-buyers have page value 0')
axes[0].legend()
plt.tight_layout()
plt.show()
../../_images/71257b18b3253a1d2deab89600b15a8f178e5c3e939304c61ba0306ceada6b35.png
print('Sessions with page value of 0, no purchase:',
      round((shoppers.loc[shoppers['outcome'] == 'no purchase', 'page_value'] == 0).mean(), 3))
print('Sessions with page value of 0, purchase:',
      round((shoppers.loc[shoppers['outcome'] == 'purchase', 'page_value'] == 0).mean(), 3))
Sessions with page value of 0, no purchase: 0.886
Sessions with page value of 0, purchase: 0.194

Page value comes close: 88.6% of non-buyers’ sessions have a page value of 0, but so do 19.4% of buyers’. Neither attribute separates the groups perfectly, but the pattern is clear. The next task is to turn it into a prediction.

### Exercise: Compare Buyers and Non-buyers
#   1. Group shoppers_ex by 'outcome' and take the mean of 'product_duration'.
#   2. Round each mean to 1 decimal and print it with its outcome label.
#   (The values are seconds on product pages.)
# Print exactly:
# no purchase: 1070.0
# purchase: 1876.2
import pandas as pd
shoppers_ex = pd.read_csv('../../data/online_shoppers.csv')
### Your code starts here.




### Your code ends here.

Hide code cell source

### Solution
import pandas as pd
shoppers_ex = pd.read_csv('../../data/online_shoppers.csv')
means_ex = shoppers_ex.groupby('outcome')['product_duration'].mean()
for ex_label, value in means_ex.items():
    print(ex_label + ':', round(value, 1))
no purchase: 1070.0
purchase: 1876.2

14.1.3. A Rule-Based Classifier#

The simplest classifier is a rule a person writes down. The histograms suggest one: most non-buyers saw pages with a page value of 0, and most buyers did not. So predict purchase when page_value is above 0, and no purchase otherwise. Accuracy is the fraction of observations whose predicted label equals the actual label.

predicted = np.where(shoppers['page_value'] > 0, 'purchase', 'no purchase')
correct = predicted == shoppers['outcome']
print('Sessions predicted correctly:', correct.sum(), 'of', len(shoppers))
print('Accuracy of the rule:', round(correct.mean(), 3))
Sessions predicted correctly: 10768 of 12330
Accuracy of the rule: 0.873

The rule is right about 87% of the time. Is that good? Compare it with a baseline classifier, one that uses no attributes at all and always predicts the more common class, no purchase. Its accuracy is called the baseline accuracy.

baseline = (shoppers['outcome'] == 'no purchase').mean()
print('Baseline accuracy (always predict no purchase):', round(baseline, 3))
print('Improvement from the rule:', round(correct.mean() - baseline, 3))
Baseline accuracy (always predict no purchase): 0.845
Improvement from the rule: 0.028

The rule beats the baseline, but only by about three percentage points, because most sessions are non-purchases and the baseline gets all of those right. A look at where the rule goes wrong helps.

print(pd.crosstab(predicted, shoppers['outcome'],
                  rownames=['predicted'], colnames=['actual']))
actual       no purchase  purchase
predicted                         
no purchase         9230       370
purchase            1192      1538

The rule misses 370 of the 1,908 buyers (those with page value 0 who bought) and flags 1,192 non-buyers (those with page value above 0 who left). A different cutoff, or a rule that uses exit rate and page value together, might do better. But you would have to guess at the cutoffs, and with five or ten attributes the number of possible rules explodes.

What is needed is a method that learns from labeled examples. Given the many past sessions whose outcomes are known, it should classify a new session by looking at the past sessions most like it. That is the idea of nearest neighbors, developed in Nearest Neighbors. Once you have such a classifier, you must test it on sessions it has not seen; Training, Testing, and Accuracy shows how.

One caution applies to everything in this chapter: what will be known at the moment the prediction is made? The store in the list at the start of this section wants to show a discount during the visit, before the visitor decides. But each row of this file describes a whole session, after it ended. Product pages and exit rate keep changing as the visit goes on, so in the middle of a visit the store knows only part of them. Page value needs more care: the analytics tool computes it from the sales that followed visits to those pages, and those sales can include the purchase in this very session. A rule built on page value may partly be “predicting” a purchase from the purchase itself. An attribute that becomes known only after the outcome is a form of data leakage (see Training, Testing, and Accuracy), and a classifier that depends on it will do worse in use than in testing. A fair test for the discount decision would use only what the store records up to that moment, such as the first few pages of each visit.

The next two sections keep page value as a feature because it makes the methods easy to see in two dimensions. Read their accuracies as the best case: for a discount shown during the visit, a classifier would have less to go on.

### Exercise: A Rule on Exit Rate
#   1. Predict 'purchase' when exit_rate is below 0.03, else 'no purchase', for every row.
#   2. Compute the accuracy: the fraction of predictions equal to the 'outcome' column.
#   3. Print the accuracy rounded to 3 decimals.
# Print exactly:
# Accuracy: 0.533
import numpy as np
import pandas as pd
shoppers_ex = pd.read_csv('../../data/online_shoppers.csv')
### Your code starts here.




### Your code ends here.

Hide code cell source

### Solution
import numpy as np
import pandas as pd
shoppers_ex = pd.read_csv('../../data/online_shoppers.csv')
pred_ex = np.where(shoppers_ex['exit_rate'] < 0.03, 'purchase', 'no purchase')
acc_ex = (pred_ex == shoppers_ex['outcome']).mean()
print('Accuracy:', round(acc_ex, 3))
# 0.533 is far below the 0.845 baseline of always predicting 'no purchase':
# many non-buyers also have low exit rates, so this rule flags too many sessions.
# A rule can be worse than ignoring the data; always compare with the baseline.
Accuracy: 0.533

14.1.4. Section Practice#

The exercise below practices the central idea of this section: a classifier is a rule that turns an observation’s attributes into a predicted label, and its accuracy is the share of predictions that match the actual labels.

### Exercise: Practice Classification
# An online store wants to flag fraudulent orders. A simple classifier uses this rule:
# predict 'fraud' when the order value is over 500 AND the order ships to a new address;
# otherwise predict 'ok'.
#   1. Apply the rule to each order and store the predictions in a list.
#   2. Count how many predictions match the actual labels.
# Print exactly:
# Predictions: ['ok', 'fraud', 'ok', 'fraud', 'ok']
# Correct: 4 of 5
order_values = [120, 750, 640, 980, 60]
new_address = [False, True, False, True, True]
actual = ['ok', 'fraud', 'fraud', 'fraud', 'ok']
### Your code starts here.




### Your code ends here.

Hide code cell source

### Solution
order_values = [120, 750, 640, 980, 60]
new_address = [False, True, False, True, True]
actual = ['ok', 'fraud', 'fraud', 'fraud', 'ok']

predictions = []
for value, is_new in zip(order_values, new_address):
    if value > 500 and is_new:
        predictions.append('fraud')
    else:
        predictions.append('ok')

ex_correct = sum(p == a for p, a in zip(predictions, actual))
print('Predictions:', predictions)
print('Correct:', ex_correct, 'of', len(actual))
Predictions: ['ok', 'fraud', 'ok', 'fraud', 'ok']
Correct: 4 of 5