← Blog/KNN for Marketing: A Churn Early Warning List, Step by Step
Machine LearningKNNPythonChurnMarketing Analytics
Machine Learning · 23 min read

KNN for Marketing: A Churn Early Warning List, Step by Step

Use k-nearest neighbours to flag customers likely to cancel, with reasons customer success can act on. Real Python code, outputs and interactive charts.

· Martin Guzman

This is a business case for k-nearest neighbours (KNN): we use it to build a weekly churn early warning list for a made-up software company, step by step in Python. The top tenth of the list churns at 75.8 percent, nearly three times the average, and every name on it comes with a reason a customer success manager can read: "8 of its 10 closest past customers left".

KNN scores a customer by finding the past customers who looked most like it and checking how many of them cancelled. This guide focuses on the business problem and the build. For the math behind the model, how to choose its settings and how to judge it, read How KNN Works first or alongside.

Every number, table and chart below is real output from code you can download and run. The company and its data are invented, so nothing here belongs to a client.

The application: who customer success calls this week

Northpine Software, the made-up company whose data we use throughout this series, sells a business software subscription. It has 4,000 paying customers, and about one in four of them cancelled in the 90 days after the data snapshot this guide uses. Each cancellation is revenue that marketing and sales already paid to win.

Northpine's customer success team can make a limited number of proactive calls a week: a check-in, an offer of training, a fix for a problem nobody reported. A call to a happy customer is pleasant and changes nothing. A call to a customer who is quietly giving up can save the account. The question is who to call first?

What teams usually do

Without a model, customer success teams sort their book of accounts by one warning sign they trust:

  • Lowest seat use first. A customer paying for 50 seats and using 5 is not getting value.
  • Fewest logins first. People who stop logging in stop renewing.
  • Most support tickets first. Frustrated customers write in before they leave.

All three are sensible, and each looks at one column. A customer with low seat use may have just bought extra seats for a team that starts next month. A customer who files a lot of tickets may be the most engaged customer you have.

What KNN changes

KNN looks at every warning sign at once, and asks a question a customer success manager already asks by instinct: what happened to customers who looked like this one? On customers the model never saw, the comparison looks like this (step 11 shows the code):

How the list is sortedChurn rate in the top 10%How well it orders the whole list (AUC)
Lowest seat use first69.2%0.720
Fewest logins first49.2%0.691
Most support tickets first58.3%0.654
KNN churn risk75.8%0.774

The single-column rules leave many customers tied on the same value, so their top-10% figures can move by a couple of points depending on how ties are ordered; step 11 shows by how much. AUC is not affected.

Seat use alone is a strong rule: the keenest warning sign really is a customer not using what they pay for. KNN beats it at the top of the list and across the whole list, because it also weighs logins, tickets, onboarding, tenure, integrations, discount and plan together.

What the teams receive

Each week, a list with one row per customer: a risk score, and a reason in plain words. For example, the top of the list built in step 10:

CustomerPlanSeats in useLogins a weekSupport ticketsRiskReason
NC-02063Growth3%1.640.5888 of its 10 closest past customers left
NC-01079Growth3%2.440.5817 of its 10 closest past customers left
NC-01850Growth3%1.640.56910 of its 10 closest past customers left

And how each team uses it:

TeamDecisionWhat they do with the list
Customer successWho to call this weekWork down the list, opening with what went wrong for the similar customers who left
Lifecycle marketingWho gets a re-engagement programSend training and onboarding content to the top of the list, before renewal comes up
Account managementWhich renewals need attentionFlag high-risk accounts whose renewal falls in the next quarter
ProductWhat drives cancellationsRead the neighbours of high-risk customers for patterns, such as unfinished onboarding

Other places the same idea works

Scoring a customer by what happened to similar past customers also works for:

  • Downgrade risk: customers likely to move to a cheaper plan.
  • Expansion: customers who look like the ones that bought more seats.
  • Payment risk: customers who look like the ones that paid late.

