← Blog/KNN for Marketing: Build a Lookalike Audience, Step by Step
Machine LearningKNNPythonAudiencesMarketing Analytics
Machine Learning · 22 min read

KNN for Marketing: Build a Lookalike Audience, Step by Step

A step-by-step guide to k-nearest neighbours for marketers: build a lookalike list in Python, with real code, charts and an interactive demo.

· Martin Guzman

This is a business case for k-nearest neighbours (KNN): we use it to build a lookalike list for a made-up software company, step by step in Python, and the top tenth of the list converts at nearly four times the average rate.

KNN scores a prospect by finding the known accounts that look most like it and checking how many of them became customers. 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 gets called, and who sees the ads

Here is the situation, at Northpine Software, the made-up company whose data we use throughout.

In the last 90 days, 5,000 companies visited Northpine's website. Sales is already talking to 724 of them. That leaves 4,276 companies that showed some interest and that nobody has contacted. Suppose the sales team has time to research and call about 200 of them a month, and marketing has budget for a matched ad audience of a few hundred companies. The question is the same for both teams: which accounts first?

What teams usually do

Without a model, teams sort the list by one signal they trust:

  • Most recent visit first. Whoever was on the site yesterday gets the call.
  • Most pricing page visits first. Whoever looked at prices most often gets the call.

Both are reasonable, and both use one column out of many. A company that visited yesterday may be a student. A company that checked prices twice may be a perfect fit that nobody follows up because someone else checked three times.

What KNN changes

KNN ranks every account at once by how closely it resembles the accounts that went on to buy, using all the signals together: size, industry, visits, downloads, webinars, emails, pricing views and recency. On accounts the model never saw, the comparison looks like this (step 11 shows the code):

How the list is sortedCustomer rate in the top 10%How well it orders the whole list (AUC)
Most recent visit first19.3%0.740
Most pricing page visits first26.7%0.719
KNN lookalike score28.7%0.840
Average account, unsorted7.3%0.500

Pricing page visits do well at the very top, because the keenest accounts really do check prices. But most accounts have no pricing views at all, so that rule cannot order the other 90 percent of the list, which is why its AUC is the lowest. KNN beats both rules at the top and orders the whole list far better, which matters as soon as you work past the first few dozen names.

What the teams receive

Each month, a table with one row per account: its lookalike score, and the five past accounts it most resembles. For example, the top of the list built in step 10:

AccountIndustryEmployeesPricing page visitsWebinarLookalike score
NP-01617Professional services897yes0.483
NP-02540Software1725yes0.450
NP-01445Professional services1525yes0.425

And how each team uses it:

TeamDecisionWhat they do with the list
Sales developmentWho to call this monthWork the top 200, opening with what similar companies cared about
Account-based marketingWho gets a tailored campaignTake the top of the list as the target account list
Paid mediaWho sees the adsUpload the top scorers as a matched audience, and leave the bottom of the list out
Marketing operationsWhere not to spendSuppress the bottom four tenths, which hold almost no future customers

Other places the same idea works

The idea behind KNN, that you can judge something by the company it keeps, also sits underneath:

  • Lookalike audiences in ad platforms. You upload customers and the platform finds people who resemble them. The platforms' methods are their own and are not published, but the question is the one this guide answers.
  • "Customers like you also bought". Recommendations from the purchases of similar customers.
  • Filling gaps in a CRM. Estimating a missing company size or industry from the most similar complete records.

KNN in one minute

How KNN scores one prospect
Step 1
Place the prospect
Describe it with the same columns as every known account
Step 2
Measure distance
How far it is from each known account, on every column at once
Step 3
Take the k closest
Its nearest neighbours, for example the 120 most similar accounts
Step 4
Let them vote
Score = share of those neighbours that became customers
There is no training in the usual sense: the model is the list of known accounts, and every score is a fresh vote.

To score an account, KNN measures how far it is from every known account across all the columns at once, takes the 120 closest, and reports the share that became customers. 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 accounts: drag the prospect and watch its nearest neighbours vote.

Drag a prospect and watch its neighbours vote
Try it
Distance:Try:
101001,00004812employees (log scale)engagement actions, 90 days
9
Drag the white diamond, tap anywhere, or use the arrow keys.
Lookalike score for this prospect
89%
8 of its 9 nearest accounts became customers. Prospect: 220 employees, 7 engagement actions.
Both features count equally because each is measured in standard deviations.
became a customerdid notSample of 280 real Northpine accounts, customers over-sampled to 25% so they are visible (the true rate is 7.3%).
Two features only, so it can be drawn. The model in this guide measures distance across ten.

