How KNN Works: The Math and Intuition, Explained for Marketers
K-nearest neighbours explained for marketers: the distance math, scaling, choosing k, and how to judge the model, with interactive charts and Python.
K-nearest neighbours (KNN) scores something new by finding the known examples that look most like it and checking what happened to them. This guide explains how it works from the ground up: the idea, the math, how to tune it, how to judge it, and where it breaks.
The business cases that apply it are separate guides, so this one can focus on the model. The first is building a lookalike audience. Every example on this page comes from that case: an invented software company, Northpine, scoring 5,000 companies that visited its website by how much they resemble the ones that became customers. Every number and chart is real output from code you can download.
How KNN works
KNN is one of the few machine learning methods you can describe completely in one sentence: to score a new account, find the k known accounts most similar to it, and report the share of them that became customers.
There is no formula fitted to the data, no weights, and no training in the usual sense. The "model" is simply the table of known accounts. That has two consequences you will feel throughout this guide:
- Every score is explainable. A score of 30 percent means "of the 120 accounts most like this one, 36 became customers", and you can list them.
- Everything depends on what "similar" means. KNN has no way to learn that pricing page visits matter more than region. It treats every column you give it as equally important, in whatever units you give it. Most of the work in this guide goes into making "similar" mean something sensible.
The math behind KNN
KNN needs less math than almost any other method, which makes it a good place to see how a model turns data into a score. There are four pieces: describing an account as numbers, measuring distance, voting, and choosing . A fifth, AUC, is how we judge the result.
An account is a list of numbers
To a model, each account is a point described by a list of numbers called a vector:
Here is the number of columns. In the running example : eight numeric columns, plus six yes-or-no columns that stand for the six industries (a step called one-hot encoding, shown in step 5 of the business case). Each known account also has an outcome , which is 1 if it became a customer and 0 if it did not.
Distance
The distance between two accounts and is the straight-line, or Euclidean, distance:
In words: for each column, take the difference between the two accounts, square it, add up all the squares, and take the square root. With two columns this is the ruler distance on the map in the playground. With fourteen it is the same calculation in fourteen dimensions.
For the industry columns, two accounts in the same industry differ by 0 on all six. Two accounts in different industries differ by 1 on two of them, one for each industry, so industry adds to the distance.
Scaling
The formula adds up raw differences, so a column measured in hundreds overwhelms a column measured in single digits. Standard scaling fixes that by rescaling every column to "how unusual is this value":
where is the column's average and its standard deviation, both computed on the training accounts. After scaling, every column has an average of 0 and a standard deviation of 1, so a difference of 1 means the same thing on every column.
Headcount gets one more step first. The difference between 10 and 110 employees matters far more than the difference between 4,000 and 4,100, so we use , which turns 10, 100 and 1,000 into 1, 2 and 3.
A worked example
Take a prospect with 100 employees and 8 engagement actions (downloads, pricing page visits and webinars added together), and two known accounts:
| Account | Employees | Engagement actions | In plain words |
|---|---|---|---|
| Prospect P | 100 | 8 | Mid-sized and very engaged |
| Account B | 110 | 0 | Same size, no interest at all |
| Account C | 300 | 8 | Bigger, exactly as engaged |
A marketer would say C is the better match. On raw numbers the formula disagrees:
B comes out fifteen times closer, because 200 employees of difference swamps 8 engagement actions. Now scale. In the running example's data, the standard deviation of is 0.499 and of engagement is 1.917, and of 100, 110 and 300 is 2.000, 2.041 and 2.477:
Now C is more than four times closer, which matches common sense. (The averages cancel out when you subtract two scaled values, which is why only the standard deviations appear.) On the full lookalike model, scaling raises cross-validated AUC from 0.772 to 0.827.
The vote
Call the known accounts closest to its neighbourhood, . KNN's score is the share of that neighbourhood that became customers:
Because each is 0 or 1, the sum just counts the customers among the neighbours. For example, the top account on the lookalike list has 58 customers among its 120 nearest neighbours, so its score is .
A common variant gives closer neighbours a bigger say, weighting each vote by one over its distance:
In scikit-learn that is weights="distance". The examples here keep the plain vote, which is easier to explain to a sales team.
Does the weighting help? Not on this data. The chart compares the two rules at every , scored with five-fold cross-validation on the training accounts; the gap is never more than 0.004 in AUC.
Choosing k: noise against blur
The choice of is a trade-off between two kinds of error:
- Small is noisy. With the score is a single account's outcome, 0 or 1, and it changes completely if that one neighbour was a fluke. Statisticians call this high variance.
- Large is blurry. Each score averages over a wide neighbourhood, so real differences between accounts get smoothed away. At the extreme, equal to every training account, every prospect gets the same score: the overall customer rate of 7.3 percent. This is called high bias.
The best sits between the two, and the only reliable way to find it is to try several on accounts the model has not seen.
You can see the trade-off directly. The map below runs KNN on just two columns, company size and engagement, and shades every point by the score it would give a prospect there. At the map is a patchwork of islands, each one a single past account. At it has melted into broad regions. Press play to watch it change.
To choose for real, use cross-validation, which tests the model on accounts it did not train on. It splits the training accounts into five parts, builds the model on four, scores the fifth, and repeats so every part is scored once. Here is the result for the full lookalike model at ten values of , with and without scaling:
- Small is noisy. With one neighbour, AUC is 0.58, barely better than a coin toss.
- The curve rises fast, then flattens. From about 60 neighbours on, every scores between 0.820 and 0.827. In that range the choice hardly matters.
- Scaling beats raw numbers at every . The amber line is the same model without scaling. It never gets above 0.78.
Why is the best as large as 120? 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 to be larger than textbook examples suggest.
Judging the result: AUC, precision and lift
AUC, the area under the ROC curve, is the probability that the model scores a randomly chosen customer above a randomly chosen non-customer:
where and are the numbers of customers and non-customers, and is 1 when the condition holds and 0 otherwise. It compares every customer with every non-customer and counts how often the customer wins, with ties counting half. 0.5 is a coin toss and 1.0 is perfect. AUC suits a lookalike list because what we need from it is a good order, not a precise probability.
Two pictures make the formula concrete. The first shows the scores the final model gives the 1,500 test accounts it never saw, split into customers and non-customers. Customers' scores sit further right: the median customer scores 13.3 percent and the median non-customer 4.2 percent. AUC is the chance that a customer picked at random lands to the right of a non-customer picked at random. Move the cut-off to see what each threshold would flag.
The second is the ROC curve itself. Each point is one possible cut-off: how many customers it catches against how many non-customers it wrongly flags. The diagonal is a random list. The shaded area under the curve is the AUC, here 0.840.
Lift turns that order into a marketing number. For any slice of the ranked list:
In the business case, the top tenth of the test accounts has 43 customers out of 150, a rate of 28.7 percent, against 7.3 percent overall, so its lift is .
Precision and recall answer a question that AUC hides: how accurate is the list at each depth? Precision is the share of flagged accounts that became customers; recall is the share of all customers that were flagged:
where counts customers flagged, non-customers flagged, and customers missed. When customers are rare, as here at 7.3 percent, this chart is more honest than the ROC curve, because it does not count the easy wins of rejecting obvious non-buyers. Its summary, average precision, is 0.327 against 0.073 for a random list.
Can the score be read as a probability?
Not quite. A score is calibrated when, among accounts scored around 20 percent, about 20 percent buy. The calibration chart checks. It sorts all 5,000 accounts by their cross-validated score, cuts them into equal groups, and compares each group's average score with the share that actually bought. Points on the diagonal would mean "a score of 20 percent means a 20 percent chance". KNN tracks the diagonal well through the low and middle groups. In the top tenth, accounts scored 23 percent on average and 31 percent actually bought: the plain vote pulls the best accounts' scores down, because even their neighbourhood of 120 includes some weaker matches. Use the score to rank, and if you need probabilities for a forecast, calibrate it first.
Why fewer columns work better
KNN gets worse when you add columns that have nothing to do with buying, and the formula shows why. Every column adds a term to the sum inside the square root. An irrelevant column adds random differences to every distance, so the neighbours chosen become a little more random each time. With many such columns, the distances between all accounts become similar and "nearest" stops meaning anything, a problem known as the curse of dimensionality. In the running example, adding region, which is unrelated to buying, lowers cross-validated AUC from 0.827 to 0.822.
To show the effect plainly, the chart adds columns of pure random numbers to the real ones. With 20 of them, AUC falls from 0.827 to 0.782. The dashed line shows why: it measures how far an account's 120 nearest neighbours are, as a share of how far a typical account is. With clean data the neighbours are about half as far away as everyone else. With 40 noise columns they are 80 percent as far, so "nearest" barely means nearer.
Try it
Now see it in action. The map below shows 280 real accounts from the running example by company size and engagement (content downloads, plus pricing page visits, plus two for a webinar). The white diamond is a new prospect.
Three things to try:
- Move the prospect around. Mid-sized, engaged companies sit among mostly green neighbours. Small or quiet companies sit among grey ones.
- Change k. With k at 1, the score jumps between 0 and 100 percent as you move, because a single neighbour decides. As k grows the score settles. That trade-off, between reacting to local detail and being steady, is the main tuning decision in KNN.
- Switch to raw numbers. Watch the neighbour lines collapse into a vertical strip of companies with the same headcount, whatever their engagement. That is the scaling problem from the worked example, happening live.
Looking inside a KNN model
A model you cannot inspect is hard to trust. KNN is easier to inspect than most, because every score is a vote by real accounts.
One prospect's vote
Take the account the lookalike model scores highest among the 1,500 test accounts. The business case lists its five closest matches; here are all 120 neighbours that vote on it, nearest first, with the running share of customers. 53 of the 120 bought, so the account scores 44 percent. Slide down and watch the score swing: with very few neighbours it depends on which accounts happen to be closest, which is the noise from the math section.
Which columns matter
KNN has no coefficients to tell you which columns matter, but you can test it. Shuffle one column in the test data, so it no longer carries any information, and measure how much AUC falls. Repeat 20 times per column. This is called permutation importance, and it works for any model.
from sklearn.inspection import permutation_importance
imp = permutation_importance(knn, X_test, y_test, scoring="roc_auc",
n_repeats=20, random_state=42)Company size matters most by a wide margin, then pricing page visits. Pages per visit and content downloads add nothing once the other columns are in: their bars sit at zero, within the noise of the shuffles. That is a hint for the next version of the model, since every useless column makes the distances a little worse, as the curse of dimensionality section showed.
How much data it needs
The learning curve trains the same model on smaller samples of the training accounts, with scaled to match. With 250 accounts, AUC is 0.71; with 1,000 it is 0.78; with all 2,800 in each training fold it is 0.83, and still rising. KNN only knows what its stored accounts show it, so more history helps it directly. On this data it needs somewhere between 250 and 1,000 training accounts, roughly 20 to 70 past customers, before it beats the simple sorting rules teams use without a model (AUC 0.72 and 0.74, compared in the business case).
KNN in Python
The whole model is a few lines of scikit-learn. Scaling and encoding go inside the pipeline, so they are learned from the training accounts only:
from sklearn.compose import make_column_transformer
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
prep = make_column_transformer(
(StandardScaler(), numeric),
(OneHotEncoder(handle_unknown="ignore"), categorical),
)
knn = make_pipeline(prep, KNeighborsClassifier(n_neighbors=120))
knn.fit(X_train, y_train)
scores = knn.predict_proba(X_test)[:, 1] # the share of neighbours that boughtfit only stores the training rows and the scaling settings. The work happens in predict_proba, when each new row is compared with every stored one. The business case runs this end to end on real data, with every output shown.
When to use KNN, and when not to
KNN is a good choice when:
- You need to explain each score. "This account behaves like these five, and three of them bought" persuades a sales team in a way a coefficient does not.
- The pattern is lumpy. If good customers come in a few distinct pockets, KNN finds each pocket without being told the shape.
- The data changes often. Add new outcomes to the table and the next scores use them, with no retraining.
Choose something else when:
- You have millions of rows. Every score compares against every stored row. At that size, use an approximate nearest-neighbour library or a different method.
- You have many columns of uncertain value. Each irrelevant column dilutes every distance. Methods that learn weights, such as logistic regression or boosted trees, cope better.
- You need a calibrated probability. KNN ranks well, but its scores are shares of a neighbourhood, not probabilities.
- You need the most accurate ranking. On the lookalike data, logistic regression ranks slightly better (AUC 0.859 against 0.840).
| Method | What it gives you | Strength | Watch out for |
|---|---|---|---|
| KNN (this guide) | A score from similar examples | 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 |
Business cases
Each case applies KNN to one marketing job, from the business problem to a working list, with the code and data:
Download the data and the notebook
The notebook builds the lookalike model and computes every chart on this page, in its appendix.
Want this on your own data?
If you would like to know whether KNN, or another method, fits a problem in your own data, get in touch and we can talk it through on a short call.