KNN in one minute

How KNN scores one customer for churn risk
Step 1
Describe the customer
Seat use, logins, tickets, tenure and the rest, the same columns as every past customer
Step 2
Measure distance
How far it is from each past customer, on every column at once
Step 3
Take the k closest
Its nearest past customers, for example the 480 most similar
Step 4
Let them vote
Risk = share of those past customers that cancelled within 90 days
The model is the list of past customers whose outcome is known. Every score is a fresh vote among the most similar ones.

To score a customer, KNN measures how far it is from every past customer across all the columns at once, takes the closest ones, and reports the share of them that left. Two things follow, and both shape the build below: columns must be put on the same scale before distances mean anything, and every column you add counts, useful or not. How KNN Works explains both with the math.

Try it on Northpine's customers. The map shows past customers by two columns, the share of their paid seats in use and how often they log in. Drag the white diamond to place a customer and watch its nearest past customers vote. Customers in the bottom-left corner, few seats and few logins, are mostly red: most of them left.

Drag a customer and watch similar past customers vote
Try it
Try:
0%25%50%75%100%0251020share of paid seats in uselogins per week (square-root scale)
10
Drag the white diamond, tap anywhere, or use the arrow keys.
Churn risk for this customer
80%
8 of 10 similar past customers left. This customer: 6% of seats in use, 1.5 logins a week.
left within 90 daysstayed
A random sample of 400 of the 2,800 past customers; 25% of them left.
Two columns only, seat use and logins, so it can be drawn. The model in this case measures distance across nine columns.

The data: Northpine Software

This case uses one table, northpine_customers.csv: 4,000 paying customers, what Northpine knew about each one, and whether it cancelled in the 90 days that followed. It is the same table that part 5 of this series, on XGBoost, will use (see the series table below), so the two methods can be compared on the same customers. Here are the first five rows, with a few columns left out to fit:

customer_idindustryemployeesplantenure (months)seats usedlogins a weekchurned
NC-00001Education183Growth70.543.70
NC-00002Software2,706Growth170.637.10
NC-00003Education546Enterprise170.8312.70
NC-00004Healthcare449Growth360.964.30
NC-00005Professional services36Starter300.419.40

And what every column means:

ColumnWhat it isRange
industryThe customer's sectorsix sectors
regionProvince or region of Canadasix regions
employeesCompany headcount5 to 5,000, median 177
first_channelHow the customer first found Northpinesix channels
planSubscription planStarter (361), Growth (3,066), Enterprise (573)
signup_discount_pctDiscount given at signup0 to 25 percent
tenure_monthsMonths as a customer2 to 36, median 20
onboarding_completedFinished onboarding (1) or not (0)0 or 1
integrations_connectedOther tools connected to Northpine0 to 9, median 2
seats_used_pctShare of paid seats in use0.03 to 0.99, median 0.61
logins_per_weekAverage logins a week0 to 38.6, median 4.1
support_tickets_90dSupport tickets in the last 90 days0 to 12, median 1
first_year_valueRevenue in the customer's first yeardollars
churned_next_90dCancelled in the next 90 days (1) or not (0)0 or 1

Two things to notice before writing any code.

Churn is common. 1,026 of the 4,000 customers cancelled, about one in four. That is far more than the 7 percent buyers in the lookalike case, and it changes what a good model looks like: the list does not need to find needles in a haystack, it needs to put the right quarter of customers at the top.

Every column must describe the customer before the 90 days start. A column filled in because the customer was leaving, such as a cancellation reason or an exit survey score, would let the model spot churners by their paperwork. It would look brilliant in testing and be useless on Monday morning, when nobody has filed that paperwork yet. This mistake is called leakage.

Step by step in Python

The code uses pandas and scikit-learn, both free. Every block below is a cell in the downloadable notebook, and every output shown is what it printed.

