← Blog/How KNN Works: The Math and Intuition, Explained for Marketers
Machine LearningKNNPythonStatisticsMarketing Analytics
Machine Learning · 24 min read

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.

· Martin Guzman

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.

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.

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 kk. 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:

x=(x1,x2,…,xp)\mathbf{x} = (x_1, x_2, \ldots, x_p)

Here pp is the number of columns. In the running example p=14p = 14: 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 ii also has an outcome yiy_i, which is 1 if it became a customer and 0 if it did not.

Distance

The distance between two accounts x\mathbf{x} and z\mathbf{z} is the straight-line, or Euclidean, distance:

d(x,z)=∑j=1p(xj−zj)2d(\mathbf{x}, \mathbf{z}) = \sqrt{\sum_{j=1}^{p} (x_j - z_j)^2}

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 12+12=2≈1.41\sqrt{1^2 + 1^2} = \sqrt{2} \approx 1.41 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":

x~j=xj−μjσj\tilde{x}_j = \frac{x_j - \mu_j}{\sigma_j}

where μj\mu_j is the column's average and σj\sigma_j 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 log⁡10(employees)\log_{10}(\text{employees}), which turns 10, 100 and 1,000 into 1, 2 and 3.

A worked example

Take a prospect PP with 100 employees and 8 engagement actions (downloads, pricing page visits and webinars added together), and two known accounts:

AccountEmployeesEngagement actionsIn plain words
Prospect P1008Mid-sized and very engaged
Account B1100Same size, no interest at all
Account C3008Bigger, exactly as engaged

A marketer would say C is the better match. On raw numbers the formula disagrees:

d(P,B)=(110−100)2+(0−8)2=164≈12.8d(P, B) = \sqrt{(110 - 100)^2 + (0 - 8)^2} = \sqrt{164} \approx 12.8 d(P,C)=(300−100)2+(8−8)2=200d(P, C) = \sqrt{(300 - 100)^2 + (8 - 8)^2} = 200

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 log⁡10(employees)\log_{10}(\text{employees}) is 0.499 and of engagement is 1.917, and log⁡10\log_{10} of 100, 110 and 300 is 2.000, 2.041 and 2.477:

d(P,B)=(2.041−2.0000.499)2+(0−81.917)2=0.0832+4.1732≈4.17d(P, B) = \sqrt{\left(\frac{2.041 - 2.000}{0.499}\right)^2 + \left(\frac{0 - 8}{1.917}\right)^2} = \sqrt{0.083^2 + 4.173^2} \approx 4.17 d(P,C)=(2.477−2.0000.499)2+(8−81.917)2=0.9562+0≈0.96d(P, C) = \sqrt{\left(\frac{2.477 - 2.000}{0.499}\right)^2 + \left(\frac{8 - 8}{1.917}\right)^2} = \sqrt{0.956^2 + 0} \approx 0.96

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 kk known accounts closest to x\mathbf{x} its neighbourhood, Nk(x)N_k(\mathbf{x}). KNN's score is the share of that neighbourhood that became customers:

p^(x)=1k∑i∈Nk(x)yi\hat{p}(\mathbf{x}) = \frac{1}{k} \sum_{i \in N_k(\mathbf{x})} y_i

Because each yiy_i 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 58/120=0.48358 / 120 = 0.483.

A common variant gives closer neighbours a bigger say, weighting each vote by one over its distance:

p^(x)=∑i∈Nk(x)wi yi∑i∈Nk(x)wi,wi=1d(x,xi)\hat{p}(\mathbf{x}) = \frac{\sum_{i \in N_k(\mathbf{x})} w_i \, y_i}{\sum_{i \in N_k(\mathbf{x})} w_i}, \qquad w_i = \frac{1}{d(\mathbf{x}, \mathbf{x}_i)}

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 kk, scored with five-fold cross-validation on the training accounts; the gap is never more than 0.004 in AUC.

Equal votes or weighted votes?
Try it
0.700.750.8051020406080120160240kAUC
every neighbour counts the samecloser neighbours count more
Hover the chart to compare at each k.
Five-fold cross-validated AUC on the training accounts, for each k and both voting rules.

Choosing k: noise against blur

The choice of kk is a trade-off between two kinds of error:

  • Small kk is noisy. With k=1k = 1 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 kk is blurry. Each score averages over a wide neighbourhood, so real differences between accounts get smoothed away. At the extreme, kk 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 kk 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 k=1k = 1 the map is a patchwork of islands, each one a single past account. At k=120k = 120 it has melted into broad regions. Press play to watch it change.

Noise against blur: the score KNN gives at every point
Try it
0481216101001,000employees (log scale)engagement actions
score0% → 60%
customernot a customer
Hover the map to read the score anywhere. Press play to step through k.
KNN on two columns only, size and engagement, using all 5,000 accounts. Bright means a high lookalike score.

