AI ENGINEER01-04 · Other core algorithms
20/90
Sign in

Layer 01 · Classical ML · Ch 04

Other core algorithms

Predict from nearby examples, separate classes with wide margins, and combine probabilistic evidence.

65 min readdifficulty beginnerdepth use

Three algorithms can learn from the same labelled table for three very different reasons.

k-NN trusts nearby examples. An SVM searches for a wide separating boundary. Naive Bayes multiplies class-conditional evidence.

Lesson details

Module
Classical machine learning
Lesson
4 · Other core algorithms
Difficulty
Beginner
Learning time
65 minutes

Before you start

  • Vectors, norms, dot products, probability, and Bayes' rule
  • Features, scaling, classification, regression, and validation

Skills you will gain

  • Calculate a k-nearest-neighbour prediction
  • Choose and scale features for meaningful distance
  • Explain SVM margins, support vectors, C, and kernels
  • Distinguish a kernel similarity from an explicit feature map
  • Calculate a small Naive Bayes posterior
  • Apply Laplace smoothing to zero word counts
  • Choose a sensible baseline algorithm for data size and representation

Why this matters

Not every tabular problem needs a tree ensemble.

Neighbour methods are transparent local baselines. Linear SVMs can excel on high-dimensional sparse text. Kernel SVMs capture nonlinear boundaries on suitable smaller datasets. Naive Bayes trains quickly and provides a strong sparse-text baseline.

Plain-English mental model

Part 1 — k-NN stores examples and delays the work

k-nearest neighboursk-nearest neighboursA non-parametric method that predicts from the targets of the k training examples closest to a query under a chosen distance. Classification votes or averages class values; regression averages numerical targets., shortened to k-NN, has a minimal fitting stage:

  1. Store training features and targets.
  2. For a query, calculate distance to training examples.
  3. Select the closest k.
  4. Combine their targets.

Classification:

prediction = majority vote or distance-weighted vote

Regression:

prediction = mean or distance-weighted mean target

k-NN is sometimes called a lazy learner because prediction performs most of the search.

Part 2 — Distance defines “near”

A distance metricDistance metricA rule for quantifying how far two feature vectors are, such as Euclidean or Manhattan distance. Its meaning depends on representation, units, scaling, missing-value handling, and domain relevance. quantifies separation between feature vectors.

Euclidean distance:

d(x,q) = square_root(Σ(x_j-q_j)²)

Manhattan distance:

d(x,q) = Σ|x_j-q_j|

Cosine distance is often defined from cosine similarity:

distance = 1 - cosine_similarity

Choice depends on representation. Euclidean distance on one-hot categories means something different from Euclidean distance on physical coordinates.

Scale can dominate

Suppose:

  • age ranges 18–90;
  • annual income ranges 15,000–300,000.

Raw Euclidean distance is dominated by income units.

Standardise numerical features using training statistics:

scaled = (value - training_mean) / training_std

Apply the frozen transform to validation, test, and query rows.

FIG 01-04.1 · THE NEIGHBOURHOOD DEPENDS ON k AND REPRESENTATIONscaled message lengthscaled account agek=3k=7new ticketbillingtechnicallocal votek=3 → 2 blue / 1 redk=7 → 3 blue / 4 reddistance is meaningless until units and scale are intentional
FIG 01-04.1— the three nearest neighbours vote billing, while a wider seven-neighbour region votes technical. Neither k is intrinsically correct. Select k, metric, weighting, and scaling using training and validation evidence.

Part 3 — Calculate a neighbour prediction

LAB 01-04.A · CLASSIFY WITH k NEAREST NEIGHBOURS
IDLE⌘↵ to run

Expected output:

[(1.414, 'billing'), (2.0, 'billing'), (2.236, 'billing')]
{'billing': 3}
prediction: billing

Important lines

dist(features, query)
Calculates Euclidean distance in the current representation. Production preprocessing must make those coordinates comparable.
sorted(... )[:k]
Ranks all stored examples and keeps the closest k. Index structures can accelerate some searches.
votes[label]
Counts class targets among neighbours. Distance weighting can give closer rows more influence.
max(votes, key=votes.get)
Returns the largest vote. A production implementation needs a deterministic tie rule.

Part 4 — Choosing k changes smoothness

