k-NN, k-means, PCA, SVM and naive Bayes: the classical toolkit

  • Intermediate
  • 1 h 25 min
  • Lesson 2 of 2 in Trees, ensembles and classical models
  • Last verified

Open slides(39 slides)

Before you start

You will be able to

  • Explain k-nearest neighbours as a model that stores the data, how k trades bias against variance, and why distance concentrates in high dimensions so that irrelevant or unscaled columns wreck the neighbours.
  • Run the k-means loop by hand, explain why it reaches only a local optimum and what k-means++ and restarts change, choose k with inertia and silhouette, and name the cases where it fails (non-convex shapes, unscaled columns, outliers) with DBSCAN and hierarchical clustering as alternatives.
  • Compute PCA by centring, covariance and eigen-decomposition, read the explained variance to pick the number of components, and say when PCA misleads (units, signal in low-variance directions, non-linear structure).
  • Choose between k-NN, a linear or kernel SVM, naive Bayes, trees and linear models for a case from its size, dimension, need for probabilities and need for explanation, using the margin and hinge loss for the SVM and the independence assumption for naive Bayes.
  • Say what Gaussian mixtures with EM, Isolation Forest, t-SNE and UMAP add to k-means and PCA, and why the clusters of a t-SNE plot are not features.

Concept

Five methods older than the deep-learning era are still in daily use: k-nearest neighbours, k-means, PCA, support vector machines and naive Bayes. Each fits in a page of code and breaks in a predictable way. This lesson teaches the mechanism and the failure together, because the failure is what an interviewer asks about and what bites in production.

Each method is a cheap bet about distance or variance: k-NN that close points share labels, k-means that clusters are balls, PCA that spread is importance, the SVM that a far boundary generalises, naive Bayes that features speak independently. Each loses on some data set; the script at the end builds that data set for every method, and the last section compares the supervised methods in one table.

The first lesson gave the vocabulary of bias, variance and validation, the second introduced the hinge loss used below, and the trees lesson covers the other classical family.

Diagram: Without labels you either group the rows (k-means, hierarchical clustering, DBSCAN) or compress the columns (PCA).

no

no

yes

Do you have labels?

Group the rows

Compress the columns

Predict a label

k-means: needs k, round clusters

Hierarchical: a tree of merges

DBSCAN: dense regions, flags noise

PCA: linear, keeps variance

k-NN: vote of close rows

SVM: widest margin

Naive Bayes: product of per-feature evidence

Diagram summary: Without labels you either group the rows (k-means, hierarchical clustering, DBSCAN) or compress the columns (PCA). With labels you predict with k-NN, an SVM or naive Bayes. Trees and linear models, from the earlier lessons, are the other supervised branches.

Why It Matters

These methods are quick baselines and train habits that carry over to every model: check units, check dimension, name the assumption. They are also common interview topics (common industry pattern).

k-nearest neighbours

To classify a new row, k-NN finds the kk training rows closest to it and takes a majority vote. Scikit-learn calls this instance-based learning: nothing is fitted, the training set is stored (scikit-learn, Nearest Neighbors). Training is cheap (at most an index is built); by brute force a query is compared with all nn rows in dd dimensions, work that grows like ndnd (derived). The guide says a KD tree is very fast for DD below 20 and inefficient as DD grows, while a ball tree can do better in high dimension, depending on the structure of the data.

Choosing k is the bias-variance trade-off. The guide says a larger kk suppresses noise but makes class boundaries less distinct. With k=1k=1 the prediction follows every flipped label, like the single deep tree of the previous lesson. Each training row is its own nearest neighbour, so 1-NN scores perfectly on its training data (unless identical rows carry different labels): choose kk on validation data. The script flips 15% of the labels of a disc (best possible accuracy 0.85), trains on 200 rows, and reports median validation accuracy over 40 datasets: 0.723 for k=1k=1, 0.792 for 5, 0.791 for 15 and 0.747 for 51.

Scale decides who the neighbours are. Euclidean distance adds squared differences, so a column in large units dominates it. On a clean disc, 5-NN scores 0.950 with the two real columns and 0.883 with one extra noise column on the same scale. Multiplying that noise column by 100 gives 0.530, below the 0.607 you get by always answering “outside the disc” (derived: the disc covers 39% of the square). Scale the columns before any distance-based method, with the scaler fitted on training data only.

The curse of dimensionality

In high dimensions the nearest and farthest points become almost equally far. Beyer, Goldstein, Ramakrishnan and Shaft showed that under a broad set of conditions the distance to the nearest point approaches the distance to the farthest as dimension grows, with the effect appearing in their experiments at as few as 10 to 15 dimensions. They add that this does not mean high-dimensional search is never meaningful, and identify workloads where the effect does not occur (Beyer et al., 1999).

A reason for random data, derived: a squared distance is a sum of dd per-column terms, so its mean grows like dd but its spread like d\sqrt d. The script compares one random query with 200 uniform points in [0,1]d[0,1]^d (median of 10 queries):

Dimension ddnearest / farthest distance
20.04
100.37
1000.74
1,0000.91

At d=1000d=1000 the nearest point is 91% as far away as the farthest.

Irrelevant columns do the same damage. Adding noise columns to the clean disc (5-NN, median of 40 datasets): 2 give 0.833, 8 give 0.645 and 32 give 0.560, below the 0.607 you get by always answering “outside”. The remedies keep fewer or better columns: feature selection, PCA (below), scaling, more data, or a model that learns which columns matter (judgment).

k-means: the Lloyd loop

k-means splits rows into kk groups by minimising the inertia, the within-cluster sum of squared distances to each cluster’s mean (scikit-learn, Clustering). The classical algorithm, Lloyd’s, alternates two steps. Assign every row to its nearest centre. Update every centre to the mean of its rows. Repeat until nothing changes.

Diagram: k-means picks starting centres, assigns each row to the nearest one, moves each centre to the mean of its rows, and repeats until no...

yes

no

Choose k starting centres

Assign each row to its nearest centre

Move each centre to the mean of its rows

Did any assignment change?

Stop: a local optimum

Diagram summary: k-means picks starting centres, assigns each row to the nearest one, moves each centre to the mean of its rows, and repeats until no assignment changes. The result is a local optimum that depends on the starting centres.

Why does it stop? Each step can only lower the inertia JJ: for fixed centres, the nearest centre minimises each row’s term, and for fixed assignments the mean minimises the squared distances. The Stanford CS229 notes call this coordinate descent on JJ: it falls monotonically and converges, but JJ is not convex, so the end point may be a local optimum, and the notes suggest running k-means many times and keeping the lowest JJ (CS229 notes). The script asserts in 1,000 runs that JJ never rose.

Worked example: the loop by hand

Six points on a line: 1, 2, 4, 9, 10, 12. Start with centres 1 and 2. The script uses exact fractions.