To choose kk 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 kk, with and without scaling:

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.
  • Small kk 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 kk scores between 0.820 and 0.827. In that range the choice hardly matters.
  • Scaling beats raw numbers at every kk. The amber line is the same model without scaling. It never gets above 0.78.

Why is the best kk 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 kk 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:

AUC=1n1 n0∑i: yi=1  ∑j: yj=0[1(p^i>p^j)+12 1(p^i=p^j)]\text{AUC} = \frac{1}{n_1 \, n_0} \sum_{i:\, y_i = 1} \; \sum_{j:\, y_j = 0} \left[ \mathbb{1}(\hat{p}_i > \hat{p}_j) + \tfrac{1}{2}\,\mathbb{1}(\hat{p}_i = \hat{p}_j) \right]

where n1n_1 and n0n_0 are the numbers of customers and non-customers, and 1(⋅)\mathbb{1}(\cdot) 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.

Customers against non-customers: where their scores fall
Try it
0%10%20%30%0%10%20%30%40%lookalike scoreshare of group
10.0%
customers flagged
69%
76 of 110
non-customers flagged
23%
317 of 1,390
became customersdid not
The 1,500 test accounts. AUC measures how far apart these two shapes sit.

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.

The ROC curve behind the AUC
Try it
0%25%50%75%100%0%25%50%75%100%AUC = 0.840non-customers wrongly flagged (false positive rate)customers caught
score ≥ 27.5%
At a score of 27.5% or more: 13% of customers caught, 1% of non-customers flagged. The diagonal is random guessing.
Every possible cut-off on the 1,500 test accounts. The shaded area is the AUC.

Lift turns that order into a marketing number. For any slice of the ranked list:

lift=customer rate in the slicecustomer rate overall\text{lift} = \frac{\text{customer rate in the slice}}{\text{customer rate overall}}

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 0.287/0.073≈3.90.287 / 0.073 \approx 3.9.

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:

precision=TPTP+FP,recall=TPTP+FN\text{precision} = \frac{TP}{TP + FP}, \qquad \text{recall} = \frac{TP}{TP + FN}

where TPTP counts customers flagged, FPFP non-customers flagged, and FNFN 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.

Precision and recall: the trade-off when customers are rare
Try it
0%25%50%75%100%0%25%50%75%100%random: 7.3%recall: share of customers foundprecision: hit rate
score ≥ 29.2%
average precision
0.327
random would be 0.073
At a score of 29.2% or more: 67% of flagged accounts are customers, and they are 11% of all customers.
The 1,500 test accounts. The dashed line is the hit rate of 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.

Can the score be read as a probability?
Try it
0%10%20%30%0%10%20%30%perfectly calibratedaverage lookalike score in the groupshare that became customers
Hover a point. Each holds an equal share of the 5,000 accounts, sorted by score.
All 5,000 accounts, each scored by a model that had not seen it (cross-validated scores).

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.

The curse of dimensionality, measured
Try it
0.760.780.800.820.8440%60%80%025102040columns of random noise addedAUC
0
AUC
0.827
clean data
nearest 120, as share of typical distance
50%
100% = no nearer than anyone
AUC (left axis)how far the nearest 120 are, vs a typical account (right axis)
Columns of pure random noise added to the real ones. Five-fold cross-validated AUC, averaged over three runs.

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.

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.

Three things to try:

  1. Move the prospect around. Mid-sized, engaged companies sit among mostly green neighbours. Small or quiet companies sit among grey ones.
  2. 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.
  3. 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 kk 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.

The vote, one neighbour at a time
Try it
Prospect NP-02445: Software, 607 employees, 7 pricing page visits, attended a webinar.
0.02.04.06.08.00%50%100%neighbours, nearest firstdistance
k = 120
Score with k = 120
44%
53 of 120 became customers
became a customerdid notrunning share of customers (right axis)
Hover a bar to see that neighbour.
The 120 accounts that vote on the top-scored test account, nearest first. Real output from the notebook appendix.

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)
Which columns the model relies on
Try it
-0.020.000.020.040.06EmployeesPricing page visitsWeb visitsDays since last visitIndustryWebinar attendedEmail clicksPages per visitContent downloadsdrop in AUC when the column is shuffled
Hover a row. The white line spans one standard deviation across the 20 shuffles.
Permutation importance on the 1,500 test accounts: each column shuffled 20 times, measuring the drop in AUC.

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 kk 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).

How many accounts does it need?
Try it
0.700.750.800.8501,0002,000training accountsAUC
2,800 training accounts (k = 120): AUC 0.827, ±0.019 across the five folds
Five-fold cross-validated AUC with smaller and larger training sets. k grows with the data.

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 bought

fit 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).
MethodWhat it gives youStrengthWatch out for
KNN (this guide)A score from similar examplesExplains 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

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.