“One classifies by asking the neighbours, the other by doing the probability maths. Both are simpler than anything we have built so far.”
Every model in this series so far has done its hard work during training. Linear regression searched for weights, trees searched for splits, boosting stacked hundreds of corrections, and the SVM solved an optimisation problem to find its margin. Once trained, they predict quickly from a compact summary of the data.
This post covers algorithms seven and eight of Module 2, and they break that pattern. K-nearest neighbours (KNN) does no training at all: it remembers every example and, when asked about a new one, looks up the most similar cases. Naive Bayes trains in a single pass by counting, then classifies with Bayes’ theorem. Both are easy to explain to anyone, both are fast to get running, and both are still used in production today: KNN in recommendation and similarity search, Naive Bayes in spam and text filters.
K-nearest neighbours: the core idea

You move to a new neighbourhood and want to guess what kind of place it is. A sensible approach is to look at your closest neighbours. If most of them are students, you are probably in a university area. KNN classifies data exactly like that:
- Store all the labelled training examples. That’s the entire “training” step.
- When a new example arrives, measure the distance from it to every stored example.
- Pick the k closest ones, its nearest neighbours.
- Vote. For classification, predict the most common class among the k neighbours. For regression, predict the average of their values.
Because it postpones all the work until prediction time, KNN is called a lazy learner. The models from earlier posts, which build a summary up front, are eager learners.
How “near” is measured
KNN is only as good as its idea of distance. The three you will meet most:
- Euclidean distance, the straight-line distance, √((x₂ − x₁)² + (y₂ − y₁)²). The default, and the right choice for most numeric data.
- Manhattan distance, |x₂ − x₁| + |y₂ − y₁|, the distance you’d walk along a city grid. Less sensitive to one large difference in a single feature.
- Cosine distance, 1 − cos θ, which compares the direction of two vectors rather than their length. Standard for text, where a long and a short document about the same topic should count as close.
In scikit-learn you choose with the metric parameter; the default is Euclidean.
Step 1: KNN by hand
Five labelled points, one new point at (3, 3). Which class does it belong to?
import numpy as np
from collections import Counter
# Labelled points: (x, y) -> colour
points = np.array([[1, 1], [2, 4], [4, 4], [5, 1], [3, 1]])
labels = ["red", "blue", "blue", "red", "red"]
query = np.array([3, 3])
distances = np.sqrt(((points - query) ** 2).sum(axis=1)) # Euclidean distance
order = distances.argsort() # nearest first
for i in order:
print(f"{points[i]} {labels[i]:<5} distance = {distances[i]:.2f}")
for k in (3, 5):
votes = Counter(labels[i] for i in order[:k])
print(f"k={k}: votes = {dict(votes)} -> predict {votes.most_common(1)[0][0]}")
Output:
[2 4] blue distance = 1.41
[4 4] blue distance = 1.41
[3 1] red distance = 2.00
[1 1] red distance = 2.83
[5 1] red distance = 2.83
k=3: votes = {'blue': 2, 'red': 1} -> predict blue
k=5: votes = {'blue': 2, 'red': 3} -> predict red
What’s actually happening here
The two blue points are closest (1.41 away), so with k = 3 blue wins 2 to 1. With k = 5 the vote includes two more red points and the answer flips to red. Same data, same new point, different prediction. k is the single most important decision in KNN, and this tiny example shows why it can’t be chosen by gut feeling. (The diagram draws the “red” class as purple squares, following the series’ colour palette.)
Choosing k, and why scaling is not optional

Small and large k fail in opposite ways:
- k = 1 copies the label of the single closest example, so one noisy or mislabelled point decides the answer. The boundary is jagged: overfitting, high variance.
- A very large k averages over so many neighbours that local patterns disappear; with k equal to the dataset size, KNN just predicts the majority class every time. That is underfitting, high bias.
There is a second trap. KNN adds up differences across all features, so a feature measured in thousands drowns out one measured in fractions. In the breast cancer data, tumour area runs into the thousands while smoothness is around 0.1, so without scaling the distance is almost entirely “difference in area”. Let’s measure both effects:
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import cross_val_score
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_breast_cancer(return_X_y=True)
raw = KNeighborsClassifier(n_neighbors=5)
scaled = make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=5))
print("k=5 without scaling:", round(cross_val_score(raw, X, y, cv=5).mean(), 3))
print("k=5 with scaling: ", round(cross_val_score(scaled, X, y, cv=5).mean(), 3))
for k in [1, 3, 5, 9, 15, 25, 51]:
model = make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=k))
print(f"k={k:<3} accuracy = {cross_val_score(model, X, y, cv=5).mean():.3f}")
Output:
k=5 without scaling: 0.928
k=5 with scaling: 0.965
k=1 accuracy = 0.954
k=3 accuracy = 0.960
k=5 accuracy = 0.965
k=9 accuracy = 0.967
k=15 accuracy = 0.961
k=25 accuracy = 0.953
k=51 accuracy = 0.951
What’s actually happening here
Scaling alone lifts accuracy from 0.928 to 0.965, with no other change. Once the features are on the same scale, accuracy rises from k = 1 to a peak at k = 9, then slowly falls as k grows and the model gets too blunt. The curve is fairly flat near the top, which is typical: there is usually a range of good k values, and cross-validation finds it. Two practical tips: use an odd k for two-class problems to avoid ties, and try weights="distance", which gives closer neighbours a bigger say in the vote.
Naive Bayes: classification as probability
Naive Bayes comes at classification from a completely different angle. Instead of measuring distances, it asks: given what I see, how probable is each class? The answer comes from Bayes’ theorem, a rule for updating a belief when new evidence arrives.

