Turn a Customer Table into a Prediction Question

Machine learning lets a program work out a rule from past examples instead of having a person write the rule by hand. Before any model can be trained, a business question such as "which customers are likely to leave?" has to become a table: one row per past example, the facts known about it, and the answer that it turned out to have. Everything the model will ever know comes from that table, so the first job is to read it well.

Finding the rule instead of writing it

Most programs follow rules that a person wrote. A shop that gives free delivery on orders over 50 euros needs one line of code: if total > 50. The rule is known exactly, so writing it down is the whole job.

Now take a question with no such rule: will this customer cancel their subscription next month? Nobody can write that rule from memory. Customers who have just joined may leave more often, and so may customers who called support several times, but how much each fact counts and how they combine is not known. What a company does have is a record of the past: thousands of earlier customers, what was known about each of them, and whether they stayed or left.

Machine learning turns that around. A learning program reads the past examples together with their answers and works out a rule that connects the two. The result is called a model: a learned rule that can be given a new case and returns a predicted answer for it.

A rule written by a person
  • New customer
  • Rule a person wrote if total > 50
  • Answer
  • New customer to Rule a person wrote
  • Rule a person wrote to Answer
A rule learned from examples
  • Past customers facts and known answers
  • New customer facts only
  • Model the learned rule
  • Predicted answer
  • Past customers to Model: learning
  • New customer to Model
  • Model to Predicted answer

Learning is worth the effort when a few things hold together:

  • the rule is too hard to write by hand, because many facts interact;
  • there are many past examples, and the answer of each one is known;
  • new cases are like the old ones, so a pattern from the past still applies;
  • an occasional wrong prediction is acceptable, because a model is right often, not always.

When an exact rule exists, such as a tax rate or a delivery threshold, writing it is simpler and always correct. A model only guesses well where the past examples show a pattern.

True or false?

A machine learning model follows rules that a programmer typed into it.

False. The programmer writes the learning program. The rule that connects facts to answers is worked out from the past examples.

For a rule that is known exactly, such as free delivery over 50 euros, writing the rule by hand is the better choice.

True. A written rule is always right and needs no examples. Learning pays off when nobody can write the rule.

Learning from examples with known answers

The kind of learning described above, where every past example comes with its answer, is called supervised learning. The known answers act like a teacher's marks: while learning, the program can compare what its rule would say with what really happened, and adjust the rule until the two agree as often as possible.

The answers come for free from the past. A customer who joined two years ago has already either stayed or left, so that outcome can be written next to the facts about them. That is the reason supervised learning works on business records: the answers were recorded as things happened.

When the answer is one of a few fixed values, the task is called classification, and each possible answer is a class. "Will this customer leave, yes or no?" has two classes, which makes it a binary classification. Sorting support emails into "billing", "technical" or "other" has three classes. Predicting an amount, such as next month's bill, is a different task, because the answer can be any number rather than one of a short list.

Predicting which customers will leave is common enough to have its own name: churn prediction, where churn means customers leaving a service.

True or false?

In supervised learning, the program needs to know the correct answer for every past example it learns from.

True. That is what supervised means: each example comes with its known answer, and the learning compares its guesses against it.

Predicting the number of months a customer will stay is a classification task.

False. The answer is an amount that can take many values. Classification predicts one of a few fixed answers, such as yes or no.

Rows, features and the label

Here is a small invented table of past customers of a music streaming service. Each row is one example: one customer, with the facts known about them and what they did.

Past customers (invented example)
customer_idplanmonthsmonthly_feesupport_callsleft
C-101Basic29.993Yes
C-102Family3017.990No
C-103Basic149.991No
C-104Student85.990No
C-105Family4117.992No

The columns play three different roles.

  • The label is the column with the answer to predict: here left, with the values Yes and No. It is also called the target.
  • The features are the columns the model may use to make its prediction: plan, months, monthly_fee and support_calls.
  • The identifier, customer_id, is neither. It is different on every row, so it names a customer without describing them. A model that used it could only memorize which name went with which answer, and that tells it nothing about a new customer with a new name.
  • customer_id identifier: neither
  • Features plan, months, monthly_fee, support_calls
  • Model
  • Label left: Yes or No
  • Features to Model
  • Model to Label

One test decides whether a column may be a feature: would its value be known at the moment the prediction is made? A model that warns about customers who might leave is used while they are still customers, so only facts known about a current customer can be features.

Suppose the table also had a column cancel_reason, filled in when a customer cancels. It would line up with the label perfectly, and a model would gladly rely on it, but for a customer who has not left yet that column is always empty. A model trained with it would look excellent on past rows and be useless on new ones.

True or false?