The data: Northpine Software

Northpine Software is an invented Canadian company that sells a business software subscription. Every guide in this series uses its data, so you can compare methods on the same business.

This guide uses one table, northpine_accounts.csv: 5,000 companies that visited Northpine's website in the last 90 days, with what marketing knew about each one and whether it went on to become a customer. Here are the first five rows, with a few columns left out to fit:

account_idindustryemployeesweb visitspricing page visitswebinarbecame customer
NP-00001Professional services419000
NP-00002Healthcare123100
NP-00003Software14611401
NP-00004Software363000
NP-00005Professional services521100

And what every column means:

ColumnWhat it isRange
industryThe company's sectorsix sectors
regionProvince or region of Canadasix regions
employeesCompany headcount5 to 4,937, median 100
first_channelHow the company first found Northpinesix channels
web_visits_90dWebsite visits in the last 90 days0 to 32
pages_per_visitAverage pages viewed per visit1 to 6.6
content_downloads_90dGuides and reports downloaded0 to 9
webinar_attendedAttended a webinar (1) or not (0)0 or 1
email_clicks_90dClicks on marketing emails0 to 13
pricing_page_visits_90dVisits to the pricing page0 to 10
days_since_last_visitDays since the last website visit0 to 180
became_opportunitySales opened a deal (1) or not (0)0 or 1
became_customerThe company bought (1) or not (0)0 or 1

Two things to notice before writing any code.

Customers are rare. 366 of the 5,000 accounts became customers, 7.3 percent. That is normal for a marketing funnel, and it shapes how we measure the model later: a model that says "nobody buys" would be right 92.7 percent of the time and completely useless.

Every column describes the account before it bought. That is deliberate. If a column were only filled in after a sale, such as the plan a customer chose, a model would learn to spot customers by their paperwork and look brilliant in testing, then fail on real prospects who do not have that paperwork yet. This mistake is called leakage, and it is the most common way a marketing model fools its builder.

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_predict,
                                     cross_val_score, train_test_split)
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
 
accounts = pd.read_csv("northpine_accounts.csv")
print(accounts.shape)
accounts.head()
(5000, 14)

Five thousand rows, one per account, and fourteen columns.

Step 2: look at the outcome

accounts["became_customer"].value_counts()
became_customer
0    4634
1     366

This is the 7.3 percent from earlier. Keep it in mind: it is the number every result below should be compared with.

Step 3: choose the columns

numeric = ["employees", "web_visits_90d", "pages_per_visit",
           "content_downloads_90d", "webinar_attended", "email_clicks_90d",
           "pricing_page_visits_90d", "days_since_last_visit"]
categorical = ["industry"]
 
X = accounts[numeric + categorical].copy()
X["employees"] = np.log10(X["employees"])   # 10 -> 1, 100 -> 2, 1,000 -> 3
y = accounts["became_customer"]

X holds what we know about each account and y holds what we want to predict. Three decisions are hiding in those lines:

  • became_opportunity is left out. It records a later stage of the same journey, so including it would be leakage: the model would learn "accounts sales already took on tend to buy", which is true and useless for finding new prospects.
  • region and first_channel are left out. In Northpine's data, region has no relationship with buying. Adding it anyway makes KNN slightly worse, 0.822 against 0.827, because every useless column adds noise to every distance. With KNN, fewer, better columns beat more columns. (First channel does matter, but through engagement, which we already include.)
  • 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 accounts back

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.3, stratify=y, random_state=42)
 
print(f"train: {len(X_train):,} accounts, {y_train.sum()} customers")
print(f"test:  {len(X_test):,} accounts, {y_test.sum()} customers")
train: 3,500 accounts, 256 customers
test:  1,500 accounts, 110 customers

We set aside 30 percent of accounts and do not look at them until the very end. They stand in for next month's prospects: the only honest test of a model is how it does on accounts it has never seen. stratify=y keeps the share of customers the same in both groups, which matters when customers are this rare. random_state=42 just makes the split repeatable, so your numbers will match these.

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, on any data you give them. It has two parts:

  • StandardScaler puts each numeric column on the same scale (why that matters).
  • OneHotEncoder turns industry into six yes-or-no columns, one per sector, because distance needs numbers. Two accounts in different industries end up about 1.4 apart on these columns, about the same as a difference of one and a half standard deviations on a numeric column, which is a reasonable weight for "different sector".

