Artificial Intelligence and Machine Learning · Lecture 12 of 16

Classification · Part 2

Classification and regression with nearest neighbors

Use nearby observations to classify or predict a number, then choose the number of neighbors through validation.

01Nearest-neighbor classification
02Class probabilities and regression
03Choosing K and comparing costs
5.7 · K-Nearest Neighbors

Parametric models learn coefficients

Choose a form

Polynomial, multiple and logistic regression each start with a chosen formula.

Fit its coefficients

For logistic regression, maximum likelihood estimates the coefficients from labelled data.

ℙ(Y=1∣X=xi)=σ(xi)
xᵢ = input for observation iσ(xᵢ) = fitted probability of class 1
5.7 · K-Nearest Neighbors

Parametric and nonparametric models

Parametric · Logistic regression

Choose a model form with a fixed number of coefficients.

Fit the coefficients on training data. For a new input, evaluate the fitted formula.

Nonparametric · KNN

Keep the labelled training examples.

For a new input, find its nearest examples and let their labels vote. As the dataset grows, KNN can represent more detailed decision boundaries.

K is a hyperparameter. It sets how many neighbors vote. It is chosen during model selection.
5.7 · K-Nearest Neighbors

K-Nearest Neighbors

Store the observations

Keep the training inputs and their labels.

Predict from nearby examples

Find the K nearest inputs. Their labels vote.

KNN is nonparametric. It uses the stored observations to predict.
K = chosen neighbor countTraining data 𝒟={(xi,yi)}i=1nn = number of training observations
Lecture map

What can we learn from nearby examples?

ChapterQuestion we will answer
5.7 · K-Nearest NeighborsWhat do nearby examples suggest for a new input?
5.7.1 · Bayesian derivationWhy does a neighbor fraction estimate a class probability?
5.7.2 · K-NN regressorWhat if the target is a number?
5.7.3 · ValidationHow do we choose K?
5.7.4 · CharacteristicsWhen is the method useful, and what does it cost?
5.7 · K-Nearest Neighbors

Read the two features and the known class

Each point has two predictors and a class label. The goal is to divide the plane into two regions, one for each class.

5.7 · K-Nearest Neighbors

The neighborhood contains the nearest examples’ targets

𝒩K(xi)={yi1,…,yiK}

Find the neighbors

Rank training inputs by their distance from xᵢ. Keep the closest K.

Collect their targets

K=5:𝒩5(xi)={0,1,1,0,1}

Each neighbor contributes one entry, including repeated labels.

xᵢ = query inputi₁, …, iₖ = indices of the selected observationsyᵢ₁, …, yᵢₖ = their observed targets
5.7 · K-Nearest Neighbors

Classify an input by the majority label nearby

y^i=argmaxc∈𝒴 ∑yj∈𝒩K(xi)𝟙(yj=c)

Count the votes

For each candidate class c, add 1 for each matching label yⱼ.

Choose the largest count

𝒩5(xi)={0,1,1,0,1}

Class 0 gets 2 votes. Class 1 gets 3, so ŷᵢ = 1.

ŷᵢ = predicted classc ∈ 𝒴 = candidate classyj∈𝒩K(xi) = selected training label𝟙(A) is 1 when A holds and 0 otherwise
5.7 · K-Nearest Neighbors

One nearest neighbor decides the new query’s class

With K = 1, the closest stored point supplies the label. The background shows the predicted class at every location.

5.7 · K-Nearest Neighbors

“Nearest” needs a distance between input measurements

‖xi−xj‖2=(xi1−xj1)2+(xi2−xj2)2

Euclidean distance

Square the feature differences, add them, and take the square root.

A small coordinate example

xi=(1,1),xj=(4,5)
‖xi−xj‖2=32+42=5
Euclidean distance is one choice. Feature units affect which inputs count as close.
xᵢ = query input, xⱼ = stored training inputxᵢ₁,xᵢ₂ = the two query feature valuesxⱼ₁,xⱼ₂ = the corresponding stored feature values‖xᵢ−xⱼ‖₂ = Euclidean distance between the inputs
5.7 · K-Nearest Neighbors

KNN: inspect the neighbors, then count their votes

Move the new input or change K. Read each selected neighbor’s distance and label, then follow the totals to the prediction. All feature values use the same synthetic scale.

5.7.1 · Bayesian derivation

From neighbor votes to class probabilities

With one vote per neighbor, the vote share from the previous example estimates the probability of a class for the new input.