Step 1: load the data

import numpy as np
import pandas as pd
from sklearn.compose import make_column_transformer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import StratifiedKFold, cross_val_score, train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
 
customers = pd.read_csv("northpine_customers.csv")
print(customers.shape)
customers.head()
(4000, 15)

Four thousand rows, one per customer, and fifteen columns.

Step 2: look at the outcome

customers["churned_next_90d"].value_counts()
churned_next_90d
0    2974
1    1026

1,026 churners. Keep the rate of about one in four in mind: every result below should be compared with it.

Step 3: choose the columns

numeric = ["employees", "signup_discount_pct", "tenure_months", "onboarding_completed",
           "integrations_connected", "seats_used_pct", "logins_per_week",
           "support_tickets_90d"]
categorical = ["plan"]
 
X = customers[numeric + categorical].copy()
X["employees"] = np.log10(X["employees"])   # 10 -> 1, 100 -> 2, 1,000 -> 3
y = customers["churned_next_90d"]

X holds what we know about each customer and y holds what we want to predict. Nine columns go in. Four decisions are hiding in those lines:

  • first_year_value is left out. It is not known for customers in their first year, who are exactly the ones a churn list most needs to cover. And what it records, mostly plan, size and discount, is already in the model through other columns. Including it would add a second copy of the same information, which in KNN means counting it twice in every distance.
  • customer_id is left out. It is a label, not a description. Two customers with neighbouring IDs are no more alike than any other two.
  • industry, region and first_channel are left out. They describe who the customer is, not how they use the product. Adding all three back gives a cross-validated AUC of 0.756 against 0.757 without them (the notebook appendix has the code): no help, and three more columns to dilute every distance.
  • Headcount goes in as its logarithm, because the gap between 10 and 110 employees matters far more than the gap between 4,000 and 4,100 (the scaling section of How KNN Works shows the math).

Step 4: hold some customers back

X_past, X_now, y_past, y_now = train_test_split(
    X, y, test_size=0.3, stratify=y, random_state=42)
 
print(f"past customers (to learn from): {len(X_past):,}, {y_past.sum()} churned")
print(f"customers to score now:         {len(X_now):,}, {y_now.sum()} churned")
past customers (to learn from): 2,800, 718 churned
customers to score now:         1,200, 308 churned

We set aside 30 percent of customers and do not look at them until the end. They stand in for this week's book of accounts: the model has to score them without knowing what they will do. The other 70 percent are the past customers whose outcomes the model learns from. stratify=y keeps the churn rate the same in both groups, and random_state=42 makes the split repeatable, so your numbers will match these.

In real use the split is by time: past customers are last quarter's accounts, whose 90 days are over, and the customers to score are today's. A random split is the simplest honest test with one snapshot of data.

Step 5: build the pipeline

prep = make_column_transformer(
    (StandardScaler(), numeric),
    (OneHotEncoder(handle_unknown="ignore"), categorical),
)
knn = make_pipeline(prep, KNeighborsClassifier(n_neighbors=25))

A pipeline chains the preparation and the model so they always run together, in the same order. StandardScaler puts each numeric column on the same scale, so that a difference of one login a week and a difference of 30 percent seat use are compared fairly. OneHotEncoder turns plan into three yes-or-no columns, because distance needs numbers. Because the scaler sits inside the pipeline, its averages are learned from past customers only. The n_neighbors=25 is a placeholder; the next step chooses it.

Step 6: choose k with cross-validation

folds = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
 
results = []
for k in [1, 5, 10, 20, 40, 80, 120, 160, 240, 320, 480, 640]:
    knn.set_params(kneighborsclassifier__n_neighbors=k)
    auc = cross_val_score(knn, X_past, y_past, cv=folds, scoring="roc_auc").mean()
    results.append((k, round(auc, 3)))
 
pd.DataFrame(results, columns=["k", "cv_auc"])
      k  cv_auc