IterationCentresAssignmentJJNew centres
11, 21 to the first; 2, 4, 9, 10, 12 to the second2171, 37/5
21, 37/51, 2, 4 to the first; 9, 10, 12 to the second1012/25 = 40.487/3, 31/3
37/3, 31/3the same28/3 = 9.33unchanged: stop

In iteration 2 the points 2 and 4 both switch to the first centre: 2 is 1 from it and 5.4 from the second, and 4 is 3 from it and 3.4 from the second. Each pass costs nknk distance computations, which is why scikit-learn’s notes call k-means one of the fastest clustering algorithms available, while warning that it falls into local minima (KMeans).

Initialisation and restarts

Where the centres start decides which local optimum you reach. k-means++ picks the first centre at random, then each next centre with probability proportional to its squared distance from the nearest centre already chosen. Arthur and Vassilvitskii prove this seeding is O(log⁡k)O(\log k)-competitive with the optimal clustering and report better speed and accuracy (k-means++, 2007). Scikit-learn uses a greedy variant by default and, with n_init="auto", makes 1 start for k-means++ and 10 for random starts.

The script builds five blobs, two pairs close together, and runs each start type 500 times with one start per run. The median final JJ is 293.8 for both, also the best value seen. The difference is in the tail:

StartRuns within 1% of the best JJ seenWorst JJ
Random rows0.72898.1
k-means++0.87709.9

k-means++ raised the share of good runs from 72% to 87% and did not remove bad ones: its worst run ended at 2.4 times the best JJ. So use k-means++ and restart several times, keeping the lowest JJ.

Choosing k

Inertia falls as kk grows and is zero when every row is its own cluster, so you cannot simply minimise it. Two common checks are the elbow (where the drop slows) and the silhouette, s=(b−a)/max⁡(a,b)s=(b-a)/\max(a,b) per row, with aa the mean distance to the row’s own cluster and bb to the nearest other cluster (scikit-learn, Clustering); from the formula ss lies between -1 and 1. Four blobs 6 apart (50 rows each, spread 1), best of 5 starts per kk:

k2345678
Inertia21931219403357322282248
Silhouette0.4600.5330.6720.5880.4960.4250.354

Both point to k=4k=4, the true number: inertia drops by about 815 from 3 to 4 and by 46 from 4 to 5, and the silhouette peaks at 4. Real data rarely has so clean a knee, and the scikit-learn guide only points to silhouette analysis as an example, not a rule for choosing kk. Treat these as evidence alongside stability across restarts and whether the clusters are useful for the decision they feed (judgment).

When k-means fails

Each failure follows from the objective.

Non-convex shapes. The scikit-learn guide says inertia assumes convex, isotropic clusters and responds poorly to elongated or irregular shapes. The script makes two concentric rings (radii 1 and 3, 150 points each). The purity of a clustering is the share of rows in the majority true class of their cluster. For k-means with k=2k=2 the median purity is 0.522, a coin flip: it cuts the plane in two and ignores the rings.

Unscaled columns. Two blobs 4 apart in column 1, plus a pure-noise column 2 with standard deviation 50, give purity 0.520 raw and 0.970 after standardising (median of 30 datasets). Standardising equalises units; it does not judge relevance.

Outliers. A mean is pulled by extreme values, and squared distance makes a far point very costly. Two blobs 8 apart plus a single outlier at (0, 100), with k=2k=2: in 30 of 30 datasets the outlier took a cluster to itself and the 200 real rows merged into the other. The objective prefers this: attaching the outlier to a blob costs about 1002=10,000100^2=10{,}000 in inertia, merging the blobs only about 3,600 (200 rows times 42+1+14^2+1+1), both derived. Remove or cap outliers first, or use a method that labels noise.

Hierarchical clustering and DBSCAN in brief

Hierarchical (agglomerative) clustering starts with every row as its own cluster and repeatedly merges the closest pair. The linkage defines “closest”: Ward minimises the total within-cluster squared distance, complete uses the largest pairwise distance, average the mean, single the smallest (scikit-learn, Clustering). The merges form a tree called a dendrogram; cutting it at any level gives that many clusters, so kk need not be fixed in advance. The guide warns that the method is expensive without connectivity constraints, and that single linkage is the worst strategy for even cluster sizes. In the script, single linkage cut to two clusters separates the rings (median purity 1.000) by following chains of nearby points. Whether a thin bridge of noise points merges clusters the same way was not tested (judgment).

DBSCAN treats clusters as dense regions separated by sparse ones. A row is a core sample if at least min_samples rows (the scikit-learn reference says this includes the row itself) lie within eps; clusters grow from core samples, and rows farther than eps from every core sample are noise (-1). Shapes are free and there is no kk, but the guide says eps is crucial and usually cannot be left at its default. On the rings, with min_samples 5 (median of 30 datasets):

epsClusters found (median)Noise points (median)
0.31232
0.551
0.820

Purity is 1.000 for all three, since every small cluster is still pure, so count the clusters too. One eps also cannot suit regions of very different density: the guide says DBSCAN assumes the density requirement is globally homogeneous and may struggle with clusters of different densities, which HDBSCAN is designed to relax (not tested here).

PCA: centre, covariance, eigenvectors

PCA looks for the direction in which the data varies most, then the next direction at a right angle to it, and so on. Keeping the first few gives a compressed version of the data that retains as much variance as possible. The steps:

  1. Centre each column by subtracting its mean. Scikit-learn centres but does not scale (PCA); the CS229 notes also divide by the standard deviation unless the columns share units, such as pixel intensities (CS229 PCA notes).
  2. Covariance Σ=1n−1Xc⊤Xc\Sigma=\frac{1}{n-1}X_c^{\top}X_c.
  3. Eigen-decomposition of Σ\Sigma. The top eigenvector is the direction of maximum projected variance, and the top kk span the best kk-dimensional subspace (CS229 PCA notes). Libraries use the SVD of the centred data, which gives the same directions (derived).
  4. Ratio of a component: its eigenvalue over the sum of all eigenvalues.
  5. Project: scores Z=XcVkZ=X_cV_k.

Worked example: six points by hand

Take the points (8,18), (9,19), (10,21), (10,22), (11,20), (12,20). The means are 10 and 20. Centred, the covariance matrix (dividing by 5) is exactly

Σ=(2112)\Sigma=\begin{pmatrix}2&1\\1&2\end{pmatrix}

Multiplying shows Σ(1,1)⊤=(3,3)⊤\Sigma(1,1)^{\top}=(3,3)^{\top}, so (1,1)(1,1) is an eigenvector with eigenvalue 3, and Σ(1,−1)⊤=(1,−1)⊤\Sigma(1,-1)^{\top}=(1,-1)^{\top} gives eigenvalue 1. The ratios are 3/4 and 1/4. The first component is (1,1)/2(1,1)/\sqrt2; the scores times 2\sqrt2 are -4, -2, 1, 2, 1, 2. Dropping the second component leaves a squared error of exactly 5, which is (n−1)(n-1) times the dropped eigenvalue, 5×15\times1. The script checks each step with fractions.