P(class | features) = P(features | class) · P(class) / P(features)
- Posterior, P(class | features): what we want, the probability of the class given the data.
- Likelihood, P(features | class): how typical these features are for that class, counted from the training data.
- Prior, P(class): how common the class is overall.
- Evidence, P(features): the same for every class, so when we only want the most likely class we can ignore it and compare the numerators.
The trouble is the likelihood. With many features, P(all features together | class) would need an example of every possible combination. So Naive Bayes makes one bold simplification: it assumes the features are independent of each other within each class. Then the joint likelihood is just a product of simple per-feature probabilities:
score(class) = P(class) · P(x₁ | class) · P(x₂ | class) · … · P(xₙ | class)
That assumption is the “naive” in the name. It is almost never true (in text, “free” and “prize” clearly tend to appear together), yet the classifier often works very well anyway, because it only needs the ranking of the classes to be right, not the exact probabilities.
Step 2: Naive Bayes by hand
Back to the tennis data from Ep03: 14 days, 9 “play” and 5 “don’t play”. Should we play on a day that is sunny and cool? Count from the data: 2 of the 9 play days were sunny and 3 were cool; 3 of the 5 no-play days were sunny and 1 was cool.
# Play-tennis counts: 9 "yes" days, 5 "no" days out of 14
p_yes, p_no = 9 / 14, 5 / 14
p_sunny_yes, p_cool_yes = 2 / 9, 3 / 9 # P(sunny | yes), P(cool | yes)
p_sunny_no, p_cool_no = 3 / 5, 1 / 5 # P(sunny | no), P(cool | no)
score_yes = p_yes * p_sunny_yes * p_cool_yes
score_no = p_no * p_sunny_no * p_cool_no
print(f"score(yes) = {score_yes:.4f}")
print(f"score(no) = {score_no:.4f}")
print(f"P(yes | sunny, cool) = {score_yes / (score_yes + score_no):.3f}")
Output:
score(yes) = 0.0476
score(no) = 0.0429
P(yes | sunny, cool) = 0.526
What’s actually happening here
Each score is prior × likelihood × likelihood. “Yes” wins narrowly, 0.0476 to 0.0429. Dividing each score by their sum turns them into probabilities that add up to 1: 52.6% play. Notice the tug of war: sunny days lean towards “no” (60% of no-play days were sunny), but cool days and the higher prior of “yes” pull it back. That is the whole algorithm. Training is just counting, which is why Naive Bayes trains in a single pass even on millions of examples.
Step 3: A spam filter with Naive Bayes