Small k:

  • captures local detail;
  • sensitive to noise and single points;
  • produces irregular decision boundaries.

Large k:

  • smooths local variation;
  • may ignore minority neighbourhoods;
  • eventually approaches the global majority.

Choose odd k to reduce binary vote ties, but ties can still occur with multiple classes or distance weighting.

Select k with validation or cross-validation. Do not choose it because a training plot looks attractive.

Part 5 — The curse of dimensionality

The curse of dimensionalityCurse of dimensionalityA collection of effects that appear as feature dimensions grow, including rapidly expanding space and less informative nearest-neighbour distances unless data grows enormously or representation has useful structure. describes problems that appear as dimensions grow.

If each feature ranges from 0 to 1, the unit hypercube volume stays 1, but neighbourhood volume becomes difficult to cover. To span only 10% of each coordinate:

1 dimension: 0.1 of the interval
10 dimensions: 0.1¹⁰ of the volume

Data becomes sparse, and nearest and farthest distances can become less distinguishable.

Responses:

  • select relevant features;
  • learn or choose a meaningful embedding;
  • reduce dimension;
  • use cosine similarity for suitable text embeddings;
  • collect more representative data;
  • choose another model.

Do not apply k-NN to thousands of raw noisy columns and assume “nearest” means similar.

Part 6 — k-NN engineering trade-offs

Training is cheap; prediction can be expensive:

brute-force query cost ≈ number of rows × dimensions

Search structures:

  • k-d trees;
  • ball trees;
  • approximate nearest-neighbour indexes.

Their effectiveness depends on metric, dimension, and accuracy/latency trade-offs.

k-NN also stores training examples. For personal or sensitive data, this creates retention, deletion, access-control, and possible information-exposure concerns.

Part 7 — SVMs prefer a wide margin

A linear classifier has boundary:

w · x + b = 0

A support-vector machineSupport-vector machineA model that chooses a separating boundary with a large margin, allowing controlled violations in the soft-margin form. The closest influential training examples are support vectors., shortened to SVM, chooses a separating boundary with a large marginMarginThe distance between an SVM decision boundary and the closest class-constraining examples. Maximising it expresses a preference for a robust separator, balanced against training violations through regularisation..

The margin is the corridor between the boundary and closest class-constraining examples.

Those closest influential points are support vectorsSupport vectorA training example on or inside the SVM margin that directly influences the fitted decision boundary. Many more distant examples can move without changing that boundary..

Distant training points often do not change the fitted boundary unless they move into the margin.

Hard margin versus soft margin

A hard-margin SVM requires perfect separation. It fails when classes overlap and is brittle to outliers.

A soft-margin SVM allows violations through slack variables.

Hyperparameter C controls penalty:

  • larger C: violations cost more; fit training data more aggressively;
  • smaller C: violations cost less; wider margin and stronger regularisation.

This convention applies to common SVM APIs, but always check library definitions.

Part 8 — Hinge loss

For labels y ∈ {-1,+1} and score f(x)=w·x+b:

hinge loss = max(0, 1 - y f(x))

If y f(x) ≥ 1, the example is correctly placed outside the margin and loss is zero.

If it is inside the margin or incorrectly classified, loss is positive.

The SVM objective balances:

  • a small weight norm, which corresponds to a wider margin;
  • penalties for hinge-loss violations.

SVM scores are not probabilities by default. Probability calibration is a separate fitted procedure requiring held-out or cross-validated evidence.

Part 9 — Kernels create nonlinear boundaries

A linear SVM separates with a hyperplane in its feature space.

A feature map can add nonlinear coordinates:

(x1, x2) → (x1², square_root(2)x1x2, x2²)

The kernel trickKernel trickComputing inner products corresponding to a richer feature mapping without explicitly constructing every mapped coordinate. It allows an SVM to form nonlinear boundaries while keeping a linear separator in the implicit feature space. computes inner products in an implicit richer space without explicitly constructing all mapped coordinates.

Common kernels:

  • linear: K(x,z)=x·z;
  • polynomial;
  • radial basis function, shortened to RBF;
  • sigmoid, used less commonly.

RBF:

K(x,z) = exp(-gamma × ||x-z||²)

gamma controls locality:

  • high gamma: influence falls quickly; flexible boundary and overfitting risk;
  • low gamma: broad influence; smoother boundary and underfitting risk.