How many components

Add up the sorted ratios and keep enough components to reach a target such as 90% or 95%. Scikit-learn accepts a number between 0 and 1 as n_components (with the full solver) and selects the number of components needed for the explained variance to exceed it. The script builds five columns from two hidden factors plus small noise (500 rows): the ratios are 0.645, 0.329, then 0.009, 0.009 and 0.008, so the cumulative share is 0.974 after two components.

A useful identity: the squared reconstruction error summed over rows and columns, divided by n−1n-1, equals the sum of the dropped eigenvalues. Keeping 1, 2 and 3 components leaves 10.2990, 0.7595 and 0.4886, matching the dropped eigenvalues in the script. A variance threshold is a judgment; the better test is whether the downstream validation score survives. Fit PCA on training data only.

When PCA misleads

Units. A column with a large scale has a large variance and captures the first component whether or not it matters. Take two correlated columns with spread near 1 and an independent column with standard deviation 1,000. Raw, the first component carries 0.999998 of the variance and loads only on the big column. Standardised, it carries 0.605 and loads (0.706, 0.707, 0.036) on the two correlated columns. Pixel intensities share units and need no scaling; height and income do not.

Signal in a quiet direction. PCA never sees the labels. In the script, column 1 is noise with standard deviation 10 and column 2 carries the class as plus or minus 1 with spread 0.3. PC1 is column 1: 5-NN on PC1 alone scores 0.508, a coin flip. PC2 alone scores 1.000, and both original columns 0.948. Keeping only the high-variance component would have thrown the signal away.

Curved structure and readability. PCA is linear, so it does not flatten a curved shape, and its components are dense mixtures of all columns (the scikit-learn guide notes their exclusively dense expressions), which is hard to read.

Beyond k-means and PCA

Gaussian mixtures. A Gaussian mixture model (GMM) assumes the data come from a mixture of Gaussians, and the scikit-learn guide describes it as generalising k-means by also modelling covariance (spherical, diagonal, tied or full) (scikit-learn, Gaussian mixtures). Expectation-maximisation (EM) fits it: the E step gives every point a probability for each component (a soft assignment), the M step refits the parameters to maximise the likelihood, and repeating converges to a local optimum. Scikit-learn starts from k-means by default, BIC can choose the number of components (recovering the true number only asymptotically), and covariances need regularising when components have too few points. So “k-means or GMM” is hard against soft assignment and balls against ellipses, paid for with more parameters.

Anomalies without labels. Isolation Forest repeatedly picks a random feature and split value; the average path length needed to isolate a point is the normality score, and anomalies get noticeably shorter paths (outlier detection; IsolationForest). The guide separates outlier detection (training data may contain outliers) from novelty detection (clean training data, judging new points). PCA gives another score: by the identity above, a row’s reconstruction error is its squared coordinate in the dropped directions, so rows far from the main subspace score high (derived, not tested). Validate any score on a small labelled review set (judgment).

t-SNE and UMAP. t-SNE is for visualising data in two or three dimensions. Its objective is not convex, so seeds give different embeddings; global structure is not explicitly preserved; TSNE has no transform for new rows; and the reference recommends reducing very high-dimensional data first with PCA or TruncatedSVD, for example to 50 dimensions (manifold learning; TSNE). Islands in a t-SNE plot are therefore not segments to use as features. UMAP can transform new data (UMAP transform), but it does not completely preserve density and can create false tears in clusters, so cluster on its output with care (UMAP clustering). Kernel PCA is a non-linear option that supports transform (decomposition); autoencoders, the neural counterpart of PCA, come later in the course.

Support vector machines

The linear models of the second lesson can use the log loss, which keeps rewarding confidence on points already correct. An SVM uses the hinge loss, which stops at a margin of 1, so only points near or past the boundary shape the model. With score f(x)=w⊤x+bf(x)=w^{\top}x+b and labels y∈{−1,+1}y\in\{-1,+1\}, the margin of a point is y f(x)y\,f(x). Scikit-learn gives the linear SVM objective as

min⁡w,b 12w⊤w+C∑i=1nmax⁡(0, 1−yif(xi))\min_{w,b}\ \tfrac12 w^{\top}w + C\sum_{i=1}^{n}\max\big(0,\,1-y_i f(x_i)\big)

(scikit-learn, Support Vector Machines). The first term wants a small ∥w∥\|w\|, a wide margin: the distance between the lines f=−1f=-1 and f=+1f=+1 is 2/∥w∥2/\|w\| (derived). The second charges the hinge loss for every point inside the margin or on the wrong side. CC is the price of a violation: low CC makes the decision surface smooth and high CC aims to classify all training points correctly (the guide). Dividing by CnCn gives the mean hinge loss plus λ∥w∥2/2\lambda\|w\|^2/2 with λ=1/(Cn)\lambda=1/(Cn) (derived): the ridge trade-off from the first lesson with a different loss. LinearSVC uses the squared hinge loss, so its numbers differ slightly.

The script fits this objective by stochastic subgradient descent, so its fits are approximate (it shrinks the intercept along with ww, as LinearSVC does). Two blobs centred 3 apart with spread 1, 200 training rows, median of 15 datasets:

CCMargin width 2/∥w∥2/\|w\|Points with margin at most 1Validation accuracy
0.012.98970.932
0.11.58500.930
11.08330.930
100.69250.928

A higher CC narrows the margin and leaves fewer points inside it. Validation accuracy differs by less than 0.01, so on this easy data there is no clear winner. Points with margin above 1 have zero hinge loss and zero gradient, so only the others shape the fit. In an exact solution these are the support vectors; the guide notes that using a subset of the training points makes the SVM memory efficient.

Kernels in brief

A linear boundary cannot separate a disc from its surroundings, but lifting the data helps: add the column x12+x22x_1^2+x_2^2 and the disc becomes a threshold on one coordinate. In the script a linear SVM on the clean disc scores 0.604, exactly the majority-class rate, and 0.978 with the extra column (median of 30 datasets). A kernel gives the same effect without building the lifted columns, by computing inner products of lifted points directly. For the degree-2 polynomial kernel, expanding the product gives (x⋅z)2=x12z12+2x1x2z1z2+x22z22(x\cdot z)^2=x_1^2z_1^2+2x_1x_2z_1z_2+x_2^2z_2^2, the dot product of the lifted vectors (x12,2x1x2,x22)(x_1^2,\sqrt2x_1x_2,x_2^2) and (z12,2z1z2,z22)(z_1^2,\sqrt2z_1z_2,z_2^2) (derived). Scikit-learn offers linear, polynomial, RBF and sigmoid kernels, and the CS229 notes say kernels let SVMs work efficiently in very high or infinite-dimensional feature spaces (CS229 notes).

