KNN for Marketing: Find Junk Leads Before Sales Does, Step by Step
Use k-nearest neighbours to spot bot and spam form fills: a review queue in Python, tested on new leads, with code, data and charts.
This is a business case for k-nearest neighbours (KNN) used without any labels: we measure how far each demo request sits from the requests most like it, and send the oddest ones to a person for review. In 4,000 requests to a made-up software company, a review queue of 120 built this way holds 88 of the 120 junk leads without using any labels, and 106 once the number of neighbours is chosen with review results. On the 500 most recent leads, which play no part in that choice, it flags 12, and all 12 are junk.
KNN usually scores something by letting its nearest neighbours vote. Here there is nothing to vote on, because nobody has marked which leads are junk yet, so the distance itself becomes the score. This guide focuses on the business problem and the build. For the math behind distance, scaling and choosing k, 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: which leads sales ops checks first
Northpine Software, the made-up company whose data we use throughout this series, gets its sales conversations from a demo request form. Over the last quarter, 4,000 requests came in. Most were real people. Some were not: bots that fill in every form they find, and spam that uses the message box to advertise something.
Junk leads cost more than they look:
- Sales time. Every junk lead routed to a sales development rep is a call, an email sequence and a disqualification that someone has to do by hand.
- Lead scoring. Junk leads that sit in the CRM as "unqualified" teach any scoring model that certain behaviour means "will not buy", when it really means "is not a person".
- Ad platforms. If form fills are sent back to an ad platform as conversions, the platform learns to find more of whatever filled the form. Bots included.
- Reporting. Cost per lead looks better than it is, and the lead-to-opportunity rate looks worse.
Sales operations can check about 120 requests by hand in the time they have. The question: which 120?
What teams usually do
Without a model, teams write rules, each one aimed at junk they have already seen:
- Too fast to be human. Block or flag forms filled in under a few seconds.
- Too many from one place. Flag several submissions from the same IP address in a day.
- Links in the message. Real buyers rarely paste links into a demo request; spammers almost always do.
Rules are a good start. They are easy to explain and they catch the junk they were written for. Their weakness is that each one looks at one column, so each one catches one kind of junk and lets the others through, and a real person who happens to trip a rule gets flagged anyway.
What KNN changes
KNN looks at all the columns at once and asks one question of every lead: how far is it from the leads most like it? Real requests resemble many other real requests. Junk does not resemble them, so it sits apart. Sort by that distance and you have a review queue. On the same 4,000 leads (step 10 shows the code):
| How leads are flagged | Leads flagged | Junk caught (of 120) | Precision | Recall |
|---|---|---|---|---|
| Form filled in under 5 seconds | 297 | 60 | 20.2% | 50.0% |
| 3 or more submissions from one IP | 86 | 84 | 97.7% | 70.0% |
| Link in the message | 164 | 60 | 36.6% | 50.0% |
| Any of the three | 456 | 118 | 25.9% | 98.3% |
| KNN oddness, top 120 | 120 | 106 | 88.3% | 88.3% |
Precision is the share of flagged leads that are junk. Recall is the share of all junk that gets flagged. Read the table as a sales ops manager would:
- The IP rule is excellent at what it does. 84 of the 86 leads it flags are junk. Keep it. But it only sees bots that submit again and again, so it misses 36 junk leads.
- Combining the rules catches nearly everything, at a price. It finds 118 of the 120 junk leads, but flags 456 leads to do it, so 338 real people land in the review pile or, worse, get blocked.
- KNN gives one ranked list of the right size. Its 120 leads hold 106 junk leads, more than any single rule finds, in a queue a person can actually work through. That uses the number of neighbours chosen in step 9; step 11 checks the choice on new leads.
What the team receives
A weekly list of the leads to check before they reach sales, oddest first. The top of the queue built in step 9:
| Lead | Seconds on the form | Message length | Link in message | Submissions, same IP | Oddness |
|---|---|---|---|---|---|
| NL-03532 | 3.8 | 40 | yes | 13 | 6.257 |
| NL-03670 | 2.4 | 0 | no | 14 | 6.023 |
| NL-00327 | 1.1 | 0 | no | 13 | 6.020 |
| NL-02039 | 2.5 | 40 | yes | 11 | 6.000 |
| NL-02683 | 4.3 | 40 | yes | 11 | 5.984 |
And how each team uses it:
| Team | Decision | What they do with the queue |
|---|---|---|
| Sales operations | Which leads to check by hand | Review the queue before routing, and mark each lead junk or real |
| Sales development | Who to call | Work only leads that passed the check, so no time goes on bots |
| Paid media | Which conversions to report back | Hold flagged leads out of conversion uploads until they are confirmed real |
| Marketing operations | Whether the form needs changing | Watch which kinds of junk keep appearing, and add a rule or a challenge for them |
Other places the same idea works
Measuring how far something sits from its nearest neighbours is a general way to find what does not fit:
- Invalid traffic on paid campaigns. Sessions that look like no other sessions: no scrolling, one page, very short, many from one network.
- Trial and sign-up abuse. Accounts created in bulk to reuse a free trial tend to look like each other and unlike real sign-ups.
- Data-entry errors in a CRM. A company with 40 employees and a billion dollars in revenue sits far from every real company.
- Survey quality. Respondents who rush through or answer in a straight line stand apart from considered answers.
KNN in one minute
The usual KNN takes a new record, finds the k known records closest to it, and lets them vote. This case uses only the first half. For every lead, find its k nearest other leads across all the columns at once, and take the average distance to them:
Here is one lead, is its -th nearest other lead, and is the straight-line distance between them after scaling (the distance section of How KNN Works explains it). A real request sits in a crowd of similar requests, so its neighbours are close and its oddness is low. A bot that fills the form in two seconds, sends no message and submits thirteen times is far from everyone, so its oddness is high.
Two consequences shape the build below. Columns must be on comparable scales, or one column decides every distance (why scaling matters). And k matters in a way it does not in the usual KNN: if junk comes in a crowd of similar leads, and k is smaller than the crowd, the junk leads are each other's nearest neighbours and look perfectly normal. Step 8 shows that happening.
Try it on 600 of Northpine's leads, drawn on two of the seven columns:
Three things to try:
- Hide the answer. Switch off "what sales ops found" and look at the rings only. That is all the model sees: the big rings are the leads far from their neighbours.
- Set k to 5, then to 60, and watch the cluster of long spam messages at the top. With a small k, each spam message finds other spam close by, so its ring stays small, and the queue catches fewer junk leads. With a large k, the neighbourhood has to reach out to real leads, the rings grow, and the spam joins the queue.
- Hover a lead in a crowd and one on its own. The lines show its neighbours. In the crowd they are short; on its own they stretch across the chart.
The data: Northpine's demo requests
This guide uses one table, northpine_leads.csv: 4,000 demo requests from the last quarter, with what the website recorded about each one. Here are the first five rows:
| lead_id | seconds on site | pages viewed | seconds on form | message length | link | free email | same IP, 24h |
|---|---|---|---|---|---|---|---|
| NL-00001 | 86 | 5 | 24.5 | 178 | 0 | 0 | 1 |
| NL-00002 | 384 | 8 | 35.7 | 60 | 0 | 0 | 1 |
| NL-00003 | 124 | 3 | 4.4 | 101 | 1 | 1 | 1 |
| NL-00004 | 320 | 4 | 5.8 | 78 | 0 | 1 | 1 |
| NL-00005 | 97 | 5 | 64.6 | 123 | 0 | 0 | 1 |
And what every column means:
| Column | What it is | Range |
|---|---|---|
seconds_on_site | Time on the website before submitting | 2 to 2,216 |
pages_viewed | Pages viewed in that visit | 1 to 15 |
form_fill_seconds | Time from first keystroke to submit | 1.1 to 182.7 |
message_chars | Length of the message box, in characters | 0 to 1,729 |
links_in_message | The message contains a link (1) or not (0) | 0 or 1 |
free_email_domain | A free email address rather than a company one | 0 or 1 |
submissions_same_ip_24h | Requests from the same IP address within a day | 1 to 14 |
is_junk | What sales ops found when they reviewed the lead | 0 or 1 |
Two things to notice before writing any code.
Junk is rare. 120 of the 4,000 requests are junk, 3.0 percent. A random queue of 120 would hold three or four of them.
is_junk is the answer, not an input. In real life you do not have it when a lead arrives; that is the whole problem. Northpine's sales ops reviewed this quarter's leads, so we have it here, and we use it for one thing only: to check how well the queue does. The model never sees it. The same goes for anything filled in after review, such as a disqualification reason: it would make the model look brilliant in testing and useless on Monday morning.
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.metrics import roc_auc_score
from sklearn.neighbors import LocalOutlierFactor, NearestNeighbors
from sklearn.preprocessing import StandardScaler
leads = pd.read_csv("northpine_leads.csv")
print(leads.shape)
leads.head()(4000, 9)Four thousand requests, nine columns: an ID, seven things the website recorded, and the review result.
Step 2: set the answer aside
answer = leads.pop("is_junk") # found on review by sales ops; the model never sees it
print(f"{answer.sum()} junk leads out of {len(leads):,} ({answer.mean():.1%})")120 junk leads out of 4,000 (3.0%)pop removes the column from the table and keeps it in a separate variable, so nothing below can use it by accident.
Step 3: look at the columns
columns = ["seconds_on_site", "pages_viewed", "form_fill_seconds", "message_chars",
"links_in_message", "free_email_domain", "submissions_same_ip_24h"]
leads[columns].describe().round(1).T[["mean", "50%", "min", "max"]] mean 50% min max
seconds_on_site 248.6 194.0 2.0 2216.0
pages_viewed 5.4 5.0 1.0 15.0
form_fill_seconds 37.6 35.6 1.1 182.7
message_chars 105.9 75.5 0.0 1729.0
links_in_message 0.0 0.0 0.0 1.0
free_email_domain 0.1 0.0 0.0 1.0
submissions_same_ip_24h 1.2 1.0 1.0 14.0The 50% column is the median, the middle lead. Look at the gap between it and the maximum. The typical lead spent 194 seconds on the site; one spent 2,216. The typical message is 75.5 characters; one is 1,729. Columns like these are called skewed: most values are small and a few are very large. Left as they are, the few very large values would dominate every distance.
Step 4: put the columns on one scale
X = leads[columns].astype(float)
skewed = ["seconds_on_site", "form_fill_seconds", "message_chars", "submissions_same_ip_24h"]
X[skewed] = np.log1p(X[skewed]) # 10 -> 2.4, 100 -> 4.6, 1,000 -> 6.9
Z = StandardScaler().fit_transform(X)
print(Z.shape, Z.mean(axis=0).round(2), Z.std(axis=0).round(2))(4000, 7) [ 0. 0. 0. 0. 0. -0. -0.] [1. 1. 1. 1. 1. 1. 1.]Two transformations, each with a reason:
- The logarithm (
log1pis the log of one plus the value, so zero stays zero) turns multiplication into addition. The step from 2 to 20 seconds counts the same as the step from 20 to 200. That matches how we think about form-fill time: two seconds against twenty is a big difference, 120 against 138 is not. StandardScalerturns each column into standard deviations from its average, so every column has an average of 0 and a spread of 1, as the output confirms. Without it, message length, which runs to the thousands, would outweigh whether a message contains a link.
The model does not learn from the answer, so steps 5 to 8 need no train and test split. Step 9 is different: it uses the answer to choose k, and a setting chosen by looking at the answer can flatter the result. So step 9 chooses k on the first 3,500 leads only, and step 11 checks that choice on the last 500, which play no part in it.
Step 5: score every lead
k = 20
distance, index = NearestNeighbors(n_neighbors=k + 1).fit(Z).kneighbors(Z) # each lead's first neighbour is itself, at distance 0
leads["oddness"] = distance[:, 1:].mean(axis=1).round(3)
leads["oddness"].describe(percentiles=[0.5, 0.9, 0.97, 0.99]).round(2)count 4000.00
mean 0.73
std 0.50
min 0.28
50% 0.58
90% 1.18
97% 2.16
99% 3.07
max 4.29
Name: oddness, dtype: float64NearestNeighbors finds, for every lead, the 21 closest leads in the table. The closest is always the lead itself, so [:, 1:] drops it and keeps the other 20. Oddness is the average distance to them. We start with k = 20, a common starting point; step 9 comes back to it.
The typical lead is 0.58 from its neighbours. The oddest 3 percent are more than 2.16 away, and the oddest lead of all is 4.29 away, more than seven times the typical distance.
Step 6: build the review queue
budget = 120
queue = leads.sort_values("oddness", ascending=False, kind="stable").head(budget)
found = answer[queue.index].sum()
print(f"junk in the queue: {found} of {budget} (precision {found / budget:.1%})")
print(f"share of all junk caught: {found / answer.sum():.1%} (recall)")
print(f"AUC over all {len(leads):,} leads: {roc_auc_score(answer, leads['oddness']):.3f}")junk in the queue: 88 of 120 (precision 73.3%)
share of all junk caught: 73.3% (recall)
AUC over all 4,000 leads: 0.991This is the first time we use the answer, and only to grade the queue. Precision and recall are the same number here because the queue happens to be the same size as the amount of junk. AUC, the area under the ROC curve, measures how well the score orders the whole list: 0.991 means a random junk lead scores higher than a random real lead 99.1 percent of the time (how AUC works). kind="stable" keeps leads with equal scores in their original order, so the queue is the same every time you run it.
88 junk leads in a queue of 120, against three or four in a random queue, with no labels at all. A good start, with 32 junk leads missing.
Step 7: look inside the queue
queue[["lead_id"] + columns + ["oddness"]].head(6)| lead_id | seconds on site | pages | seconds on form | message | link | free email | same IP | oddness |
|---|---|---|---|---|---|---|---|---|
| NL-03532 | 14 | 2 | 3.8 | 40 | 1 | 1 | 13 | 4.286 |
| NL-00622 | 7 | 2 | 2.1 | 0 | 0 | 1 | 2 | 4.231 |
| NL-02683 | 9 | 1 | 4.3 | 40 | 1 | 1 | 11 | 4.026 |
| NL-02039 | 10 | 1 | 2.5 | 40 | 1 | 1 | 11 | 4.012 |
| NL-01421 | 3 | 1 | 2.4 | 12 | 0 | 1 | 2 | 3.984 |
| NL-02788 | 8 | 2 | 3.5 | 0 | 0 | 0 | 3 | 3.970 |
Every one of these is a bot by any human standard: seconds on the site, one or two pages, a form filled in under five seconds, a short or empty message, and more than one request from the same IP address. To see why the model picked one, compare it with the typical lead:
def explain(lead_id):
i = leads.index[leads["lead_id"] == lead_id][0]
return pd.DataFrame({
"this lead": leads.loc[i, columns],
"typical lead": leads[columns].median(),
"its neighbours": leads.loc[index[i, 1:], columns].median(),
"z_score": Z[i].round(1),
})
explain(queue["lead_id"].iloc[0]) this lead typical lead its neighbours z_score
seconds_on_site 14 194.0 13.00 -3.2
pages_viewed 2 5.0 1.00 -1.6
form_fill_seconds 3.8 35.6 2.65 -2.1
message_chars 40 75.5 40.00 -0.5
links_in_message 1 0.0 0.00 4.8
free_email_domain 1 0.0 1.00 2.5
submissions_same_ip_24h 13 1.0 10.50 8.6The z-score is how many standard deviations the lead sits from the average on each column, after the log in step 4. Five of the seven columns are more than two standard deviations out, and submissions from the same IP are 8.6 out. No single rule would describe this lead; together, the columns put it far from every real request. The "its neighbours" column shows a detail worth noticing: its 20 nearest leads are other bots. The bots form a loose group of their own, and that whole group sits far from every real request.
Being able to show this matters. A sales ops person will trust a queue faster if every entry comes with "this is why it looks odd" in plain columns they recognize.
Step 8: what the queue gets wrong
A queue has two kinds of mistakes: real leads that are in it, and junk that is not.
false_alarms = queue[answer[queue.index] == 0]
print(f"{len(false_alarms)} real leads in the queue")
false_alarms[["lead_id"] + columns + ["oddness"]].head(6)32 real leads in the queue| lead_id | seconds on site | pages | seconds on form | message | link | free email | same IP | oddness |
|---|---|---|---|---|---|---|---|---|
| NL-02571 | 998 | 6 | 49.0 | 14 | 1 | 1 | 1 | 3.295 |
| NL-01259 | 36 | 6 | 73.1 | 5 | 1 | 0 | 2 | 3.223 |
| NL-00219 | 275 | 4 | 67.6 | 1 | 1 | 0 | 1 | 3.152 |
| NL-00202 | 36 | 5 | 9.0 | 47 | 1 | 1 | 1 | 3.108 |
| NL-03362 | 373 | 15 | 14.2 | 3 | 0 | 0 | 1 | 3.064 |
| NL-02502 | 369 | 5 | 75.5 | 102 | 1 | 1 | 2 | 3.032 |
These are real people who did something unusual: pasted a link with almost no message, viewed 15 pages, spent a long time on the site. That is the honest limit of this method. Unusual is not the same as junk. A large prospect with a long, detailed request can look as odd as a bot. That is why the output is a review queue for a person, and not a filter that deletes leads.
Now the junk that got away:
missed = leads[(answer == 1) & ~leads.index.isin(queue.index)]
print(f"{len(missed)} junk leads not in the queue")
long_spam = (answer == 1) & (leads["message_chars"] > 500)
print(f"junk leads with a message over 500 characters: {long_spam.sum()}, "
f"of which in the queue: {long_spam[queue.index].sum()}")
pd.DataFrame({"caught": queue.loc[answer[queue.index] == 1, columns].median(),
"missed": missed[columns].median(),
"real leads": leads.loc[answer == 0, columns].median()})32 junk leads not in the queue
junk leads with a message over 500 characters: 49, of which in the queue: 18
caught missed real leads
seconds_on_site 14.5 67.5 198.0
pages_viewed 1.0 2.0 5.0
form_fill_seconds 3.9 15.1 36.2
message_chars 40.0 1010.0 75.0
links_in_message 0.0 1.0 0.0
free_email_domain 0.0 1.0 0.0
submissions_same_ip_24h 5.5 3.0 1.0The missed junk is a different kind: spam, with messages of about 1,010 characters, a link and a free email address. Northpine received 49 of these long spam messages and the queue caught only 18.
The reason is the one the section KNN in one minute warned about. Spam arrives in a crowd. Each spam message looks a lot like the other spam messages, so with k = 20 its 20 nearest neighbours are mostly other spam, close by. Measured against its own crowd, a spam message looks normal. The bots got caught because the bots' group sits far from the real leads.
Step 9: choose k
How many neighbours should each lead be compared with? There is no vote to score with cross-validation here, so we do two things: look at how much the queue changes as k changes, which needs no labels, and check it against the review results, which Northpine happens to have.
Checking against the review results means looking at the answer, and a k chosen by looking at the answer will flatter any result measured on the same leads. So the check uses the first 3,500 leads only, with its own scaler and a queue of the same 3 percent. The last 500 leads stay out of it, for step 11.
tune = X.iloc[:3500] # choose k on the first 3,500 leads; step 11 tests it on the last 500
Z_tune = StandardScaler().fit_transform(tune)
budget_tune = round(budget * len(tune) / len(leads)) # the same 3 percent: 105 leads
print(f"{answer[tune.index].sum()} junk leads in the first {len(tune):,}, queue of {budget_tune}")
check, tops = [], {}
for k_ in [1, 2, 5, 10, 20, 40, 80, 160]:
d, _ = NearestNeighbors(n_neighbors=k_ + 1).fit(Z_tune).kneighbors(Z_tune)
score = pd.Series(d[:, 1:].mean(axis=1), index=tune.index)
tops[k_] = score.sort_values(ascending=False, kind="stable").head(budget_tune).index
check.append({"k": k_, "junk_in_queue": int(answer[tops[k_]].sum()),
"auc": round(roc_auc_score(answer[tune.index], score), 3)})
check = pd.DataFrame(check).set_index("k")
check.insert(0, "same_as_k20", [len(tops[k_].intersection(tops[20])) for k_ in check.index])
check106 junk leads in the first 3,500, queue of 105
same_as_k20 junk_in_queue auc
k
1 75 55 0.935
2 75 55 0.969
5 83 63 0.983
10 99 73 0.990
20 105 78 0.994
40 97 86 0.998
80 86 92 0.999
160 80 94 0.998What the table says:
- Small k misses crowds. With one neighbour, a bot that has a single twin looks perfectly normal, and the queue holds 55 of the 106 junk leads.
- The jump comes when k passes the size of the spam crowd. At k = 40 the queue holds 86 junk leads; at k = 80, 92. The full table has 49 long spam messages, and k = 80 forces each one to look beyond its own crowd, to real leads far away.
- After that, the gains are small. k = 160 adds two more, and its AUC is slightly lower. A smaller k keeps the score about the lead's own surroundings, so we use 80.
- The local outlier factor does badly here. The indigo line in the chart is LocalOutlierFactor, a popular method that compares each lead's crowding with its neighbours' crowding. A tight crowd of bots is as crowded as its neighbours, so it looks normal. At k = 80 it catches 52 of these 106 junk leads. Simple distance suits this job better.
The same_as_k20 column is the part you can always compute, even without labels. Between k = 10 and k = 40 the queue barely changes; at k = 80, 86 of its 105 leads were already in the k = 20 queue. In practice, you set k from what you know about your junk (bots and spam often arrive in bursts of dozens), then check it against a few weeks of review results.
Now score all 4,000 leads again with k = 80:
k = 80
distance, index = NearestNeighbors(n_neighbors=k + 1).fit(Z).kneighbors(Z)
leads["oddness"] = distance[:, 1:].mean(axis=1).round(3)
queue = leads.sort_values("oddness", ascending=False, kind="stable").head(budget)
found = answer[queue.index].sum()
print(f"k = {k}: junk in the queue: {found} of {budget}, AUC {roc_auc_score(answer, leads['oddness']):.3f}")
queue[["lead_id", "form_fill_seconds", "message_chars", "links_in_message",
"submissions_same_ip_24h", "oddness"]].head(5)k = 80: junk in the queue: 106 of 120, AUC 0.999The queue now holds 106 of the 120 junk leads, with 14 real leads in it. Read that number with care: k was chosen with the review results for 3,500 of these 4,000 leads, so it is not a clean test. The two honest numbers are 88 at k = 20 in step 6, which used no labels at all, and step 11, which checks k = 80 on the 500 leads that played no part in choosing it.
The five leads at the top are the table from the application section. The chart below shows how junk piles up as sales ops works down the list: slide the review budget to see the trade-off. Two numbers from the ranking:
ranked = answer[leads.sort_values("oddness", ascending=False, kind="stable").index].to_numpy()
reviews_for_all = int(np.argmax(ranked.cumsum() == answer.sum())) + 1
print(f"junk leads in a row at the top of the queue: {int(np.argmin(ranked))}")
print(f"leads to review to find all {answer.sum()} junk leads: {reviews_for_all}, "
f"of which real: {reviews_for_all - answer.sum()}")junk leads in a row at the top of the queue: 66
leads to review to find all 120 junk leads: 196, of which real: 76The first 66 leads in the queue are all junk. Reviewing 196 finds every one of the 120, at the cost of checking 76 real leads along the way.
And why three leads in this queue were flagged: a bot, a spam message, and a real person who looked odd.
The real lead, NL-00219, was flagged for one thing: a link in a one-character message, a combination almost no real request has. Its neighbours share the link, but not the empty message. A reviewer sees in seconds that the rest of the visit was ordinary: 275 seconds on the site, four pages, more than a minute on the form.
Step 10: compare with the rules
A fair guide should compare the method with what a team would do without it, and with the obvious alternative:
rules = {
"Form filled in under 5 seconds": leads["form_fill_seconds"] < 5,
"3 or more submissions from one IP": leads["submissions_same_ip_24h"] >= 3,
"Link in the message": leads["links_in_message"] == 1,
}
rules["Any of the three"] = pd.concat(rules.values(), axis=1).any(axis=1)
rules[f"KNN oddness, top {budget}"] = leads.index.isin(queue.index)
lof = LocalOutlierFactor(n_neighbors=k).fit(Z)
lof_score = pd.Series(-lof.negative_outlier_factor_, index=leads.index)
rules[f"Local outlier factor, top {budget}"] = leads.index.isin(
lof_score.sort_values(ascending=False, kind="stable").head(budget).index)
ip_first = leads.assign(ip=rules["3 or more submissions from one IP"]).sort_values(
["ip", "oddness"], ascending=False, kind="stable")
rules[f"IP rule, then KNN, top {budget}"] = leads.index.isin(ip_first.head(budget).index)
comparison = pd.DataFrame([
{"rule": name, "flagged": int(flag.sum()), "junk_caught": int(answer[flag].sum()),
"precision": round(answer[flag].mean(), 3), "recall": round(answer[flag].sum() / answer.sum(), 3)}
for name, flag in rules.items()
]).set_index("rule")
comparison flagged junk_caught precision recall
rule
Form filled in under 5 seconds 297 60 0.202 0.500
3 or more submissions from one IP 86 84 0.977 0.700
Link in the message 164 60 0.366 0.500
Any of the three 456 118 0.259 0.983
KNN oddness, top 120 120 106 0.883 0.883
Local outlier factor, top 120 120 47 0.392 0.392
IP rule, then KNN, top 120 120 105 0.875 0.875Three findings:
- The speed rule is the weakest. It flags 297 leads and only 60 are junk. The other 237 are real people who finished the form in under five seconds, the speed that browser autofill gives. Blocking fast forms would block real buyers.
- KNN does not beat the IP rule at the rule's own job. The IP rule's precision, 97.7 percent, is higher than anything else in the table. What KNN adds is the junk the rule cannot see.
- Putting the IP rule first does not help here. Filling the queue with the IP rule's 86 leads and then the oddest of the rest gives 105, one fewer than KNN alone, because KNN already ranks those repeat-submission bots at the top. Keep the rule anyway: it is instant, needs no model and explains itself.
Step 11: score new leads every week
The queue so far scored a quarter's leads against each other. Each week, new leads should be scored against the history, without the history being changed by them. This step is also the clean test of step 9: the history is the 3,500 leads k was chosen on, and the 500 most recent leads stand in for a new week. None of their review results were used to choose k.
history, new = X.iloc[:3500], X.iloc[3500:] # the leads k was chosen on, and the most recent 500
scaler = StandardScaler().fit(history)
nn_history = NearestNeighbors(n_neighbors=k + 1).fit(scaler.transform(history))
d, _ = nn_history.kneighbors(scaler.transform(history))
cutoff = np.quantile(d[:, 1:].mean(axis=1), 0.97) # odder than 97% of last quarter's leads
d, _ = nn_history.kneighbors(scaler.transform(new), n_neighbors=k) # new leads are not in the history
flagged = new.index[d.mean(axis=1) > cutoff]
print(f"cut-off: {cutoff:.2f}")
print(f"this week: {len(flagged)} of {len(new)} leads flagged, {answer[flagged].sum()} of them junk")
print(f"junk this week: {answer[new.index].sum()}")
leads.loc[flagged, ["lead_id"]].assign(flag="review").to_csv("junk_review_queue.csv", index=False)cut-off: 3.50
this week: 12 of 500 leads flagged, 12 of them junk
junk this week: 14Three details make this safe to run every week:
- The scaler and the neighbours are fitted on the history only. New leads are measured with the same ruler every time, and a sudden flood of bots this week cannot redefine what normal looks like.
- A new lead is compared with history, not with itself. For history leads, the first neighbour is the lead itself and is dropped. New leads are not in the history, so all k neighbours count.
- The cut-off is fixed in advance. Any new lead odder than 97 percent of last quarter's leads goes to review. 3 percent matches the 120 out of 4,000 that sales ops could check.
Of the 500 most recent leads, 12 crossed the line and all 12 were junk. These leads played no part in choosing k, so this is the fairest result in the guide, if a small one. Two junk leads got through, which is the reason for the audit sample described in the next section.
Using the queue
A queue only helps if it fits into how leads move:
- Check before routing. Score each new request as it arrives and hold the flagged ones for review before they reach sales. Unflagged leads flow on as normal, so real buyers are not delayed.
- Review, do not delete. The model ranks; a person decides. Step 8 showed real people in the queue, and a real enterprise buyer is exactly the kind of lead that can look unusual.
- Keep the rules. The IP rule and a link check are instant and clear. Use them alongside the queue, not instead of it.
- Save every review decision. Each week of "junk" and "real" marks is a set of labels. After a few months there are enough to tune k properly, and to train a supervised model that learns what junk looks like, such as logistic regression, the subject of part 3 of this series.
- Refresh the history monthly. Fit the scaler and neighbours on the last quarter, and leave confirmed junk out of the history so that "normal" means real leads.
- Handle IP addresses with care. Under Canadian privacy law an IP address can be personal information. Count submissions per address without storing the address longer than you need, and say so in your privacy policy.
Then measure it properly. The queue's misses are invisible by design: junk that is not flagged reaches sales and looks like any other bad lead. To estimate them, have sales ops check a small random sample of unflagged leads each week. The share of junk in that sample, times the number of unflagged leads, estimates how much gets through. Track that number and the share of the queue that turns out to be junk, and you know both sides of the trade-off. The same idea of a random holdout is what makes incrementality measurable.
Mistakes to avoid
- Skipping the log. Raw seconds and characters let one long message or one long visit decide every distance, and the queue fills with real people who wrote a lot.
- A k smaller than the junk crowd. Bots and spam arrive in bursts of near-identical requests. If k is smaller than the burst, they vouch for each other and look normal. At k = 20 this queue missed 31 of the 49 long spam messages.
- Letting the model block leads. Oddness is about being different, not about being fake. Blocked real buyers never complain; they just go elsewhere.
- Reading oddness as a probability. An oddness of 6 does not mean "60 percent junk". It is a distance, useful for ranking and for a cut-off, nothing more.
- Letting this week's junk define normal. If new leads are added to the history before they are scored, a large bot attack becomes its own crowd and looks normal. Score against a fixed history.
- Tuning only on what reviewers flagged. Review results only cover the leads that were reviewed. Without a random audit of unflagged leads, a model can look perfect while junk slips past.
KNN and the rest of the series
For when KNN is the right choice in general, see How KNN Works. For finding junk specifically:
| Method | Needs labelled junk? | What it gives you | Watch out for |
|---|---|---|---|
| KNN distance (this case) | No | A ranked review queue on day one | Crowds of junk, unusual real buyers |
| Logistic regression | Yes | A probability that a lead is junk, with a weight per column | Only finds the kinds of junk it was shown |
| Decision tree | Yes | Rules a person can read, such as "under 5 seconds and same IP" | Unstable, overfits if allowed |
| XGBoost | Yes | Usually the most accurate once labels exist | Needs extra tools to explain |
| Linear regression | Not suited | Predicts amounts, not yes or no | Wrong tool for this job |
The usual path is the order of this table: start with KNN distance because you have no labels, collect labels from the review queue, then move to a supervised model and keep the distance score for new kinds of junk it has never seen.
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 11 writes your own junk_review_queue.csv.
Want this on your own data?
If junk leads are wasting your sales team's time or muddying your reporting, and you would like a review queue built on your own form data, get in touch and we can talk it through on a short call.