Text is where Naive Bayes shines. Each email becomes a bag of word counts, and the model learns how likely each word is in spam versus normal mail (“ham”):
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
emails = [
"win a free prize now", "claim your free reward today", "cheap loans approved instantly",
"you have won cash click here", "limited offer win free money", "urgent claim your prize",
"meeting moved to monday", "can you review my pull request", "lunch at noon tomorrow",
"project update attached", "please send the invoice", "notes from today's standup",
]
labels = ["spam"] * 6 + ["ham"] * 6
vectorizer = CountVectorizer()
X = vectorizer.fit_transform(emails) # word counts per email
model = MultinomialNB(alpha=1.0).fit(X, labels)
new = ["free prize waiting for you", "can we move the meeting", "claim the invoice today"]
for text, probs in zip(new, model.predict_proba(vectorizer.transform(new))):
p = dict(zip(model.classes_, probs))
print(f"{text:<28} spam={p['spam']:.2f} ham={p['ham']:.2f}")
Output:
free prize waiting for you spam=0.91 ham=0.09
can we move the meeting spam=0.10 ham=0.90
claim the invoice today spam=0.39 ham=0.61
What’s actually happening here
CountVectorizer builds a vocabulary from the training emails and turns each email into a vector of word counts. MultinomialNB learns P(word | spam) and P(word | ham) from those counts. With just twelve emails, it already flags “free prize waiting for you” at 91% spam and clears the meeting message.
The third message is the interesting one. “claim” and “today” appeared in spam, but “invoice” appeared in a work email, so the evidence is mixed and the model lands at 39% spam, leaning ham but unsure. That is honest behaviour, and with a few thousand real emails instead of twelve it would become far more confident.
Two details make this work in practice:
- Laplace smoothing (
alpha=1.0). Words like “waiting” never appeared in training, so their raw probability would be 0, and one zero in the product would wipe out the whole score. Adding 1 to every count keeps unseen words from vetoing the decision. - Log probabilities. Multiplying hundreds of small probabilities underflows to zero on a computer, so implementations add logarithms instead of multiplying the raw numbers. The ranking stays the same.
The three flavours of Naive Bayes
Choose the version that matches your features:
GaussianNBfor continuous features (temperature, blood pressure, tumour radius). It assumes each feature follows a normal (bell-curve) distribution within each class and uses its mean and variance.MultinomialNBfor counts, above all word counts in text classification.BernoulliNBfor binary features, such as “does this word appear at all, yes or no”.
scikit-learn also offers ComplementNB, a variant of the multinomial model that copes better with imbalanced text classes, and CategoricalNB for categorical features like the tennis data.
Step 4: KNN vs Naive Bayes on the same data
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import cross_val_score
from sklearn.naive_bayes import GaussianNB
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_breast_cancer(return_X_y=True)
models = {
"Gaussian Naive Bayes": GaussianNB(),
"KNN (k=9, scaled)": make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=9)),
}
for name, model in models.items():
scores = cross_val_score(model, X, y, cv=5)
print(f"{name:<21} accuracy = {scores.mean():.3f} ± {scores.std():.3f}")
Output:
Gaussian Naive Bayes accuracy = 0.939 ± 0.015
KNN (k=9, scaled) accuracy = 0.967 ± 0.014
What’s actually happening here
Gaussian Naive Bayes reaches 0.939 with no tuning and no scaling. That’s a respectable baseline, but it trails KNN because many of these 30 tumour measurements are strongly related (radius, perimeter and area all describe size), which breaks the independence assumption. KNN, with scaling and a tuned k, matches the random forest and SVM from earlier posts. Neither result is “the winner” in general: Naive Bayes would beat KNN easily on a text problem with 50,000 word features, where distances become meaningless.
When to use which
- KNN suits small to medium datasets with a modest number of meaningful, scaled numeric features, where similar inputs really should have similar outputs: recommendations (“customers like you bought…”), finding similar patients or products, handwriting recognition, filling in missing values (
KNNImputer), and anomaly detection (a point far from all its neighbours is suspicious). - Naive Bayes suits text and other high-dimensional data, very large datasets, and situations where you need a fast, cheap baseline: spam filtering, sentiment analysis, news and document categorisation, and real-time classification where training must be instant.
Common first-time mistakes
- Forgetting to scale features for KNN. As the 0.928 → 0.965 jump shows, this is the most common cause of a “bad” KNN.
- Picking k by eye. Use cross-validation, and prefer odd values for two-class problems.
- Running KNN on hundreds of features. In high dimensions every point ends up roughly equally far from every other (the curse of dimensionality), so “nearest” stops meaning anything. Reduce dimensions first (PCA, coming in Ep09) or choose another model.
- Trusting Naive Bayes probabilities literally. Because of the independence assumption, its probabilities are often pushed towards 0 or 1. The ranking is usually right; the exact numbers are not. Use
CalibratedClassifierCVif you need reliable probabilities. - Turning off smoothing in Naive Bayes, so a single unseen word zeroes out a class.
The honest limitations
KNN is fast to “train” but slow to predict: a naive implementation compares every new point with every stored example, and it must keep the whole training set in memory. Tree-based indexes (algorithm="kd_tree" or "ball_tree") help on low-dimensional data, but on millions of rows you need approximate nearest-neighbour libraries. It is also sensitive to irrelevant features, since every feature counts towards the distance.
Naive Bayes’ independence assumption is its weakness as well as its strength. When features are strongly correlated it effectively double-counts the same evidence, and it can’t learn interactions (“this word means spam only when that word is also present”). It is rarely the most accurate model on structured data, but it is often the fastest one that is good enough.
Where to go next
- scikit-learn: Nearest Neighbors user guide, covering distance metrics, weighting and KD-tree and ball-tree indexes.
- scikit-learn: Naive Bayes user guide, covering the Gaussian, multinomial, Bernoulli, complement and categorical variants.
That makes eight supervised algorithms. Ep06 closes Module 2 with the ninth, the artificial neural network, which stacks logistic regressions into layers and learns with backpropagation. Then we finally answer the question every post so far has hinted at: how do you know if a model is actually good? That means overfitting, cross-validation, the confusion matrix, and precision, recall and F1.
This post is part of the CeyTech series Machine Learning: From 0 to Machine – deep tech, no fluff. Add a few emails of your own to the spam example, or try metric="manhattan" in KNN, and tell me what changed.

Comments (...)
You must be signed in to join the discussion.