0     1   0.594
1     5   0.686
2    10   0.710
3    20   0.735
4    40   0.738
5    80   0.741
6   120   0.743
7   160   0.746
8   240   0.753
9   320   0.752
10  480   0.757
11  640   0.757

Cross-validation tries each k on past customers only: it builds the model on four fifths of them, scores the last fifth, and repeats until each fifth has been scored once. AUC, the measure in the table, is the chance that a random churner gets a higher score than a random customer who stayed: 0.5 is a coin toss and 1 is perfect.

Choosing k: cross-validated AUC for each number of neighbours
Try it
scaled columnsraw numbers
0.600.650.700.750.801510204080160320640number of neighbours that vote, k (log scale)cross-validated AUC
Best: k = 480, AUC 0.757. Hover or tap the curve to read each k.
Five-fold cross-validation on the 2,800 past customers. Real output from step 6 and the notebook appendix.

What the curve says:

  • A handful of neighbours is too few. With one neighbour, a customer's score is whatever its single closest match did, and AUC is 0.594.
  • After about 40 neighbours, the curve is nearly flat. It creeps from 0.738 at 40 to 0.757 at 480. The best k is large, 480, which is 17 percent of all past customers.
  • Scaling matters. The amber line is the same model on raw numbers, without scaling. It peaks at 0.682 and falls as k grows.

Why does such a large k win? Churn here depends on a few broad conditions, such as low seat use, low logins and unfinished onboarding, rather than on fine detail. A large neighbourhood averages over many customers in the same broad situation and gives a steadier score. The cost is that "480 similar customers" stretches the word similar, which is why the list in step 10 explains each score with the 10 closest neighbours instead. Choosing k in the main guide explains the trade-off.

Step 7: fit the model and test it once

best_k = max(results, key=lambda r: r[1])[0]
knn.set_params(kneighborsclassifier__n_neighbors=best_k)
knn.fit(X_past, y_past)
 
risk = knn.predict_proba(X_now)[:, 1]
print(f"k = {best_k}, test AUC = {roc_auc_score(y_now, risk):.3f}")
k = 480, test AUC = 0.774

On the 1,200 customers it never saw, the model ranks a random churner above a random stayer 77 percent of the time, close to the cross-validated estimate of 0.757. The model did not just memorise its training customers.

Step 8: is the list worth using?

AUC says the order is good. Customer success needs something more concrete: if we call the top of the list, how many of the customers we reach were really about to leave?

ranked = pd.DataFrame({"risk": risk, "churned": y_now.values})
ranked = ranked.sort_values("risk", ascending=False, kind="stable").reset_index(drop=True)
ranked["decile"] = ranked.index * 10 // len(ranked) + 1
 
by_decile = ranked.groupby("decile")["churned"].agg(customers="count",
                                                    churned="sum",
                                                    rate="mean")
by_decile["lift"] = by_decile["rate"] / ranked["churned"].mean()
by_decile.round(3)
        customers  churned   rate   lift
decile
1             120       91  0.758  2.955
2             120       52  0.433  1.688
3             120       40  0.333  1.299
4             120       33  0.275  1.071
5             120       30  0.250  0.974
6             120       19  0.158  0.617
7             120       13  0.108  0.422
8             120       10  0.083  0.325
9             120       11  0.092  0.357
10            120        9  0.075  0.292

This sorts the 1,200 customers from highest risk to lowest, cuts them into ten groups of 120 called deciles, and counts the churners in each. Lift is each group's churn rate divided by the overall rate. kind="stable" keeps customers with equal scores in their original order, so the result is the same every time.

Reading it as a customer success lead:

  • The top tenth churns at 75.8 percent, nearly three times the average. Of the 120 customers there, 91 were about to leave.
  • The bottom three tenths still lose some customers. 30 of the 360 customers there churned. No list built from these columns catches everyone; some customers leave for reasons the data does not record.
  • Not every high-risk customer leaves. A quarter of the top decile stayed. A call to them is not wasted, but it is a check-in, not a rescue.