ℙ(Y=c∣X=x)≈KcKBayes decision rule:y^=argmaxc∈𝒴 ℙ(Y=c∣X=x)
Three of five neighbors in class 1 give an estimate of 3/5 = 0.60.
Predict the class with the largest fraction.
K = number of selected neighborsK꜀ = neighbors in class c𝒴 = set of class labels
5.7.1 · Bayesian derivation

Start with Bayes’ theorem

pY∣X(y∣x)=pX∣Y(x∣y)pY(y)pX(x)
Class posterior=Likelihood×Class priorEvidence

Estimate these three quantities

Likelihood, prior, and evidence.

Use a region around x

We begin with the input density and estimate it from nearby data.

pY∣X(y ∣ x) = posterior class probabilitypX∣Y(x ∣ y) = likelihood (class-conditional density)pY(y) = prior (class probability before observing x)pX(x) = evidence (input density)
5.7.1 · Bayesian derivation

Estimating the evidence from a small region

Bayes’ theorem needs the input density at the query, which we can approximate using the probability mass around it.

A smooth input-density curve with the area shaded only within the interval around the query x.
The shaded area is the chance that a randomly drawn input falls inside 𝓡.
Pℛ=ℙ(X∈ℛ)=∫ℛpX(x)dx

The integral adds up the density across 𝓡 to give the shaded area.

pX(x)≈PℛV
If density is nearly constant in the region, probability mass ≈ density × volume.
𝓡 = region around the query xX = random inputpX = input densityPℛ = probability mass in 𝓡ℙ = probabilityV = size of the input region 𝓡With one input coordinate, V is length. With two input coordinates, V is area. With three input coordinates, V is volume.
5.7.1 · Bayesian derivation

A worked example of local density

The input is uniform from 0 to 10. The whole rectangle has area 1 and width 10, so its height, the density, is 1 ÷ 10 = 0.10 per input unit.

Density = 0.10 per input unit

0.1004610Shaded area = 0.10 × (6 − 4) = 0.20𝓡

Mass divided by length

The shaded area (0.20) is the 20% probability of landing between 4 and 6. Since the density is flat, dividing by the interval length V = 2 gives the exact density.

pX(x)=PℛV=0.202=0.10
With data, the probability mass is unknown. Estimate it by counting points in the region.
5.7.1 · Bayesian derivation

Why does the neighbor vote estimate a probability?

We want to estimate the chance that a new input belongs to a class. Bayes’ theorem gives us a way to do this, using quantities we can estimate from the training data.

Count inside the region

First, show why the fraction of training inputs inside a fixed region estimates the probability of landing there.

Estimate the three Bayes terms

Evidence is the local density across all inputs.
Likelihood is the local density within the chosen class.
Prior is the class’s overall frequency.

See what cancels

Put those estimates into Bayes’ theorem. The shared region size cancels, along with the dataset counts, leaving a fraction of the neighbors.

The formula we’ll deriveℙ(Y=c∣X=x)≈KcKFor query x, K is the total number of selected neighbors and Kc counts those in class c.
5.7.1 · Bayesian derivation

Why can a count estimate the region’s probability?

01 · Count inside a fixed region

K~Bin(n,Pℛ)

02 · Find the expected count

𝔼[K]=nPℛ

03 · Divide by the sample size

𝔼[Kn]=𝔼[K]n=Pℛ

04 · Measure the spread

Var[Kn]=Var[K]n2=nPℛ(1−Pℛ)n2=Pℛ(1−Pℛ)n

05 · Estimate the probability

Kn≈𝔼[Kn]=Pℛ
𝓡 is fixed in this counting argumentK = random count inside 𝓡, n = sampled inputsPℛ = probability that one input lies inside 𝓡Bin = binomial distribution𝔼 = expectation, Var = varianceIn KNN itself, K is chosen and the region changes to include K neighbors.
5.7.1 · Bayesian derivation

Bayes’ theorem explains the neighbor fraction

01 · Estimate the input density

pX(x)≈PℛV≈K/nV=KnV
Evidence

02 · Estimate density within a class

pX∣Y(x∣c)≈KcncV
Likelihood

03 · Estimate the class prior

pY(c)=ncn
Prior

04 · Substitute into Bayes’ theorem

pY∣X(c∣x)≈(Kc/(ncV))×(nc/n)(K/(nV))
Class posterior=Likelihood×Class priorEvidence

05 · Cancel the common factors