From the scikit-learn guide: SVMs are not scale invariant, so apply the same scaling at test time; kernel SVC fit time grows between n2n^2 and n3n^3 times the number of features, while LinearSVC scales almost linearly to millions of rows; probabilities need an expensive five-fold cross-validation.

Naive Bayes

Bayes’ rule says P(y∣x)∝P(y) P(x∣y)P(y\mid x)\propto P(y)\,P(x\mid y). Modelling P(x∣y)P(x\mid y) over all feature combinations needs exponentially many parameters; the CS229 notes work through a 50,000-word vocabulary where this is hopeless (CS229 generative notes). Naive Bayes assumes the features are conditionally independent given the class, so

P(y∣x) ∝ P(y)∏j=1dP(xj∣y)P(y\mid x)\ \propto\ P(y)\prod_{j=1}^{d}P(x_j\mid y)

and each factor is estimated separately: about dd numbers per class (derived). Scikit-learn names the assumption as conditional independence between every pair of features given the class (scikit-learn, Naive Bayes).

Worked example: spam by hand

Vocabulary: buy, free, meeting. Spam messages: “buy free free”, “free buy”. Ham messages: “meeting”, “buy meeting meeting”, “free meeting”. Word counts are (2, 3, 0) for spam (total 5) and (1, 1, 4) for ham (total 6); the priors are 2/5 and 3/5. The multinomial estimate with smoothing α\alpha is θ^yi=(Nyi+α)/(Ny+αn)\hat\theta_{yi}=(N_{yi}+\alpha)/(N_y+\alpha n) for n=3n=3 words (the guide’s formula); a message’s score is the prior times the product of its word probabilities.

Messageα\alphaSpam scoreHam scoreP(spam)
free buy012/1251/60144/169 = 0.852
free buy13/404/13581/113 = 0.717
meeting free001/150
meeting free11/402/2727/107 = 0.252

Without smoothing, “meeting” never appeared in spam, so any message containing it is ruled out as spam however spammy its other words are. Laplace smoothing (α=1\alpha=1) gives unseen words a small probability; the guide says it prevents zero probabilities.

Why it works when the assumption is false

Words are not independent, yet the scikit-learn guide says naive Bayes has worked quite well in many real-world situations, famously document classification and spam filtering, and calls it a bad estimator whose predict_proba outputs are not to be taken too seriously. Classification only asks which class scores higher. The log score is a sum of one piece of evidence per feature, and correlated features repeat evidence: that inflates confidence, but the sign of the sum can stay the same.

The script tests this with 8 binary features, each agreeing with the label 65% of the time and independent given the label (300 training rows, 50 datasets):

FeaturesAccuracyMean stated confidence
8 distinct0.8000.810
Each copied 3 times0.8000.928
First feature copied 20 times0.6501.000

Copying every feature three times left the accuracy at 0.800 and raised the stated confidence to 0.928 (with balanced classes, tripling every term triples the log-odds and keeps its sign, derived). Copying one feature 20 times let it outvote the other seven: accuracy fell to 0.650, that of the single feature, with confidence 1.000. Naive Bayes survives evenly spread duplication and fails when one correlated group dominates.

Choosing between classical models

No method wins everywhere. Scaling and probability entries come from the sources and scripts above; the “reach for” and “breaks when” columns are judgment.

ModelReach for it whenBreaks whenNeeds scaling?Probabilities?
Regularised linear or logisticYou need a baseline, a coefficient story, speedThe boundary is strongly curved and you have no features for itYes, for regularisation and optimisationYes (logistic)
k-NNSmall data, few meaningful columns, a quick baselineMany columns, large nn, strict latencyYesVote fractions only
Linear SVMMany sparse columns, medium to large nnYou need probabilities without extra workYesNo, extra step
Kernel SVMMedium data and a curved boundaryVery large nnYesNo, extra step
Naive BayesText, tiny data, a baseline in minutesYou need trustworthy probabilitiesGaussian: no (derived: a rescaled column rescales every class’s likelihood equally). Multinomial or Bernoulli: rescaling a count column changes its weight (derived)Overconfident
Trees and ensemblesMixed-type tabular dataExtrapolation, tiny data (trees lesson)NoCheck calibration

A defensible workflow (judgment): list the constraints (rows, columns, latency, probabilities, explanation), fit a regularised linear baseline, add one flexible model, and compare both on the same validation folds.

Code

This standard-library script produced every number in the lesson (Python 3.14.6, about 8 seconds). It builds k-NN, k-means with k-means++, DBSCAN, single-linkage clustering, a silhouette score, PCA by Jacobi eigen-decomposition, a subgradient SVM and naive Bayes from scratch, with Fraction for the hand examples and fixed seeds for the random ones. Another Python version may draw different random numbers, moving decimals but not orderings.

Python

import math
import random
import statistics
from fractions import Fraction as Fr

d2 = lambda a, b: math.dist(a, b) ** 2
med = lambda v: round(statistics.median(v), 3)
mean_pt = lambda pts: [sum(c) / len(pts) for c in zip(*pts)]

def blobs(centers, n, sd, rng):
    X = [[rng.gauss(m, sd) for m in c] for c in centers for _ in range(n)]
    return X, [lab for lab in range(len(centers)) for _ in range(n)]

def purity(lab, y):                       # share of points in the majority true class of their cluster (noise = one cluster)
    return sum(max(sum(l == c and t == k for l, t in zip(lab, y)) for k in set(y)) for c in set(lab)) / len(y)

# ---------- 1. k-NN: distance concentration, the choice of k, noise columns, scale ----------
def disc(seed, n, flip=0.0, noise_scales=()):          # label 1 inside a disc; optional extra noise columns
    r = random.Random(seed)
    X = [[r.uniform(-1, 1), r.uniform(-1, 1)] for _ in range(n)]
    y = [int(a * a + b * b < 0.5) ^ (r.random() < flip) for a, b in X]
    return [x + [r.uniform(-1, 1) * s for s in noise_scales] for x in X], y

def knn_acc(Xtr, ytr, Xte, yte, ks):
    hits = dict.fromkeys(ks, 0)
    for x, t in zip(Xte, yte):
        order = sorted(range(len(Xtr)), key=lambda i: d2(x, Xtr[i]))
        for k in ks:
            hits[k] += (sum(ytr[i] for i in order[:k]) * 2 > k) == t
    return {k: h / len(yte) for k, h in hits.items()}

print("1a. 200 uniform points in [0,1]^d, median over 10 queries")
for d in (2, 10, 100, 1000):
    r = random.Random(d)
    P = [[r.random() for _ in range(d)] for _ in range(200)]
    runs = []
    for _ in range(10):
        q = [r.random() for _ in range(d)]
        ds = [math.dist(q, p) for p in P]
        runs.append(min(ds) / max(ds))
    print("   d=%-5d nearest/farthest %.3f" % (d, med(runs)))