How many calls should the team make? Slide the cut-off. Calling the top 120 reaches 91 churners where a random 120 would reach 31. Calling the top 240 reaches 143, 46 percent of all churners, against 62 at random. Where to stop depends on what a call costs and what a saved customer is worth.

How many calls, how many churners reached
Try it
120
Churners reached
91
30% of 308
A random list
31
same number of calls
Hit rate
76%
base rate 26%
010020030002004006008001,0001,200customers called, highest risk firstchurners reached
KNN churn risk, highest firstrandom order
The 1,200 test customers, called from the highest KNN risk down. The model never saw them while it was built.

Step 9: explain a score

A churn score that customer success cannot explain will not be used. Take the customer with the highest risk and ask the model which past customers it was compared with:

steps = knn.named_steps
top = X_now.iloc[[np.argmax(risk)]]
distance, index = steps["kneighborsclassifier"].kneighbors(
    steps["columntransformer"].transform(top), n_neighbors=5)
 
show = ["customer_id", "plan", "tenure_months", "onboarding_completed",
        "seats_used_pct", "logins_per_week", "support_tickets_90d", "churned_next_90d"]
print(customers.loc[top.index, show].to_string(index=False))
neighbours = customers.loc[X_past.index[index[0]], show]
neighbours.assign(distance=distance[0].round(2))

The customer:

customer_idplantenureonboardingseats usedlogins a weekticketschurned
NC-02063Growth1500.031.641

Its five closest past customers:

customer_idplantenureonboardingseats usedlogins a weekticketschurneddistance
NC-03944Growth1300.211.8301.31
NC-03923Growth1000.291.6511.55
NC-02853Growth1300.143.5401.57
NC-02984Growth1500.034.1511.61
NC-02423Growth2300.280.3411.63

A Growth customer, more than a year in, that never finished onboarding, uses 3 percent of its seats, barely logs in and keeps filing tickets. Its closest matches are in the same situation, and three of these five left. In fact this customer did cancel.

That is the conversation a customer success manager can open with. Not "the model says you are at risk", but "customers set up like you often never get the team using it; can we run the onboarding you skipped?". If the closest matches made no business sense, that would be a sign that something is wrong with the columns or the scaling.

Step 10: build the call list

Now score this week's customers and keep the 50 most at risk, each with a reason:

now = customers.loc[X_now.index].copy()
now["risk"] = risk.round(3)
 
_, closest = steps["kneighborsclassifier"].kneighbors(
    steps["columntransformer"].transform(X_now), n_neighbors=10)
now["closest_10_left"] = y_past.values[closest].sum(axis=1)
now["reason"] = now["closest_10_left"].astype(str) + " of its 10 closest past customers left"
 
call_list = now.sort_values("risk", ascending=False, kind="stable").head(50)
call_list[["customer_id"]].to_csv("churn_call_list.csv", index=False)
 
call_list[["customer_id", "plan", "seats_used_pct", "logins_per_week",
           "support_tickets_90d", "risk", "reason"]].head(10)
customer_idplanseats usedlogins a weekticketsriskreason
NC-02063Growth0.031.640.5888 of its 10 closest past customers left
NC-01079Growth0.032.440.5817 of its 10 closest past customers left
NC-01850Growth0.031.640.56910 of its 10 closest past customers left
NC-01523Growth0.261.860.5628 of its 10 closest past customers left
NC-01371Growth0.140.650.55810 of its 10 closest past customers left
NC-02527Growth0.200.980.5549 of its 10 closest past customers left
NC-02685Growth0.232.460.5529 of its 10 closest past customers left
NC-02965Growth0.141.250.5429 of its 10 closest past customers left
NC-01016Growth0.172.540.5428 of its 10 closest past customers left
NC-00081Growth0.211.450.5408 of its 10 closest past customers left