Putting the scaler inside the pipeline matters more than it looks. It means the averages and standard deviations are learned from the training accounts only, and then applied unchanged to anything scored later. Scaling the whole table first would let information from the test accounts leak into the model, a quieter version of the leakage problem.

The n_neighbors=25 is a placeholder. The next step chooses it properly.

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, 60, 80, 120, 160, 240]:
    knn.set_params(kneighborsclassifier__n_neighbors=k)
    auc = cross_val_score(knn, X_train, y_train, 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.580
1    5   0.680
2   10   0.729
3   20   0.783
4   40   0.815
5   60   0.820
6   80   0.824
7  120   0.827
8  160   0.824
9  240   0.827

Cross-validation tries each k without touching the test accounts. It splits the training accounts into five parts, builds the model on four, scores the fifth, and repeats so every part is scored once. The result is a fair estimate of how each k would do on new accounts.

Choosing k: cross-validated AUC for each number of neighbours
0.50.60.70.8151020406080120160240k, the number of neighboursAUCbest k = 120
scaledraw numbersHover the chart to read each k
Five-fold cross-validation on the 3,500 training accounts of the lookalike model. Real output from the notebook.

What the curve says:

  • Small k is noisy. With one neighbour, an account's score is whatever its single closest match did. That reacts to chance, and AUC is 0.58, barely better than a coin toss.
  • The curve rises fast, then flattens. From about 60 neighbours on, every k scores between 0.820 and 0.827. In that range the choice hardly matters.
  • Scaling beats raw numbers at every k. The amber line is the same model without scaling. It never gets above 0.78.

How KNN Works explains the trade-off behind this curve. Why does a large k work here? Customers are 7 percent of accounts, so a vote among 5 neighbours can only say 0, 20, 40, 60, 80 or 100 percent, and most votes come out zero. A vote among 120 gives a finer, steadier score. With a rare outcome, expect the best k to be larger than textbook examples suggest.

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_train, y_train)
 
test_scores = knn.predict_proba(X_test)[:, 1]
print(f"k = {best_k}, test AUC = {roc_auc_score(y_test, test_scores):.3f}")
k = 120, test AUC = 0.840

On the 1,500 accounts it never saw, the model ranks a random customer above a random non-customer 84 percent of the time. The test result is close to the cross-validation estimate of 0.827, which is what you want: the model did not just memorise its training accounts.

For KNN, "fit" only stores the training accounts and the scaling settings. The work happens at scoring time, when each new account is compared with all 3,500 stored ones.

Step 8: is the list worth using?

AUC tells you the order is good. A marketing team needs something more concrete: if we work the top of the list, how many more customers do we find than if we picked at random?

ranked = pd.DataFrame({"score": test_scores, "customer": y_test.values})
ranked = ranked.sort_values("score", ascending=False, kind="stable").reset_index(drop=True)
ranked["decile"] = ranked.index * 10 // len(ranked) + 1
 
by_decile = ranked.groupby("decile")["customer"].agg(accounts="count",
                                                       customers="sum",
                                                       rate="mean")
by_decile["lift"] = by_decile["rate"] / ranked["customer"].mean()
by_decile.round(3)
        accounts  customers   rate   lift
decile
1            150         43  0.287  3.909
2            150         22  0.147  2.000
3            150         19  0.127  1.727
4            150         14  0.093  1.273
5            150          6  0.040  0.545
6            150          5  0.033  0.455
7            150          0  0.000  0.000
8            150          1  0.007  0.091
9            150          0  0.000  0.000
10           150          0  0.000  0.000

This sorts the test accounts from highest score to lowest, cuts them into ten equal groups called deciles, and counts the customers in each. Lift is each group's customer rate divided by the overall rate. kind="stable" keeps accounts with equal scores in their original order, so the result is the same every time you run it.

Is the list useful? The 1,500 test accounts, ranked by lookalike score
0%10%20%30%12345678910base rate 7.3%decile of the ranked list (1 = highest scores)
Hover a bar to read it.
Real output from step 8. The model never saw these accounts while it was being built.

Reading it as a marketer:

  • The top tenth converts at 28.7 percent, nearly four times the 7.3 percent average. Those 150 accounts hold 43 of the 110 customers in the test set.
  • Working the top fifth of the list finds 59 percent of all customers. Working the top 30 percent finds 76 percent. Picking at random, you would find 20 and 30 percent.
  • The bottom four deciles hold almost nobody. Of 600 accounts, one became a customer. That is useful too: it is where outreach and ad spend can safely stop.
  • The curve is not perfectly smooth. Decile 8 has one customer and decile 7 has none. With 150 accounts per group, a single customer either way moves the rate, so read the overall slope rather than each bar.