res = {k: [] for k in (1, 5, 15, 51)}
for s in range(40):
    for k, a in knn_acc(*disc(s, 200, 0.15), *disc(100 + s, 1000, 0.15), tuple(res)).items():
        res[k].append(a)
print("1b. disc with 15% flipped labels (ceiling 0.85), 200 train rows, median validation accuracy by k:",
      {k: med(v) for k, v in res.items()})
print("1c. 5-NN validation accuracy on a clean disc plus extra columns of uniform noise (median of 40 datasets)")
for label, scales in (("no extra columns", ()), ("2 noise columns", (1,) * 2), ("8 noise columns", (1,) * 8),
                      ("32 noise columns", (1,) * 32), ("1 noise column, scale 1", (1,)), ("1 noise column, scale 100", (100,))):
    print("   %-28s %.3f" % (label, med(knn_acc(*disc(s, 200, 0, scales), *disc(100 + s, 300, 0, scales), (5,))[5] for s in range(40))))

# ---------- 2. k-means, DBSCAN, single linkage, silhouette ----------
def kmeans(X, k, rng, plus=True):
    C = [rng.choice(X)] if plus else rng.sample(X, k)
    while plus and len(C) < k:                                    # k-means++: next centre drawn with weight D(x)^2
        C.append(rng.choices(X, weights=[min(d2(x, c) for c in C) for x in X])[0])
    C, hist = [c[:] for c in C], []
    for _ in range(100):
        lab = [min(range(k), key=lambda j: d2(x, C[j])) for x in X]                    # assign
        hist.append(sum(d2(x, C[l]) for x, l in zip(X, lab)))
        new = [mean_pt([x for x, l in zip(X, lab) if l == j]) if j in lab else C[j] for j in range(k)]   # update
        if new == C:
            break
        C = new
    return C, lab, hist

def best_of(X, k, starts=5):
    return min((kmeans(X, k, random.Random(s)) for s in range(starts)), key=lambda t: t[2][-1])

def dbscan(X, eps, m):
    n, lab, cid = len(X), [None] * len(X), -1
    nb = [[j for j in range(n) if d2(X[i], X[j]) <= eps * eps] for i in range(n)]
    for i in range(n):
        if lab[i] is not None or len(nb[i]) < m:
            continue
        cid += 1
        lab[i], stack = cid, [i]
        while stack:
            for j in nb[stack.pop()]:
                if lab[j] is None:
                    lab[j] = cid
                    if len(nb[j]) >= m:
                        stack.append(j)
    return [-1 if l is None else l for l in lab]

def single_linkage(X, k):                                         # merge the closest pair of clusters until k remain
    parent, comps = list(range(len(X))), len(X)

    def find(a):
        while parent[a] != a:
            a = parent[a] = parent[parent[a]]
        return a
    for _, i, j in sorted((d2(X[i], X[j]), i, j) for i in range(len(X)) for j in range(i)):
        if find(i) != find(j):
            parent[find(i)] = find(j)
            comps -= 1
            if comps == k:
                break
    return [find(i) for i in range(len(X))]

def silhouette(X, lab):
    out = []
    for i, x in enumerate(X):
        by = {}
        for j, z in enumerate(X):
            if j != i:
                by.setdefault(lab[j], []).append(math.dist(x, z))
        a = statistics.fmean(by.pop(lab[i]))
        out.append((min(statistics.fmean(v) for v in by.values()) - a) / max(a, min(statistics.fmean(v) for v in by.values())))
    return statistics.fmean(out)

xs, C = [Fr(v) for v in (1, 2, 4, 9, 10, 12)], [Fr(1), Fr(2)]     # 2a. the loop by hand, exact
for it in range(1, 5):
    lab = [min((0, 1), key=lambda j: abs(x - C[j])) for x in xs]
    new = [sum(x for x, l in zip(xs, lab) if l == j) / lab.count(j) for j in (0, 1)]
    print("2a. iteration", it, "centres", [str(c) for c in C], "assign", lab,
          "J", sum((x - C[l]) ** 2 for x, l in zip(xs, lab)), "-> new centres", [str(c) for c in new])
    if new == C:
        break
    C = new

X, _ = blobs([(0, 0), (4, 0), (8, 0), (0, 5), (4, 5)], 50, 0.8, random.Random(1))      # 2b. initialisation, 5 blobs
runs = {}
for name, plus in (("random start", False), ("k-means++", True)):
    for s in range(500):
        hist = kmeans(X, 5, random.Random(s), plus)[2]
        assert all(a >= b - 1e-9 for a, b in zip(hist, hist[1:])), "J must never increase"
        runs.setdefault(name, []).append(hist[-1])
best = min(min(v) for v in runs.values())
for name, v in runs.items():
    print("2b. %-12s one start per run, 500 runs: median J %.1f, worst %.1f, within 1%% of the best J seen (%.1f): %.2f of runs"
          % (name, statistics.median(v), max(v), best, sum(j <= 1.01 * best for j in v) / len(v)))
print("    J never rose in any iteration of the 1,000 runs (asserted)")

X, _ = blobs([(0, 0), (6, 0), (0, 6), (6, 6)], 50, 1.0, random.Random(2))               # 2c. choosing k, 4 blobs
print("2c. k: inertia (best of 5 starts), silhouette")
for k in range(2, 9):
    _, lab, hist = best_of(X, k)
    print("   %d: %8.1f  %.3f" % (k, hist[-1], silhouette(X, lab)))

def rings(seed, n=150):
    r = random.Random(seed)
    ang = [r.uniform(0, 2 * math.pi) for _ in range(2 * n)]
    return ([[(1 + 2 * (i >= n)) * f(a) + r.gauss(0, 0.1) for f in (math.cos, math.sin)] for i, a in enumerate(ang)],
            [int(i >= n) for i in range(2 * n)])

out = {"k-means": [], "single linkage": [], 0.3: [], 0.5: [], 0.8: []}                  # 2d. failures
for s in range(30):
    X, y = rings(s)
    out["k-means"].append(purity(best_of(X, 2)[1], y))
    out["single linkage"].append(purity(single_linkage(X, 2), y))
    for eps in (0.3, 0.5, 0.8):
        db = dbscan(X, eps, 5)
        out[eps].append((len(set(db) - {-1}), db.count(-1), purity(db, y)))
print("2d. two rings (radii 1 and 3, 150 points each), median of 30 datasets: purity k-means %.3f, single linkage %.3f"
      % (med(out["k-means"]), med(out["single linkage"])))
for eps in (0.3, 0.5, 0.8):
    print("    DBSCAN eps %.1f, min_samples 5: clusters %s, noise points %s, purity %.3f" % ((eps,) + tuple(med(c) for c in zip(*out[eps]))))