Two details in that code matter:

  • The score and the reason use different neighbourhoods, on purpose. The risk score is the share of all 480 voting neighbours that left: 0.588 means 282 of them. That is the steadiest ranking. The reason uses only the 10 closest, because "8 of its 10 closest past customers left" is something a person can check and believe. The two agree on direction: for every customer in this top ten, at least 7 of the 10 closest left.
  • Do not read the score as a probability. In the top tenth, the average score was 0.454, but 75.8 percent actually churned. A vote over 480 neighbours pulls every score toward the average. Use it to rank, not to forecast how many customers you will lose (the calibration check explains why this happens).

Pick a customer from the top of the list to see the 40 past customers nearest to it, nearest first. The red squares left.

The call list, and the past customers behind each row
Try it
customerseatsloginsriskreason
3%1.60.5888 of 10 closest left
3%2.40.5817 of 10 closest left
3%1.60.56910 of 10 closest left
26%1.80.5628 of 10 closest left
14%0.60.55810 of 10 closest left
20%0.90.5549 of 10 closest left
23%2.40.5529 of 10 closest left
14%1.20.5429 of 10 closest left
17%2.50.5428 of 10 closest left
21%1.40.5408 of 10 closest left
NC-02063, Growth plan, 15 months a customer, onboarding not completed, 4 support tickets in 90 days. 8 of its 10 closest past customers left, and 282 of all 480 that vote.
Pick a customer above, then hover a square to see that past customer.
left within 90 daysstayed
The top 10 of the 1,200 test customers by risk. Each square is one of the 40 nearest past customers, nearest first.

Step 11: how does KNN compare?

A fair guide should compare the method with the simple rules a team would use without any model, and with another model:

logit = make_pipeline(prep, LogisticRegression(max_iter=1000)).fit(X_past, y_past)
 
