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.
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 sorted | Customer rate in the top 10% | How well it orders the whole list (AUC) |
|---|---|---|
| Most recent visit first | 19.3% | 0.740 |
| Most pricing page visits first | 26.7% | 0.719 |
| KNN lookalike score | 28.7% | 0.840 |
| Average account, unsorted | 7.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:
| Account | Industry | Employees | Pricing page visits | Webinar | Lookalike score |
|---|---|---|---|---|---|
| NP-01617 | Professional services | 89 | 7 | yes | 0.483 |
| NP-02540 | Software | 172 | 5 | yes | 0.450 |
| NP-01445 | Professional services | 152 | 5 | yes | 0.425 |
And how each team uses it:
| Team | Decision | What they do with the list |
|---|---|---|
| Sales development | Who to call this month | Work the top 200, opening with what similar companies cared about |
| Account-based marketing | Who gets a tailored campaign | Take the top of the list as the target account list |
| Paid media | Who sees the ads | Upload the top scorers as a matched audience, and leave the bottom of the list out |
| Marketing operations | Where not to spend | Suppress 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
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.
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_id | industry | employees | web visits | pricing page visits | webinar | became customer |
|---|---|---|---|---|---|---|
| NP-00001 | Professional services | 41 | 9 | 0 | 0 | 0 |
| NP-00002 | Healthcare | 12 | 3 | 1 | 0 | 0 |
| NP-00003 | Software | 146 | 11 | 4 | 0 | 1 |
| NP-00004 | Software | 36 | 3 | 0 | 0 | 0 |
| NP-00005 | Professional services | 52 | 1 | 1 | 0 | 0 |
And what every column means:
| Column | What it is | Range |
|---|---|---|
industry | The company's sector | six sectors |
region | Province or region of Canada | six regions |
employees | Company headcount | 5 to 4,937, median 100 |
first_channel | How the company first found Northpine | six channels |
web_visits_90d | Website visits in the last 90 days | 0 to 32 |
pages_per_visit | Average pages viewed per visit | 1 to 6.6 |
content_downloads_90d | Guides and reports downloaded | 0 to 9 |
webinar_attended | Attended a webinar (1) or not (0) | 0 or 1 |
email_clicks_90d | Clicks on marketing emails | 0 to 13 |
pricing_page_visits_90d | Visits to the pricing page | 0 to 10 |
days_since_last_visit | Days since the last website visit | 0 to 180 |
became_opportunity | Sales opened a deal (1) or not (0) | 0 or 1 |
became_customer | The 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 366This 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_opportunityis 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.regionandfirst_channelare 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 customersWe 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:
StandardScalerputs each numeric column on the same scale (why that matters).OneHotEncoderturnsindustryinto 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.827Cross-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.
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.840On 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.000This 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.
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.
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_id | industry | employees | pricing page visits | downloads | webinar | became customer | distance |
|---|---|---|---|---|---|---|---|
| NP-02540 | Software | 172 | 5 | 5 | 1 | 0 | 3.96 |
| NP-02986 | Software | 178 | 5 | 2 | 1 | 1 | 4.21 |
| NP-01612 | Retail | 194 | 6 | 3 | 1 | 1 | 4.31 |
| NP-04097 | Manufacturing | 337 | 6 | 4 | 1 | 1 | 4.39 |
| NP-02027 | Software | 172 | 9 | 3 | 1 | 0 | 4.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_id | industry | employees | pricing page visits | webinar | lookalike score |
|---|---|---|---|---|---|
| NP-01617 | Professional services | 89 | 7 | 1 | 0.483 |
| NP-02540 | Software | 172 | 5 | 1 | 0.450 |
| NP-01445 | Professional services | 152 | 5 | 1 | 0.425 |
| NP-01264 | Healthcare | 116 | 4 | 1 | 0.400 |
| NP-00957 | Software | 161 | 3 | 1 | 0.358 |
| NP-02350 | Professional services | 613 | 1 | 1 | 0.358 |
| NP-03158 | Education | 46 | 5 | 1 | 0.350 |
| NP-01047 | Manufacturing | 58 | 5 | 1 | 0.342 |
| NP-02583 | Software | 439 | 3 | 0 | 0.333 |
| NP-03251 | Software | 68 | 4 | 0 | 0.333 |
Two details in that code are easy to get wrong:
cross_val_predictscores 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 == 0keeps 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.
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.859Each 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.
| Method | What it gives you | Strength | Watch out for |
|---|---|---|---|
| KNN (this case) | A score from similar accounts | Explains itself with real examples | Scaling, slow at large scale |
| Linear regression | How much one number moves another | Simple, readable effects | Mistaking correlation for cause |
| Logistic regression | A probability for a yes or no outcome | Accurate, clear weights per column | Straight-line assumptions |
| Decision tree | Rules that split customers into groups | Rules anyone can read | Unstable, overfits if allowed |
| XGBoost | Strong predictions from many trees | Usually the most accurate | Needs 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.