(Kc/(ncV))×(nc/n)(K/(nV))=Kc/(nV)K/(nV)=KcK
Class posterior=Likelihood×Class priorEvidence
x = fixed query, c = candidate classn = all training cases, n꜀ = all class-c casesK = selected neighbors, K꜀ = class-c neighborsV = volume of their common local regionpX = input density, pX∣Y = class-conditional densitypY∣X(c∣x)=ℙ(Y=c∣X=x)
5.7.1 · Bayesian derivation

From the circle’s counts to a class probability

Choose K, move the query and choose a class. Use the same circle to estimate both densities, then substitute the numbers into Bayes’ theorem.

5.7.2 · K-NN regressor

From voting to averaging

The same nearest neighbors can predict a number by averaging their target values.

y^i=1K∑yj∈𝒩K(xi)yj

Find the K nearest inputs

Use their numerical targets.

Average those targets

𝒩3(xi)={2,6,10}
y^i=2+6+103=6
ŷᵢ = predicted numerical target𝒩K(xi) = collection of selected targetsyⱼ = one selected target
5.7.2 · K-NN regressor

KNN regression: see every target in the average

Move the new input x and choose K. Select neighbors by horizontal input distance only, then add their numerical targets y and divide by K.

5.7.3 · Validation

What happens when we average every target?

In the regression demo, setting K = n makes every query average the same training targets.

−202Blue: targets Green: KNN prediction
y^i=1n∑xj∈𝒟yj=y¯

Regression predicts the global mean. Classification predicts the global majority class.

n = number of stored observationsȳ = global mean of the targetsEqual weights give a constant prediction, which can have high bias.𝒟 = training dataset
5.7.3 · Validation

What happens when we use just one neighbor?

At the other extreme, K = 1 makes the prediction depend entirely on the closest stored observation.

−202Blue: targets Green: KNN prediction
y^i=yi*

A different sample can change the nearest target. This highly local rule typically has higher variance.

i∗ = index of the closest stored observationyi∗ = its observed target
Validation helps choose a value of K between these extremes.
5.7.3 · Validation

How do we choose K between these extremes?

The last two slides show how K changes the prediction, so we need a fair way to compare candidate values.

The tempting approach

Try several values of K and keep the one with the best test score.

Use validation to choose K

Choosing K selects a prediction rule. Compare candidates on validation data and reserve test data for the final assessment.

K is a hyperparameter chosen by comparing candidate models.
5.7.3 · Validation

Three datasets separate fitting, choosing and assessing

Training: 30 cases
Validation: 10 cases
Test: 10 cases

Training

Store the training examples.

Validation

Compare candidates and choose K.

Test

Evaluate the chosen model.

5.7.3 · Validation

Use a metric that matches the target

Class labels: accuracy

Acc=1n∑i=1n𝟙(yi=y^i)

Fraction of correct labels. Higher is better.

Numerical targets: RMSE

RMSE=1n∑i=1n(yi−y^i)2

Typical size of the error in the target’s units. Lower is better.

Compare candidates on the same validation cases. Evaluate the chosen model on the test set.
n = number of cases in the set currently being evaluatedi = evaluation-case index, not a neighbor index hereyᵢ = observed target, ŷᵢ = its prediction𝟙(A) = 1 if A is true, otherwise 0
5.7.3 · Validation

Choose K using validation, then reveal the test

Compare K = 1, 5 and 15. Click a validation case to see how its neighbors voted, then lock your choice to reveal the test score.

5.7.4 · Characteristics

When might KNN be a useful choice?

A useful relationship has a known form

A parametric model can work well when its chosen form fits the relationship.

We want a more flexible shape

KNN uses local examples and can adapt to varied decision boundaries or regression shapes.

5.7.4 · Characteristics

KNN stores more data and does more work at prediction time

For our two-feature exampleLogistic regressionKNN
What is stored for prediction?3 fitted coefficients: intercept + 2 slopes50 input pairs and their 50 labels
What happens for one new input?Evaluate the fitted probability formulaCompare input distances and combine nearby labels
A full scan compares the query with every stored point.
Search trees or stored distances can speed up search and use additional memory.
Lecture summary

What nearest neighbors can tell us

IdeaWhat to explain
KNN classificationNearby labels vote, optionally with distance weights.
Bayesian derivationLocal density estimates lead to the neighbor fraction Kc/K.
KNN regressionAverage the nearest observations’ numerical targets.
ValidationChoose K before using the final test observations.
Further reading
Continue learning
AIML · Lecture 12 · Classification · Part 2
Course home