Lift is one way to read the ranking. The question a sales manager actually asks is how many accounts should we call? Slide the cut-off. Calling the top 150 finds 43 customers where a random 150 would find 11. Calling the top 450 finds 84, three quarters of them, and leaves 26 behind. Where to stop depends on what a call costs and what a customer is worth, which is a business decision the model can inform but not make.

Where to cut the list
Try it
150 of 1,500
became customers
did not
contacted
43
found
worth the call
107
calls that went nowhere
the cost of the list
not contacted
67
missed
customers left on the table
1,283
rightly skipped
time saved
hit rate
28.7%
average is 7.3%
customers found
39%
of all 110
random list would find
11
vs 43 with KNN
lift
3.9×
against random
05010005001,0001,500
customers found, KNN orderrandom order
The 1,500 test accounts, contacted from the highest score down.

Step 9: explain a score

This is where KNN earns its place. Take the test account with the highest score and ask the model which known accounts it was compared with:

steps = knn.named_steps
best = X_test.iloc[[np.argmax(test_scores)]]
distance, index = steps["kneighborsclassifier"].kneighbors(
    steps["columntransformer"].transform(best), n_neighbors=5)
 
show = ["account_id", "industry", "employees", "pricing_page_visits_90d",
        "content_downloads_90d", "webinar_attended", "became_customer"]
neighbours = accounts.loc[X_train.index[index[0]], show]
neighbours.assign(distance=distance[0].round(2))
account_idindustryemployeespricing page visitsdownloadswebinarbecame customerdistance
NP-02540Software17255103.96
NP-02986Software17852114.21
NP-01612Retail19463114.31
NP-04097Manufacturing33764114.39
NP-02027Software17293104.93

These are its five closest matches out of the 120 that voted: mid-sized companies that looked at pricing five to nine times, downloaded content and came to a webinar. Three of the five bought.

Being able to say this matters in practice. A sales team will not work a list because "the model says so". They will work it if you can say "this account is behaving like these five, and three of them bought". It also lets you catch a bad model early: if the closest matches make no business sense, something is wrong with the columns or the scaling.

To see all 120 neighbours that vote on this account, and which columns the model relies on most, see Looking inside a KNN model.

Step 10: build the lookalike list

Now score the accounts sales has not yet taken on, and keep the top 200:

scores = cross_val_predict(knn, X, y, cv=folds, method="predict_proba")[:, 1]
accounts["lookalike_score"] = scores.round(3)
 
prospects = accounts[accounts["became_opportunity"] == 0]
shortlist = prospects.sort_values("lookalike_score", ascending=False).head(200)
shortlist[["account_id"]].to_csv("lookalike_shortlist.csv", index=False)
 
shortlist[["account_id", "industry", "employees", "pricing_page_visits_90d",
           "webinar_attended", "lookalike_score"]].head(10)
account_idindustryemployeespricing page visitswebinarlookalike score
NP-01617Professional services89710.483
NP-02540Software172510.450
NP-01445Professional services152510.425
NP-01264Healthcare116410.400
NP-00957Software161310.358
NP-02350Professional services613110.358
NP-03158Education46510.350
NP-01047Manufacturing58510.342
NP-02583Software439300.333
NP-03251Software68400.333

Two details in that code are easy to get wrong:

  • cross_val_predict scores each account with a model that has not seen it. Scoring an account with a model that includes it would let it vote for itself, which inflates scores for exactly the accounts you are trying to rank fairly.
  • Only prospects make the list. became_opportunity == 0 keeps accounts sales has not touched. A high score for one of them means "this company looks like the ones that bought, and nobody is talking to it yet", which is the whole point of a lookalike list.

The score reads as a share of neighbours: 0.483 means 58 of this account's 120 closest matches bought. It is a ranking signal, not a promise. Against a 7.3 percent average, though, these are the accounts to call first. Use the score to rank rather than as a probability: in the top tenth, accounts scored 23 percent on average and 31 percent actually bought (the calibration check explains why).