Scale features before RBF SVM, because squared distance drives the kernel.

FIG 01-04.2 · SVM USES THE BOUNDARY POINTS · NAIVE BAYES USES CLASS EVIDENCESVM · widest safe streetdecision boundarymarginclosest points = support vectorskernel → curved boundaryNaive Bayes · evidenceprior class probabilityP(billing)× P("refund" | billing)× P("invoice" | billing)unnormalised class scorenormalise across classesposterior probabilitieszero count? smooth itfeatures assumed independent given class
FIG 01-04.2— support vectors constrain a maximum-margin boundary; kernels can make that boundary nonlinear through implicit similarity. Naive Bayes starts with priors, multiplies class-conditional feature evidence, and normalises. Smoothing prevents one unseen count from zeroing a class.

Part 10 — SVM computational choices

Kernel SVM training can scale poorly with the number of rows because it uses pairwise similarities. Exact complexity depends on data and solver, but large datasets can become expensive in time and memory.

For large sparse text:

  • use a linear SVM implementation designed for many rows/features;
  • avoid an RBF kernel by default;
  • compare logistic regression and Naive Bayes.

For smaller nonlinear datasets:

  • scale features;
  • tune C and gamma inside cross-validation;
  • compare against trees and simpler baselines.

Part 11 — Naive Bayes applies Bayes by class

For class c and features x:

P(c | x) ∝ P(c) × P(x | c)

Naive BayesNaive BayesA probabilistic classifier that combines class priors with feature likelihoods using a conditional-independence assumption. The assumption is often unrealistic, but the model can work well for sparse text and small-data baselines. assumes features are conditionally independentConditional independenceTwo variables are conditionally independent given a third when knowing one provides no additional information about the other after the third is known. Naive Bayes assumes features are conditionally independent given the class. given the class:

P(x1, x2, ... | c)
= P(x1|c) × P(x2|c) × ...

Text words are not truly independent. “credit” and “card” correlate. The assumption still produces a useful, fast classifier in many sparse problems.

Work in log space

Multiplying many tiny probabilities underflows:

log score(c)
= log P(c) + Σ log P(feature_j | c)

Choose the largest log score, or use stable log-sum-exp to normalise.

Part 12 — A small text calculation

Training counts:

Class Documents refund count server count total word count
billing 6 5 0 20
technical 4 1 4 16

Without smoothing, P(server|billing)=0, so any document containing server gives billing score zero.

Laplace smoothingLaplace smoothingAdding a positive pseudo-count, commonly one, to categorical or word counts before estimating probabilities. It prevents unseen training combinations from forcing a Naive Bayes class score to zero. adds one to every vocabulary count:

P(word | class)
= (count(word,class)+1) / (total_words_in_class + vocabulary_size)

Smoothing strength is a hyperparameter in general additive smoothing.

LAB 01-04.B · NAIVE BAYES IN LOG SPACE
IDLE⌘↵ to run

Expected output:

{'billing': 0.376, 'technical': 0.624}

The result depends on simplified counts, vocabulary, tokenisation, smoothing, and independence assumptions.

Part 13 — Naive Bayes variants

Choose a likelihood model matching feature type.

Gaussian Naive Bayes

Models each numeric feature with a Gaussian distribution per class.

Suitable baseline for continuous features when the approximation is reasonable.

Multinomial Naive Bayes

Models non-negative counts or count-like values.

Common for word-count and TF–IDF-style text features, though TF–IDF is not literally generated by a multinomial count process.

Bernoulli Naive Bayes

Models binary feature presence/absence.

Useful when whether a token appears matters more than how often.

Complement Naive Bayes

Uses statistics from the complement of each class and is often useful for imbalanced text classification.

Validate variants; names describe assumptions, not guaranteed winners.

Part 14 — Probability quality and duplicated evidence

Naive Bayes posterior numbers can be overconfident because correlated features are multiplied as if independent.

If refund, refunds, and refunding all encode nearly the same evidence, the model may count it several times.

Evaluate:

  • discrimination;
  • calibration;
  • errors by class and group;
  • robustness to vocabulary and tokenisation;
  • out-of-vocabulary behaviour;
  • probability stability under duplicated correlated features.

Use calibrated probabilities when downstream decisions require trustworthy risk estimates.