raw, std, alone, share = [], [], 0, []
for s in range(30):
    r = random.Random(s)
    X, y = blobs([(0,), (4,)], 100, 1.0, r)
    X = [[a[0], r.gauss(0, 50)] for a in X]                      # column 2 is pure noise, in large units
    mu, sd = mean_pt(X), [statistics.pstdev(c) for c in zip(*X)]
    raw.append(purity(best_of(X, 2, 3)[1], y))
    std.append(purity(best_of([[(v - m) / q for v, m, q in zip(x, mu, sd)] for x in X], 2, 3)[1], y))
    X, y = blobs([(0, 0), (8, 0)], 100, 1.0, random.Random(s))
    lab = best_of(X + [[0.0, 100.0]], 2)[1]                      # one outlier far above the first blob
    alone += lab.count(lab[-1]) == 1
    share.append(max(lab[:200].count(0), lab[:200].count(1)) / 200)
print("    column 2 pure noise with sd 50, blobs 4 apart in column 1: median purity raw %.3f, standardised %.3f" % (med(raw), med(std)))
print("    two blobs 8 apart plus one outlier at (0, 100), k=2: outlier alone in its own cluster in %d of 30 datasets; "
      "median share of the 200 blob points in the larger cluster %.2f" % (alone, med(share)))

# ---------- 3. PCA: centre, covariance, eigenvectors, project ----------
def jacobi_eigh(A):                       # eigenvalues (descending) and eigenvectors (rows) of a symmetric matrix
    n, A = len(A), [r[:] for r in A]
    V = [[float(i == j) for j in range(n)] for i in range(n)]
    for _ in range(60):
        if sum(A[i][j] ** 2 for i in range(n) for j in range(n) if i != j) < 1e-24:
            break
        for p in range(n):
            for q in range(p + 1, n):
                if A[p][q] == 0:
                    continue
                th = (A[q][q] - A[p][p]) / (2 * A[p][q])
                t = (1 if th >= 0 else -1) / (abs(th) + math.sqrt(th * th + 1))
                c = 1 / math.sqrt(t * t + 1)
                s = t * c
                for M in (A, V):                                   # rotate columns p and q
                    for k in range(n):
                        M[k][p], M[k][q] = c * M[k][p] - s * M[k][q], s * M[k][p] + c * M[k][q]
                for k in range(n):                                 # rotate rows p and q of A
                    A[p][k], A[q][k] = c * A[p][k] - s * A[q][k], s * A[p][k] + c * A[q][k]
    order = sorted(range(n), key=lambda i: -A[i][i])
    return [A[i][i] for i in order], [[V[k][i] for k in range(n)] for i in order]

def pca(X):                               # centre, covariance with n - 1, eigen-decompose
    mu = mean_pt(X)
    Xc = [[v - m for v, m in zip(x, mu)] for x in X]
    S = [[sum(r[i] * r[j] for r in Xc) / (len(X) - 1) for j in range(len(mu))] for i in range(len(mu))]
    return (mu, Xc) + jacobi_eigh(S)

raw = [(8, 18), (9, 19), (10, 21), (10, 22), (11, 20), (12, 20)]                   # 3a. by hand, exact
mu = [Fr(sum(p[i] for p in raw), 6) for i in (0, 1)]
Xc = [[Fr(p[i]) - mu[i] for i in (0, 1)] for p in raw]
S = [[sum(r[i] * r[j] for r in Xc) / 5 for j in (0, 1)] for i in (0, 1)]
print("3a. mean", [str(m) for m in mu], "covariance (n - 1)", [[str(v) for v in r] for r in S])
for lam, v in ((3, (1, 1)), (1, (1, -1))):
    print("    S @ %s = %s, which is %d times the vector" % (v, [str(S[i][0] * v[0] + S[i][1] * v[1]) for i in (0, 1)], lam))
print("    scores on (1,1)/sqrt2, times sqrt2:", [str(r[0] + r[1]) for r in Xc],
      "| squared error of the 1-component fit", sum((r[0] - r[1]) ** 2 / 2 for r in Xc), "= (n - 1) x dropped eigenvalue =", 5 * 1)

r = random.Random(3)                                                                # 3b. five columns, two hidden factors
U = [(1, 1, 0.5, 0, 0), (0, 0, 0.5, 1, 1)]
F = [(r.gauss(0, 3), r.gauss(0, 2)) for _ in range(500)]
X = [[f[0] * U[0][j] + f[1] * U[1][j] + r.gauss(0, 0.5) for j in range(5)] for f in F]
_, Xc, vals, vecs = pca(X)
ratios = [v / sum(vals) for v in vals]
print("3b. eigenvalues", [round(v, 3) for v in vals], "ratios", [round(v, 3) for v in ratios],
      "cumulative", [round(sum(ratios[:k + 1]), 3) for k in range(5)])
for k in (1, 2, 3):
    sse = sum(d2(x, [sum(sum(a * b for a, b in zip(x, v)) * v[j] for v in vecs[:k]) for j in range(5)]) for x in Xc)
    print("    keep %d: squared error / (n - 1) = %.4f, sum of dropped eigenvalues = %.4f" % (k, sse / 499, sum(vals[k:])))

r = random.Random(4)                                                                # 3c. units matter
X = [[a, 0.8 * a + r.gauss(0, 0.6), r.gauss(0, 1000)] for a in (r.gauss(0, 1) for _ in range(500))]
sd = [statistics.pstdev(c) for c in zip(*X)]
for label, data in (("raw", X), ("standardised", [[(v - m) / q for v, m, q in zip(x, mean_pt(X), sd)] for x in X])):
    vals, vecs = pca(data)[2:]
    print("3c. %-12s PC1 share %.6f, PC1 loadings %s" % (label, vals[0] / sum(vals), [round(abs(c), 3) for c in vecs[0]]))

def hidden(seed, n):                      # column 1: big noise; column 2: the class signal, in a small-variance direction
    rr = random.Random(seed)
    y = [rr.randrange(2) for _ in range(n)]
    return [[rr.gauss(0, 10), 2 * t - 1 + rr.gauss(0, 0.3)] for t in y], y

acc = {"PC1 only": [], "PC2 only": [], "both columns": []}
for s in range(30):
    (X, y), (Xv, yv) = hidden(s, 150), hidden(100 + s, 300)
    mu, _, vals, vecs = pca(X)
    proj = lambda data, v: [[sum((a - m) * b for a, m, b in zip(x, mu, v))] for x in data]
    for i, name in ((0, "PC1 only"), (1, "PC2 only")):
        acc[name].append(knn_acc(proj(X, vecs[i]), y, proj(Xv, vecs[i]), yv, (5,))[5])
    acc["both columns"].append(knn_acc(X, y, Xv, yv, (5,))[5])
print("    5-NN validation accuracy when the signal sits in the low-variance direction:", {k: med(v) for k, v in acc.items()})