def top_decile_rate(score):
    order = pd.DataFrame({"score": score, "churned": y_now.values})
    order = order.sort_values("score", ascending=False, kind="stable")
    return order["churned"].head(len(order) // 10).mean()
 
rankings = {
    "Lowest seat use first": -X_now["seats_used_pct"],
    "Fewest logins first": -X_now["logins_per_week"],
    "Most support tickets first": X_now["support_tickets_90d"],
    "KNN churn risk": risk,
    "Logistic regression": logit.predict_proba(X_now)[:, 1],
}
pd.DataFrame({
    "top_10pct_churn_rate": {n: round(top_decile_rate(s), 3) for n, s in rankings.items()},
    "auc": {n: round(roc_auc_score(y_now, s), 3) for n, s in rankings.items()},
})
                            top_10pct_churn_rate    auc
Lowest seat use first                      0.692  0.720
Fewest logins first                        0.492  0.691
Most support tickets first                 0.583  0.654
KNN churn risk                             0.758  0.774
Logistic regression                        0.742  0.784

Each ranking is judged on the same 1,200 unseen customers. Seat use and logins are negated so that the lowest values come first.

Single-column rules have many ties, so their top-10% figure depends on the order in which tied customers happen to fall. The top-10% cut for support tickets lands inside a block of 66 customers who all filed 4 tickets. Over 200 random orders of the tied customers (the notebook appendix has the code), that rule's top-10% churn rate averages 59.6 percent and ranges from 58.3 to 60.8 percent. Seat use averages 68.1 percent and logins 49.6 percent. AUC is unaffected, because it counts a tied pair as half right whatever the order.

KNN against simple rules and logistic regression
Try it
Lowest seat use first69.2%Fewest logins first49.2%Most support tickets first58.3%KNN churn risk75.8%Logistic regression74.2%base rate 25.7%
Hover or tap a bar to read it.
All five rankings judged on the same 1,200 test customers. Real output from step 11.

The honest reading:

  • Logistic regression orders the whole list slightly better, 0.784 against 0.774. That is common: KNN is rarely the most accurate method overall. Logistic regression is the subject of part 3 of this series.
  • KNN does slightly better at the very top, 75.8 percent against 74.2 percent in the top tenth. That is a difference of two customers out of 120, so treat the two as level there.
  • Both clearly beat every single-column rule. The best rule, lowest seat use, reaches 69.2 percent at the top and 0.720 overall.

So why use KNN? For the same reasons as in the lookalike case. Every score comes with real past customers that explain it, which matters more for churn than for most problems, because the person acting on the list has to start a conversation with the customer. It makes no assumption about the shape of the relationship. And it adapts at once: add last quarter's outcomes to the table and the next scores use them, with no retraining.

Using the list

A list only matters if someone acts on it. Ways Northpine could use this one:

  • Weekly calls. Hand the top of the list to customer success every Monday, each customer with its 10 closest past customers, so the call can start from what went wrong for similar accounts.
  • Automated help for the next tier. Customers ranked just below the call list get an onboarding email series or a training invitation, rather than a call.
  • Pair it with renewal dates. A high-risk customer renewing in three weeks needs attention before one renewing in ten months.
  • Refresh weekly. Logins and tickets change from week to week, and the list should too.

Then measure whether the calls work. The decile table shows that high-risk customers leave more often. It does not show that calling them keeps them, because they were at risk either way. To measure what the calls add, hold back a random part of the high-risk list, call the rest, and compare churn between the two groups after 90 days. That is an incrementality test, explained in Incrementality Meaning, With a Marketing Example. Without it, a team can make hundreds of calls a quarter and never know whether one of them mattered.

Mistakes to avoid

  • Leaky columns. Cancellation reasons, exit survey scores, a "renewal at risk" flag set by an account manager who already knew: anything recorded because the customer was leaving makes the model look perfect in testing and useless in practice.
  • Training on the wrong window. Past customers must have had their full 90 days. A customer who joined last month and has not had time to cancel looks like a stayer and teaches the model the wrong thing.
  • Skipping scaling. Without it, the column with the biggest numbers, such as logins, tenure or discount, decides who counts as similar. On this data, the unscaled model never passes an AUC of 0.682.
  • Explaining with all k neighbours. A list of 480 "similar customers" persuades nobody. Score with the k that cross-validation picks, and explain with the closest few.
  • Reading the score as a forecast. The top tenth of the list averaged a risk of 0.454, and 75.8 percent of it churned. Use the score to rank, not to count expected losses.
  • Calling only the top and measuring nothing. Hold back a random group, or you will never know whether the calls saved anyone.
  • Letting the list go stale. Churn signals move weekly. A list built a month ago calls customers who have already gone.

KNN and the rest of the series

For when KNN is the right choice and when it is not, see How KNN Works. Part 5 of this series uses XGBoost on the same northpine_customers.csv, so that it can be compared with this case on the same customers.

MethodWhat it gives youStrengthWatch out for
KNN (this case)A risk score from similar past customersExplains itself with real customersScaling, large k blurs "similar"
Linear regressionHow much one number moves anotherSimple, readable effectsMistaking correlation for cause
Logistic regressionA probability for a yes or no outcomeAccurate, clear weights per columnStraight-line assumptions
Decision treeRules that split customers into groupsRules anyone can readUnstable, overfits if allowed
XGBoostStrong predictions from many treesUsually the most accurateNeeds extra tools to explain

Download the data and the notebook

Both files are free to use. The notebook runs every step of this guide in order and already contains the outputs shown above, so you can compare your results line by line.

To run it: install Python, then run pip install pandas scikit-learn jupyter, put both files in one folder, and open the notebook with Jupyter. Step 10 writes your own churn_call_list.csv.

Want this on your own data?

If you would like a churn early warning list built from your own product usage and CRM data, or want to know whether your data is ready for it, get in touch and we can talk it through on a short call.