Worked comparison — ticket topic classification

Goal: classify a new ticket as billing or technical.

k-NN

Represent messages with embeddings, scale any added numeric features, and retrieve nearby labelled tickets.

Strength: inspect actual neighbours.

Risk: embedding distance may not match topic; queries grow expensive; stored examples may expose sensitive text.

Linear SVM

Represent messages with sparse TF–IDF features and fit a wide-margin separator.

Strength: strong high-dimensional sparse baseline.

Risk: score is not a probability; tune C; inspect token and label bias.

Multinomial or Complement Naive Bayes

Use token counts or suitable non-negative text features with smoothing.

Strength: extremely fast and effective with small sparse data.

Risk: correlated words and likelihood assumptions can create overconfidence.

Selection

Use the same time-and-customer split. Compare the declared metric, calibration if required, latency, memory, privacy, and explainability.

The best algorithm depends on representation and operating constraints, not the name.

In a real AI system

Common mistakes

Running k-NN on raw mixed-scale features.

Fix — Choose units and metric deliberately; fit scaling on training data and apply it unchanged.

Choosing k from test-set accuracy.

Fix — Select k, weighting, and metric with training and validation or cross-validation evidence.

Assuming nearest neighbours stay meaningful in many noisy dimensions.

Fix — Select or learn useful representations, reduce dimension, inspect distance concentration, and compare another model.

Treating an SVM score as a probability.

Fix — It is a signed decision score. Fit and evaluate a separate calibration procedure when probabilities are needed.

Using RBF SVM without scaling or tuning gamma.

Fix — Place scaling inside the pipeline and tune C and gamma within training folds.

Calling the kernel trick free nonlinear modelling.

Fix — Kernel training and prediction can be expensive; boundary flexibility still needs regularisation and valid evaluation.

Letting one unseen word make a Naive Bayes class probability zero.

Fix — Use additive smoothing fitted on training counts.

Believing Naive Bayes features are literally independent.

Fix — Treat independence as a modelling approximation and evaluate calibration and correlated evidence.

Exercises

warmup · 1

Training points are `A=(0,0)`, `B=(2,0)`, and `C=(5,0)` with labels red, red, blue. For query `(3,0)`, calculate Euclidean distances and predict with `k=1` and `k=3`.

Reveal solution

Distances are 3 to A, 1 to B, and 2 to C. With k=1, nearest B predicts red. With k=3, two red votes beat one blue vote, so the prediction remains red. This example also shows that changing k need not change every decision.

core · 2

An SVM has a narrow margin with zero training mistakes. Another has a wider margin with two violations. Explain why validation might prefer the second and which hyperparameter controls the trade-off.

Reveal solution

The zero-error separator may be shaped by noise and generalise poorly. A soft-margin SVM balances margin width and violations. Hyperparameter C penalises violations: larger C usually prioritises fewer training violations and a narrower margin, while smaller C allows more violations for stronger regularisation. Select C using scaled training and validation data.

stretch · 3

A two-class text model has priors `P(billing)=0.6`, `P(technical)=0.4`. It estimates `P(refund|billing)=0.5`, `P(invoice|billing)=0.4`, `P(refund|technical)=0.1`, and `P(invoice|technical)=0.05`. Calculate and normalise Naive Bayes scores for a document containing refund and invoice.

Reveal solution

Billing score is 0.6×0.5×0.4=0.12. Technical score is 0.4×0.1×0.05=0.002. Total is 0.122, so normalised billing posterior is about 0.12/0.122=0.984 and technical about 0.016, under the model assumptions.

Knowledge check

Knowledge check

1Why is feature scaling especially important for Euclidean k-NN?
2Which training examples determine an SVM boundary most directly?
3What does a high RBF gamma usually do?
4Why use Laplace smoothing in Multinomial Naive Bayes?

Practice activity

Practice · 10–20 minutes

Compare three predictions on one tiny dataset

Goal: Trace the mechanism of k-NN, a linear margin score, and Naive Bayes rather than treating them as black boxes.

  1. Calculate Euclidean distances from query `(2,1)` to the supplied points.
  2. Predict with k=3.
  3. Calculate SVM-style score `z=x1+x2-2.5` and its class sign.
  4. Calculate unnormalised Naive Bayes class scores for words refund and server.
  5. Normalise the Naive Bayes scores.
  6. State which representation assumption each prediction relies on.