# ---------- 4. Support vector machine: hinge loss, margin, kernels ----------
def svm_fit(X, y, lam, epochs, rng):      # stochastic subgradient descent on lam/2 |w|^2 + mean hinge loss; bias = constant column
    w, t = [0.0] * (len(X[0]) + 1), 0
    for _ in range(epochs):
        for i in rng.sample(range(len(X)), len(X)):
            t += 1
            eta, x = 1 / (lam * t), X[i] + [1.0]
            hit = y[i] * sum(a * b for a, b in zip(w, x)) < 1
            w = [(1 - eta * lam) * a + (eta * y[i] * b if hit else 0.0) for a, b in zip(w, x)]
    return w

score = lambda w, x: sum(a * b for a, b in zip(w, x)) + w[-1]
two_class = lambda seed, n: (lambda X, y: (X, [2 * t - 1 for t in y]))(*blobs([(-1.5, 0), (1.5, 0)], n, 1.0, random.Random(seed)))
print("4a. linear SVM, two blobs centred at (-1.5, 0) and (1.5, 0), 200 train points, lam = 1 / (C n), median of 15 datasets")
for C in (0.01, 0.1, 1, 10):
    rows = []
    for s in range(15):
        (X, y), (Xv, yv) = two_class(s, 100), two_class(50 + s, 1000)
        w = svm_fit(X, y, 1 / (C * len(X)), 30, random.Random(s))
        m = [t * score(w, x) for x, t in zip(X, y)]
        rows.append((2 / math.hypot(*w[:2]), sum(v <= 1 for v in m), statistics.fmean(t * score(w, x) > 0 for x, t in zip(Xv, yv))))
    q = [med(c) for c in zip(*rows)]
    print("   C=%-5g margin width 2/|w| %.2f, points with margin <= 1: %3d, validation accuracy %.3f" % ((C,) + tuple(q)))

lift = lambda D: [x + [x[0] ** 2 + x[1] ** 2] for x in D]
res = {"linear": [], "with x1^2 + x2^2": [], "majority class": []}
for s in range(30):
    (Xd, yd), (Xe, ye) = disc(s, 300), disc(100 + s, 1000)
    yd, ye = [2 * t - 1 for t in yd], [2 * t - 1 for t in ye]
    for name, f in (("linear", lambda D: D), ("with x1^2 + x2^2", lift)):
        w = svm_fit(f(Xd), yd, 0.01, 20, random.Random(s))
        res[name].append(statistics.fmean(t * score(w, x) > 0 for x, t in zip(f(Xe), ye)))
    res["majority class"].append(max(ye.count(1), ye.count(-1)) / len(ye))
print("    disc data, validation accuracy of a linear SVM:", {k: med(v) for k, v in res.items()})

# ---------- 5. Naive Bayes ----------
words = ("buy", "free", "meeting")
train = {"spam": ["buy free free", "free buy"], "ham": ["meeting", "buy meeting meeting", "free meeting"]}
prior = {c: Fr(len(d), 5) for c, d in train.items()}
count = {c: [sum(t.split().count(w) for t in d) for w in words] for c, d in train.items()}
for alpha in (0, 1):
    theta = {c: [Fr(n + alpha, sum(v) + alpha * 3) for n in v] for c, v in count.items()}
    for msg in ("free buy", "meeting free"):
        sc = {c: prior[c] * math.prod(theta[c][words.index(w)] for w in msg.split()) for c in prior}
        print("5a. alpha=%d '%s': spam score %s, ham score %s, P(spam) = %s" % (alpha, msg, sc["spam"], sc["ham"], sc["spam"] / sum(sc.values())))

def nb_fit(X, y):
    return [[(sum(x[j] for x, t in zip(X, y) if t == c) + 1) / (y.count(c) + 2) for j in range(len(X[0]))] for c in (0, 1)]

def nb_p1(th, x):                         # P(class 1 | x) from the sum of per-feature log likelihood ratios
    lo = sum(math.log((th[1][j] if v else 1 - th[1][j]) / (th[0][j] if v else 1 - th[0][j])) for j, v in enumerate(x))
    return 1 / (1 + math.exp(-lo))

def votes(seed, n):                       # 8 binary features, each equal to the label with probability 0.65, independent given it
    r = random.Random(seed)
    y = [r.randrange(2) for _ in range(n)]
    return [[t if r.random() < 0.65 else 1 - t for _ in range(8)] for t in y], y

print("5b. 8 binary features, each agrees with the label 65% of the time, independent given the label; 50 datasets")
res = {}
for s in range(50):
    (X, y), (Xv, yv) = votes(s, 300), votes(100 + s, 3000)
    for name, f in (("8 distinct features", lambda x: x), ("each copied 3 times", lambda x: x * 3),
                    ("first feature copied 20 times", lambda x: x + x[:1] * 19)):
        th = nb_fit([f(x) for x in X], y)
        p = [nb_p1(th, f(x)) for x in Xv]
        res.setdefault(name, []).append((statistics.fmean((q > 0.5) == t for q, t in zip(p, yv)), statistics.fmean(max(q, 1 - q) for q in p)))
for name, v in res.items():
    print("   %-30s accuracy %.3f, mean stated confidence %.3f" % ((name,) + tuple(med(c) for c in zip(*v))))

Scikit-learn’s KNeighborsClassifier, KMeans, DBSCAN, PCA, SVC and MultinomialNB are the production versions; their numbers will differ.

Real-World Application

Scale first, inside a pipeline fitted on training data only. Use k-NN, naive Bayes and a linear model as baselines; for naive Bayes rank by its score and calibrate before using the number as a probability. Segment with k-means only after checking stability across restarts and that no outlier has taken a cluster. Use PCA to drop redundant columns and verify the downstream metric survives. Use DBSCAN when you need noise flagged and cannot say how many groups exist, and plan time to tune eps.

Interview Perspective

Expect “what is the curse of dimensionality”, “how do you choose k in k-means”, “when does k-means fail”, “walk me through PCA”, “when would PCA hurt”, “explain the SVM margin and the kernel trick”, “why does naive Bayes work when features are not independent”, “k-means or a Gaussian mixture” and “how would you detect anomalies with no labels”. A strong answer gives the mechanism with a small number or failure case; a weak one lists definitions.

Provenance: Common industry pattern. These are standard questions for ML roles, not a verified list for any named company.

Practice Questions

  • Basic: Run k-means by hand on the points 0, 1, 5, 6, 20 with starting centres 0 and 5, and report JJ after each assignment until it stops changing.
  • Intermediate: Your k-means segments change on every rerun. List three causes and a fix for each.
  • Advanced: PCA keeps 95% of the variance, yet a classifier on the scores is worse than on the raw columns. Give two explanations and a test for each.
  • Product-Company (Generated practice): A “similar listings” feature runs k-NN on 400 embedding columns plus price and area in raw units. What goes wrong, and how do you fix and evaluate it?

Activity