A customer number should be used as a feature, because it is different for every customer.

False. Being different on every row is exactly the problem: it describes nothing a new customer shares with past ones, so there is no pattern to learn from it.

A column that is only filled in after a customer leaves cannot be a feature for predicting who will leave.

True. Features must be known when the prediction is made, and for a current customer that column is still empty.

In a table of past examples, each row is one example and the label is one of its columns.

True. A row holds the features of one example together with its known answer in the label column.

Loading the table with pandas

Tables like this are usually stored as a CSV file: plain text with one row per line, values separated by commas, and the column names on the first line.

customers.csv
customer_id,plan,months,monthly_fee,support_calls,left
C-101,Basic,2,9.99,3,Yes
C-102,Family,30,17.99,0,No
C-103,Basic,14,9.99,1,No
C-104,Student,8,5.99,0,No
C-105,Family,41,17.99,2,No

In Python, the pandas library reads such a file into a DataFrame: a table of named columns, where each column may hold a different type of value, much like a spreadsheet. Before training anything, three quick looks tell you whether the table was read the way you expect: its size, the type of each column, and its first rows.

import pandas as pd

# Read the CSV file into a DataFrame; the first line becomes the column names.
df = pd.read_csv("customers.csv")

# The size of the table: (number of rows, number of columns).
print(df.shape)

# The data type pandas chose for each column.
print(df.dtypes)

# The first rows of the table, five unless you ask for another number.
print(df.head())

pd.read_csv reads the file and returns the DataFrame, here stored in the variable df. The three looks then work like this:

  • df.shape gives the size. It is an attribute, a value stored on the DataFrame, not a function call, so it has no parentheses. For this file it is (5, 6): five rows, six columns.
  • df.dtypes lists the type pandas chose for each column.
  • df.head() returns the first five rows. It is the quickest way to see that the values landed in the right columns.

A related call, df.info(), prints all of this in one summary: the number of rows, each column's type and how many of its values are present.

For this file, pandas reads the columns with these types:

ColumnTypeWhat it holds
customer_idstrtext
planstrtext
monthsint64whole numbers
monthly_feefloat64numbers with decimals
support_callsint64whole numbers
leftstrtext

The types are worth reading closely, because pandas decides them from the values it finds. A column becomes a number type only if every value in it can be read as a number. If a column you expect to hold numbers shows up as str, at least one of its cells holds something else, such as a blank written as a space, and it has to be dealt with before the column can be used as a number. Older tutorials show text columns as object; pandas 3 shows them as str.

True or false?

To get the number of rows and columns of a DataFrame `df`, you call `df.shape()`.

False. `shape` is an attribute, written `df.shape` without parentheses. It holds the tuple (rows, columns).

A column of prices that pandas reports as `str` contains at least one value that is not a number.

True. pandas gives a column a number type only when every value can be read as a number; one blank or stray word keeps the whole column as text.

How often each answer occurs

The first question to ask of a label is how often each answer appears. This is the class balance.

pandas answers it in two steps. First, df["left"] picks one column out of the table; a single column like this is called a Series. Then its value_counts method counts each distinct value in that column, most frequent first. Given normalize=True, it returns each value's share of the rows instead of a count.

print(df["left"].value_counts())
print(df["left"].value_counts(normalize=True))
Printed
left
No     4
Yes    1
Name: count, dtype: int64
left
No     0.8
Yes    0.2
Name: proportion, dtype: float64

The shares are fractions between 0 and 1, so 0.2 means 20 percent. In this table one customer in five left. Real records about people leaving a service often look like this: most customers stay, and the answer that matters most is the rarer one.

  • 8 of 10 stayed: 0.8
  • 2 of 10 left: 0.2

A rare answer shapes everything that is measured afterwards. Consider a "model" that ignores every feature and always answers No. On a table where 80 percent of customers stayed, it is right on 80 percent of the rows, yet it never finds a single customer who leaves, which is the one thing it was built for. So a score is only meaningful next to the share of the most common answer: being right 80 percent of the time is no achievement when always saying No does the same.

The rare answer also means fewer examples to learn from. A table of 1,000 past customers with a 20 percent share of leavers holds only 200 examples of the answer that matters. Counting the classes first tells you what a useless model would score and how much evidence the model has for the rare answer.

True or false?

If 80 percent of past customers stayed, a model that is right on 80 percent of new customers has clearly learned something useful.

False. Always answering "stayed" is also right 80 percent of the time, while finding no customer who leaves. A score must be compared with that share.

`value_counts(normalize=True)` returns shares between 0 and 1, not percentages.

True. A share of 0.2 is 20 percent; multiply by 100 to read it as a percentage.