Expected result: k-NN predicts billing; the linear score is 0.5 and predicts the positive class under threshold zero; the smoothed Naive Bayes example assigns about 0.376 billing and 0.624 technical.

Optional challenge: Change one feature scale by 100 and show how k-NN changes unless the transform is corrected.

Reveal solution
from math import dist

training = [
    ((0, 0), "billing"),
    ((1, 0), "billing"),
    ((0, 1), "billing"),
    ((4, 4), "technical"),
]
query = (2, 1)

neighbours = sorted(
    (dist(point, query), label)
    for point, label in training
)[:3]

margin_score = query[0] + query[1] - 2.5

print("neighbours:", [(round(d, 3), label) for d, label in neighbours])
print("k-NN:", "billing")
print("margin score:", margin_score)
print("SVM-style class:", int(margin_score >= 0))
print("Naive Bayes:", {"billing": 0.376, "technical": 0.624})

Expected output:

neighbours: [(1.414, 'billing'), (2.0, 'billing'), (2.236, 'billing')]
k-NN: billing
margin score: 0.5
SVM-style class: 1
Naive Bayes: {'billing': 0.376, 'technical': 0.624}

k-NN assumes geometric neighbourhood is meaningful. The SVM score assumes a linear boundary in this feature space. Naive Bayes assumes its fitted feature likelihoods and conditional-independence factorisation are useful.

Key takeaways

  • k-NN predicts from local training targets, so representation, scale, metric, and k define its behaviour.
  • High-dimensional distance can become uninformative and exact neighbour search can become expensive.
  • SVMs balance a wide margin against training violations; support vectors determine the boundary.
  • Kernels provide implicit nonlinear feature similarity but add compute and tuning risk.
  • Naive Bayes multiplies class priors and feature likelihoods under conditional independence.

Flashcards

Flashcards

1 of 10

Revision and interview questions

  1. Design and calculate a k-NN prediction, including scaling, metric, k, weighting, and tie handling.
  2. Explain hard and soft margins, hinge loss, support vectors, and C.
  3. Explain an RBF kernel and how gamma changes boundary flexibility.
  4. Calculate a smoothed Multinomial Naive Bayes posterior in log space.
  5. Compare k-NN, linear SVM, kernel SVM, and Naive Bayes for sparse text, embeddings, and small tabular data.

One-page sketchnote summary

Print me · one-page revision sheet

Other core algorithms

Main idea

k-NN uses local examples, SVMs use margin geometry, and Naive Bayes uses a probabilistic factorisation. Each can be an excellent baseline when its representation and assumptions match the problem.

Core terms

  • k-NN — local target vote
  • Metric — meaning of distance
  • Margin — SVM safety corridor
  • Support vector — boundary-defining row
  • Kernel — implicit feature similarity
  • Naive Bayes — prior × likelihoods

One picture

SVM · widest safe streetdecision boundarymarginclosest points = support vectorskernel → curved boundaryNaive Bayes · evidenceprior class probabilityP(billing)× P("refund" | billing)× P("invoice" | billing)unnormalised class scorenormalise across classesposterior probabilitieszero count? smooth itfeatures assumed independent given class

Code pattern

knn = vote(nearest(query, k, metric))
svm_class = sign(weights @ features + bias)
log_score[class] = log(prior[class]) + sum(log_likelihoods)
posterior = softmax(log_scores)

Watch out

  • Do not use raw mixed-scale distance
  • Do not tune k on test data
  • Do not call SVM scores probabilities
  • Do not kernelise huge data blindly
  • Do not multiply unsmoothed tiny probabilities

Remember

  • Neighbourhood depends on representation
  • Wide margins regularise boundaries
  • Kernels trade flexibility for cost
  • Bayes combines prior and evidence
  • Smooth counts · calculate in log space

Three quick questions

  1. What does near mean here?
  2. Which rows constrain this margin?
  3. Which evidence was counted twice?

Lesson checklist

0 of 9 complete

Resources

Next up
Unsupervised learning
You can now compare several supervised decision mechanisms. Next, remove the target labels and learn how clustering and dimensionality reduction reveal useful structure without pretending that discovered groups are ground truth.