Run the script once. In 1c, predict the 5-NN accuracy with 4 noise columns before running it. In 2d, try eps 0.6 and 1.2. In 3c, raise the signal column’s spread from 0.3 and say how large it must be before the signal column becomes PC1 (about 10, since its variance is then about 1 plus the spread squared against 100 for the noise column). In 5b, copy the first feature 2 times and predict whether accuracy changes.

Homework

Implement the pieces of k-means and PCA in pure Python: assign, update, the Lloyd loop, the k-means++ choice of the next centre, and a two-column PCA with explained variance. The code is in homework/; run the tests until they pass.

Quick Revision

  • k-NN stores the data; choose kk on validation; scale columns; distances concentrate as dimension grows (nearest/farthest 0.04 at d=2d=2, 0.91 at d=1000d=1000).
  • k-means alternates assign and update and ends at a local optimum: use k-means++ and restarts; it fails on rings, unscaled columns and outliers. DBSCAN needs eps and flags noise.
  • PCA: centre, covariance, eigenvectors, project; it misleads on units, quiet signal and curved data.
  • SVM: 12∥w∥2+C∑\tfrac12\|w\|^2 + C\sum hinge; wide margin; kernels lift without building columns. Naive Bayes: per-feature evidence multiplied; decent decisions, overconfident probabilities.
  • GMM with EM is soft k-means with covariances; Isolation Forest isolates anomalies in few random splits; t-SNE is for plots only, not features.

Check yourself

  • Walk-through: Without notes, run Lloyd’s loop on six points and say why JJ cannot increase yet the answer can be bad.
  • Variation: A feature changes from metres to millimetres. What happens to k-NN, k-means, PCA, a kernel SVM and Gaussian naive Bayes?
  • Common misconception: “PCA keeps the important information” and “naive Bayes works because the features are independent”.

Resources & Further Reading

Checked sources to go deeper. The essential ones come first in each group.

Official documentation

Further reading

Research papers

More for this module: Trees, ensembles and classical models resources

Practice

Test what you just read. Quizzes and cards are grouped by module: Trees, ensembles and classical models.

Check yourself17 questions on what this lesson set out to teach

Checking answers needs JavaScript. You can still read every question and option below.

0 of 17 answered

Keyboard: arrow keys move between options. Space or Enter selects the focused option.

ObjectiveExplain k-nearest neighbours as a model that stores the data, how k trades bias against variance, and why distance concentrates in high dimensions so that irrelevant or unscaled columns wreck the neighbours.

  1. Question 1 of 17A rental-price classifier uses 5-NN on three columns: floor area in square metres (20 to 200), number of rooms (1 to 5) and distance to the nearest metro station in metres (50 to 5,000). Accuracy is poor and the neighbours it returns look similar only in metro distance. What is the most direct fix?

    Choose one answer.

  2. Question 2 of 17Which statements about k-nearest neighbours are true? Select all that apply.

    Choose all that apply.

  3. Question 3 of 17For 1,000 uniformly random points in 500 dimensions, an engineer finds that for a typical query the ratio (nearest distance) / (farthest distance) is about 0.85. What does this say about k-NN on data like this?

    Choose one answer.

  4. Question 4 of 17On a validation set of 1,000 rows, a k-NN fraud model has these results. k = 1: accuracy 0.72 (training accuracy 1.00). k = 15: 0.79. k = 301: 0.74. What should you conclude?

    Choose one answer.

ObjectiveRun the k-means loop by hand, explain why it reaches only a local optimum and what k-means++ and restarts change, choose k with inertia and silhouette, and name the cases where it fails (non-convex shapes, unscaled columns, outliers) with DBSCAN and hierarchical clustering as alternatives.

  1. Question 5 of 17Five points on a line: 0, 2, 3, 10, 11. k-means with k = 2 starts with centres at 2 and 3. After the first update step, what are the centres, and what happens in the next assignment step?

    Choose one answer.

  2. Question 6 of 17A customer-segmentation job gives different segments each night, although the data barely changes. Which statements are true? Select all that apply.

    Choose all that apply.

  3. Question 7 of 17A fraud analyst runs k-means with k = 3 on two columns: transaction amount (0 to 50,000) and number of items (1 to 10). The three clusters are simply low, middle and high amounts, whatever the item count. What is the cause and the first thing to try?

    Choose one answer.

  4. Question 8 of 17You must group GPS pings into regions. The regions are curved, such as a ring road and a river bank, their number is unknown, and about 5% of the pings are errors that should be flagged. Which approach fits best?

    Choose one answer.

  5. Question 15 of 17On a customer data set, k-means gives these inertias for k = 2 to 8: 900, 610, 190, 170, 155, 142, 131. The silhouette scores are 0.41, 0.49, 0.64, 0.52, 0.47, 0.40, 0.37. What do you report as the number of clusters, and how do you support it?

    Choose one answer.

ObjectiveCompute PCA by centring, covariance and eigen-decomposition, read the explained variance to pick the number of components, and say when PCA misleads (units, signal in low-variance directions, non-linear structure).

  1. Question 9 of 17After centring, two features have covariance matrix with rows (5, 2) and (2, 2). Its eigenvalues are 6 and 1. What share of the total variance does the first principal component explain?

    Choose one answer.

  2. Question 10 of 17Which statements about using PCA before a classifier are true? Select all that apply.

    Choose all that apply.

  3. Question 11 of 17A factory monitors 40 sensors. Reducing them to the 3 principal components that explain 98% of the variance leaves a fault detector with much lower recall. Engineers found that faults appear as small shifts in a combination of sensors that normally varies very little. What explains the drop?

    Choose one answer.

ObjectiveChoose between k-NN, a linear or kernel SVM, naive Bayes, trees and linear models for a case from its size, dimension, need for probabilities and need for explanation, using the margin and hinge loss for the SVM and the independence assumption for naive Bayes.

  1. Question 12 of 17You have 40,000 documents, about 20,000 sparse word-count columns, a binary label, and one day to ship a first baseline that ranks documents; calibrated probabilities are not needed yet. Which first model family is the best choice?

    Choose one answer.

  2. Question 13 of 17A linear SVM on a noisy two-class data set is retrained with C raised from 0.1 to 100, nothing else changed. What do you expect, and why?

    Choose one answer.

  3. Question 14 of 17In a naive Bayes spam filter, the single strongest word feature accidentally appears three times in the feature vector (the same count copied twice). Which statements are true? Select all that apply.

    Choose all that apply.

ObjectiveSay what Gaussian mixtures with EM, Isolation Forest, t-SNE and UMAP add to k-means and PCA, and why the clusters of a t-SNE plot are not features.

  1. Question 16 of 17A t-SNE plot of 40,000 customers shows six well-separated islands. A product manager wants to ship the island numbers as segment features in a production model, and to place next month's new customers by running t-SNE again on them alone. What is the main problem?

    Choose one answer.

  2. Question 17 of 17Which statements about Gaussian mixtures and unlabelled anomaly detection are true? Select all that apply.

    Choose all that apply.