Finally, the whole audience on one picture. The map uses t-SNE, a method that squeezes the 14 columns into two while keeping similar accounts near each other. The axes have no units, only closeness means something. Customers gather in a few regions, the pipeline sits around them, and the 200-account list lands in and next to those regions, among prospects nobody is working yet. Switch to colouring by score to see the gradient.

The whole audience on one map
Try it
Hover any dot. The axes have no units: only closeness means something.
t-SNE places similar accounts near each other. Customers, the pipeline and the lookalike list are shown in full; other prospects are a 45% sample.

Step 11: how does KNN compare?

A fair guide should tell you how the method does against the alternatives, including the simple rules a team would use without any model:

logit = make_pipeline(prep, LogisticRegression(max_iter=1000)).fit(X_train, y_train)
 
def top_decile_rate(score):
    order = pd.DataFrame({"score": score, "customer": y_test.values})
    order = order.sort_values("score", ascending=False, kind="stable")
    return order["customer"].head(len(order) // 10).mean()
 
rankings = {
    "Most recent visit first": -X_test["days_since_last_visit"],
    "Most pricing page visits first": X_test["pricing_page_visits_90d"],
    "KNN lookalike score": test_scores,
    "Logistic regression": logit.predict_proba(X_test)[:, 1],
}
pd.DataFrame({
    "top_10pct_customer_rate": {n: round(top_decile_rate(s), 3) for n, s in rankings.items()},
    "auc": {n: round(roc_auc_score(y_test, s), 3) for n, s in rankings.items()},
})
                                top_10pct_customer_rate    auc
Most recent visit first                           0.193  0.740
Most pricing page visits first                    0.267  0.719
KNN lookalike score                               0.287  0.840
Logistic regression                               0.293  0.859

Each ranking is judged on the same 1,500 unseen accounts. Recency is negated so that the most recent visits come first. The two simple rules are the comparison from the application section at the top of this guide.

Logistic regression, the subject of part 3 of this series, ranks slightly better than KNN on the same data. That is common: KNN is rarely the most accurate method. You choose it for other reasons:

  • It explains each score with real accounts, as in step 9.
  • It makes no assumption about the shape of the relationship. If buyers cluster in a few distinct pockets, such as small agencies and large manufacturers, KNN finds both without being told.
  • It adapts at once. Add last month's new customers to the table and the next scores use them, with no retraining.

Using the list

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

  • Sales priority. Hand the top 200 to the sales team, with the five closest matches for each account, so the first call can reference what similar companies cared about.
  • Account-based marketing. Put the top-scoring accounts into a tailored campaign, and leave the bottom four deciles out of paid programmes altogether.
  • Ad audiences. Upload the list to an ad platform as a matched audience. Uploads use hashed contact details, and they are only appropriate for contacts who have agreed to that use. Check your consent records and your privacy policy against Canadian privacy law before uploading anything.
  • Refresh monthly. Engagement changes quickly. Re-score each month so the list reflects what accounts are doing now.

Then measure it properly. The lift chart shows that high scorers convert more often. It does not show that contacting them caused extra sales, because they were more likely to buy anyway. To measure what the outreach added, hold back a random part of the list, contact the rest, and compare. That is an incrementality test, explained in Incrementality Meaning, With a Marketing Example.

Mistakes to avoid

  • Skipping scaling. The single biggest cause of a bad KNN model. Always scale inside the pipeline.
  • Throwing in every column. Each irrelevant column dilutes every distance. Start with the few that plausibly relate to buying, and test whether each addition helps.
  • Leaky columns. Anything recorded after the outcome, such as plan type, opportunity stage or contract value, has no place in a model meant to find new buyers.
  • Using a small k with a rare outcome. With 7 percent customers, five neighbours give a lumpy, unstable score. Let cross-validation choose.
  • Expecting it to scale for free. Every score compares one account with every stored account. That is fine for thousands of rows and slow for millions; at that size, use an approximate nearest-neighbour library or a different method.
  • Confusing resemblance with cause. "Looks like our customers" is a reason to prioritise an account, not proof that contacting it will change anything. Test before you scale spend.
  • A stale seed. If your best customers today are different from the ones three years ago, a list built on all of them chases the old market. Weight or filter the history to the customers you want more of.

KNN and the rest of the series

For when KNN is the right choice and when it is not, see How KNN Works.

MethodWhat it gives youStrengthWatch out for
KNN (this case)A score from similar accountsExplains itself with real examplesScaling, slow at large scale
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. The last step writes your own lookalike_shortlist.csv.

Want this on your own data?

If you would like a lookalike list built from your own CRM and website 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.