⚡0 XP🔥0

K-Nearest Neighbours and Naive Bayes

Lesson 5 of 11 ⏱ 6 min read ✎ 2 exercises ❓ 4-question quiz ▶ Runs Python

Two intuitive classifiers - KNN (vote of the closest examples, choosing k, why scaling matters) and Naive Bayes (probability with Bayes' theorem), including a small spam filter on text.

K-Nearest Neighbours (KNN)#

KNN is the simplest classifier to understand: "tell me who your neighbours are, and I'll tell you who you are."

To classify a new point:

  1. Measure its distance to every training point (usually Euclidean distance).
  2. Take the k closest points.
  3. Predict the majority class among them (for regression: their average).
distance between a and b = √((a₁ - b₁)² + (a₂ - b₂)² + ...)
▶ Try it YourselfPython
Ctrl + Enter to run
Output
  neighbour [ 3 80] (fail) at distance 2.83
  neighbour [ 5 72] (pass) at distance 6.00
  neighbour [ 6 85] (pass) at distance 7.07
Prediction: pass
हिंदी में समझें

KNN नए point के सबसे पास वाले k पड़ोसी ढूँढता है और उनमें जो class सबसे ज़्यादा है, वही जवाब देता है - "जैसी संगत, वैसी रंगत"। यह training में कुछ नहीं सीखता, बस data याद रखता है, इसलिए इसे "lazy learner" कहते हैं।

Why scaling matters for KNN#

In the example, attendance (60-95) has a much larger range than study hours (2-8), so it dominates the distance. With real features like income (lakhs) and age (years), unscaled KNN is almost meaningless:

▶ Try it YourselfPython
Ctrl + Enter to run
Output
without scaling: 0.759
with scaling   : 0.963

Choosing k#

▶ Try it YourselfPython
Ctrl + Enter to run
Output
k= 1  train 1.000  test 0.944
k= 3  train 0.968  test 0.963
k= 5  train 0.984  test 0.963
k= 9  train 0.976  test 0.963
k=15  train 0.968  test 0.944
k=25  train 0.976  test 0.963
k=45  train 0.976  test 0.963
  • Small k - very flexible; k = 1 scores 100% on training data (it memorises) - overfitting risk.
  • Large k - smoother, more stable; too large and it ignores local patterns - underfitting.
  • Use odd k for two classes (no ties), and choose k with cross-validation.
KNN pros KNN cons
simple, no training time slow predictions on big datasets (compares with every point)
works for any number of classes needs scaling; struggles with many features ("curse of dimensionality")
naturally non-linear must store all training data

Naive Bayes#

Naive Bayes uses probability. Bayes' theorem says how to update a belief with evidence:

P(class | features) = P(features | class) · P(class) / P(features)

"Naive" means it assumes every feature is independent given the class, so P(features | class) is just a product of per-feature probabilities. The assumption is rarely true, yet Naive Bayes is fast and works surprisingly well - especially for text (spam filters, sentiment, news categories).

A tiny worked example#

10% of emails are spam. The word "free" appears in 60% of spam and 5% of normal (ham) emails. An email contains "free" - how likely is it spam?

▶ Try it YourselfPython
Ctrl + Enter to run
Output
P(free) = 0.105
P(spam | 'free') = 0.571

One word raised the spam probability from 10% to 57%. Naive Bayes multiplies the evidence from every word.

A spam filter with scikit-learn#

Text must become numbers first. CountVectorizer turns each message into word counts (a "bag of words"):

▶ Try it YourselfPython
Ctrl + Enter to run
Output
vocabulary size: 31
free cash offer           -> spam (P(spam) = 0.94)
send the project notes    -> ham  (P(spam) = 0.05)
win a free trip now       -> spam (P(spam) = 0.97)
team meeting tomorrow     -> ham  (P(spam) = 0.10)

Variants: MultinomialNB (word counts), BernoulliNB (word present/absent), GaussianNB (continuous features like measurements).

Tip

For real spam or sentiment projects, try the SMS Spam Collection or IMDB reviews datasets on Kaggle, use TfidfVectorizer instead of raw counts, and evaluate with precision and recall.

Summary#

  • KNN predicts from the k nearest training points; scale features and choose k carefully.
  • Small k overfits, large k underfits; KNN is simple but slow on large data.
  • Naive Bayes applies Bayes' theorem with an independence assumption; it is fast and strong on text.
  • Text → numbers with CountVectorizer/TfidfVectorizer, then MultinomialNB.

Practice Exercises

Write your code, then press Check. Your program is tested automatically.

1

Find the best k

On the wine data (test_size=0.3, random_state=5, stratify=y), scale with a pipeline and try k = 1, 3, 5, ..., 15. Store the k with the highest test accuracy in best_k (choose the smallest k if tied) and print best k = ....

2

Classify messages with Naive Bayes

Train CountVectorizer + MultinomialNB on the messages in the starter and predict the label of "win a free recharge now" and "lecture notes for tomorrow". Store the predictions in a list preds and print it.

Quick Quiz

Q1.

How does KNN classify a new point?

Q2.

Why must features be scaled for KNN?

Q3.

A very small k (like k = 1) tends to...

Q4.

Why is Naive Bayes called "naive"?