AIML · Lecture 12 · Classification · Part 2Course homeOpen slide deck  
AIML · Lecture 12 · Classification · Part 2

Classification and regression with nearest neighbors

A complete companion to the lecture, with the same chapter sequence, worked mathematics and interactive examples.

Read each explanation before exploring its controls. A hat on y marks a prediction. Open the slides

5.7 · K-Nearest NeighborsParametric 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

In parametric models such as polynomial, multiple and logistic regression, the formula specifies a family of relationships. Training estimates its coefficients from data. For logistic regression, the fitted function gives the class-1 probability for an input.

Open the corresponding slide ↗

5.7 · K-Nearest NeighborsParametric 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.

For a given set of features, logistic regression uses an intercept and one coefficient per feature. Adding more training observations can change their fitted values. In KNN, the stored examples determine the prediction locally, so the set of points that can shape the decision boundary grows with the training set. K controls the size of the neighborhood.

Open the corresponding slide ↗

5.7 · K-Nearest NeighborsK-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

The K-Nearest Neighbors classifier keeps the labelled training observations and uses nearby inputs at prediction time. The neighbor count K is chosen outside training. The method can adapt to a wide range of decision boundaries, with memory and prediction-time costs discussed in Characteristics.

K-Nearest Neighbors, abbreviated KNN or K-NN, is nonparametric. It does not fit a fixed coefficient vector for a predefined global relationship. It keeps the observations and predicts from nearby inputs. K is a chosen number of neighbors rather than a coefficient fitted by the learning rule. The method can adapt to varied relationships, but its flexibility has limitations that we examine later.

Open the corresponding slide ↗

Lecture mapWhat 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?

We start with nearest-neighbor classification and derive its class probability estimate. We then use the same neighborhood idea for regression and compare choices of K through validation.

Open the corresponding slide ↗

5.7 · K-Nearest NeighborsRead 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.

The dataset contains 50 synthetic observations, with 25 in class 0 and 25 in class 1. The two axes are measured input features in arbitrary units. They are not class probabilities or physical quantities with a stated clinical interpretation.

A point’s horizontal coordinate is feature 1 and its vertical coordinate is feature 2. Its colour and marker shape give its known target label: blue circles for 0 and orange crosses for 1. Selecting an observation shows both coordinates and its target explicitly.

For a new observation we know its input coordinates but not its class. KNN will use the known classes of nearby training inputs to predict that missing label. A binary separator is the division of the input plane into regions receiving prediction 0 or prediction 1.

Interactive example · Read the two features and the known class
Initial worked example: Read the two features and the known class. The preview uses the same values and calculations as the slide.
The same controls and observations as the slide. Use Larger view for more room. Printing uses the initial-state preview.
Open the corresponding slide ↗

5.7 · K-Nearest NeighborsThe neighborhood contains the nearest examples’ targets

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

First: select nearby inputs

Compare query xᵢ with the stored training inputs.
Select the K smallest distances.
i1,…,iK identify those K observations.

Then: read their targets

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

Keep one target entry for each neighbor.
Three entries are 1 and two are 0.

Here 𝒩K(xi) collects target labels, not feature coordinates or indices.
Repeated labels count separately: the braces describe the selected collection, with one entry per neighbor.
xᵢ = input being classifiedK = number of selected neighborsi1,…,iK = indices of those training observationsyi1,…,yiK = their observed target labels

The neighborhood 𝒩K(xi) contains the targets of the K nearest training observations to input xᵢ. The indices i1,…,iK identify the selected observations, and yi1,…,yiK are their targets.

We use braces for this selected collection, retaining one entry per neighbor. Repeated labels are not merged or discarded. For example, five neighbors with targets {0,1,1,0,1} supply five votes: three for class 1 and two for class 0. This convention makes the following sum over targets unambiguous.

Open the corresponding slide ↗

5.7 · K-Nearest NeighborsClassify an input by the majority label nearby

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

Count one vote at a time

Try a candidate class c.
A neighbor contributes 1 if its target yⱼ equals c, and 0 otherwise.
The sum is the number of votes for c.

Choose the largest vote count

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

Class 0: 2 votes. Class 1: 3 votes.
argmax returns class 1, so ŷᵢ=1.

The prediction depends on the stored data, the chosen K and the distance used to select neighbors.
No learnable coefficients appear in the rule.
xᵢ = query input, ŷᵢ = its predicted class𝒴={0,1} here, c = a candidate classyⱼ = one selected training target𝒩K(xi) = collection of K neighbor targets𝟙(A) = 1 if A is true, otherwise 0argmax returns the class with the largest sumHere j indexes a selected training observation, not a feature column.

KNN classifies an input with the majority class among its K nearest neighbors. For every candidate class c, sum an indicator over the target entries yⱼ in 𝒩K(xi). Each matching label contributes one, and each other label contributes zero. The sum is the class vote count.

The argmax selects the candidate with the largest count and returns its label. For {0,1,1,0,1}, class 1 receives three votes versus two for class 0. The prediction is therefore ŷᵢ=1.

The method depends on the stored data, a chosen K, and the neighborhood determined by a mathematical metric. There are no coefficients learned by this vote formula. Here j indexes a selected training observation, rather than a feature column.

Open the corresponding slide ↗

5.7 · K-Nearest NeighborsOne 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.

The star marks a new query input. Its two coordinates are known, but its class is to be predicted. With K=1, select the stored input with the smallest Euclidean distance to this query, then copy its known class label.

The numbered green ring identifies that one selected neighbor. The table shows its distance and class, and the result copies that class. The background applies exactly the same rule at other possible query positions. It is a map of predictions, not another set of observations.

Move either query coordinate or select one of the prepared positions. A small movement near a region boundary can change which stored input is nearest and therefore change the prediction. At an exact stored input the distance is zero. Equal distances are resolved by stored order.

Interactive example · One nearest neighbor decides the new query’s class
Initial worked example: One nearest neighbor decides the new query’s class. The preview uses the same values and calculations as the slide.
The same controls and observations as the slide. Use Larger view for more room. Printing uses the initial-state preview.
Open the corresponding slide ↗

5.7 · K-Nearest Neighbors“Nearest” needs a distance between input measurements

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

Euclidean distance

For these two-feature inputs:
subtract corresponding feature values,
square the differences, add, and take the square root.

A small coordinate example

xi=(1,1),xj=(4,5)
‖xi−xj‖2=32+42=5
Select the K training inputs with the smallest distances to the query.
Euclidean distance is one possible metric. Feature units affect what counts 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

The neighborhood can be constructed with a mathematical metric. Here we use Euclidean distance ‖xᵢ−xⱼ‖₂, the straight-line distance between two inputs. For the two-dimensional example it is the square root of the sum of the two squared feature differences.

In the small coordinate example, the feature differences are 3 and 4, so the distance is √(9+16)=5. Calculate a distance from the query to each stored input and select the K nearest observations. Other metrics are possible. The units of measured features matter because the distance combines their differences.

Open the corresponding slide ↗

5.7 · K-Nearest NeighborsKNN: 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.

The example uses the same 50 synthetic two-feature observations. A purple star marks the new query input, and numbered green rings identify selected nearest training inputs. The numbers match the table’s distance ranking when K is at most nine. The table contains all K selected rows and can be scrolled for larger neighborhoods.

Each selected row contributes one vote to its known class. Count the rows with label 0 and those with label 1. The larger count determines the prediction. At the initial query (0.50,0.20) with K=5, two selected labels are 0 and three are 1, so the class-1 fraction is 3/5=0.60 and the prediction is class 1.

The background colors show the predicted class at other inputs. If the two classes receive the same number of votes, the example chooses class 0. Choosing an odd K avoids tied vote counts with two classes. If neighbors are equally distant, the example uses their stored order.

Interactive example · KNN: inspect the neighbors, then count their votes
Initial worked example: KNN: inspect the neighbors, then count their votes. The preview uses the same values and calculations as the slide.
The same controls and observations as the slide. Use Larger view for more room. Printing uses the initial-state preview.
Open the corresponding slide ↗

5.7.1 · Bayesian derivationFrom 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

Although the KNN vote formula directly returns a class label, it also has a probabilistic interpretation. The fraction K꜀/K estimates ℙ(Y=c | X=x), where K꜀ counts the selected neighbors belonging to class c. The class with the largest count also has the largest fraction because K is common to all classes.

We use ≈ to distinguish a finite-sample estimate from the unknown true class probability. To motivate it, return to Bayes’ theorem: posterior equals class-conditional likelihood times prior divided by input density. The following steps estimate those three quantities locally.

ℙ states a probability event in full. Lowercase p names a distribution function, as in Part 1. Because Y is discrete, pY∣X(y | x)=ℙ(Y=y | X=x). With continuous inputs, pX and pX∣Y are densities, rather than point probabilities.

Open the corresponding slide ↗

5.7.1 · Bayesian derivationStart 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)

The general Bayes formula uses y for a class value. In the worked derivation, c identifies a candidate class. For continuous inputs, the class-conditional and input terms are densities. The class prior and posterior are probabilities.

Open the corresponding slide ↗

5.7.1 · Bayesian derivationEstimating 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.

Begin with the input density pX(x). Consider a small region 𝓡 centered around the query. In the plot, V is the width of the interval along the input axis, and the shaded area is the probability mass.

The region’s probability mass Pℛ=ℙ(X∈𝓡) is the integral of pX over the region. In that integral, x is the variable that runs over possible input values. If the density changes little across this small region, probability mass is approximately density times volume. Rearranging gives pX(x)≈Pℛ/V.

We cannot evaluate the integral directly because the true input distribution is unknown. The next argument uses the fraction of sampled observations falling inside the region to estimate Pℛ.

Open the corresponding slide ↗

5.7.1 · Bayesian derivationA 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.

This one-dimensional example illustrates the small-region approximation. The derivation that follows explains how the observed fraction K/n estimates that mass.

Open the corresponding slide ↗

5.7.1 · Bayesian derivationWhy 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.

The first argument holds the region fixed to study how the observed fraction behaves across samples. When using KNN to predict, choose the neighbor count first and use the region that contains those neighbors. Use that same region for the overall and within-class density estimates.

Open the corresponding slide ↗

5.7.1 · Bayesian derivationWhy can a count estimate the region’s probability?

01 · Count inside a fixed region

K~Bin(n,Pℛ)

Hold the region 𝓡 fixed. Each independent observation either falls inside it or outside it.

K counts how many of the n observations fall inside. Its possible values are 0,…,n.

This is a binomial count, with probability Pℛ of an inside outcome.

Teaching example: n=100 independent inputs and PR=0.20. The count K changes from sample to sample.

02 · Find the expected count

𝔼[K]=nPℛ

An individual observation has probability Pℛ of falling inside.

Across n observations, the expected number inside is n times that probability.

For example, if n=100 and Pℛ=0.20, the expected count is 20.

Example: 100×0.20=20 expected points inside the fixed region.

03 · Divide by the sample size

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

K/n is the observed fraction inside the region.

Divide the expected count nPℛ by the fixed number n. The n factors cancel.

The expected fraction is therefore the true probability mass Pℛ.

Example: 𝔼[K/100]=20/100=0.20. This is an average over repeated samples.

04 · Measure the spread

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

Step 3 gave the average across samples. How far might one sample’s K/n be from that average?

To measure that spread, start with the binomial variance Var(K) = nPℛ(1 − Pℛ).

Dividing K by n divides its variance by n². The variance of K/n shrinks as n grows.

Example: 0.20×0.80/100=0.0016. With n=1000 the variance is 0.00016.

05 · Estimate the probability

Kn≈𝔼[Kn]=Pℛ

Step 3 tells us where K/n is centered. Its average is the true probability mass Pℛ.

Step 4 tells us how tightly K/n clusters around that average. Larger samples have smaller variance.

With enough independent observations, one sample’s K/n is therefore likely to be close to Pℛ.

For example, an observed K=18 gives 18/100=0.18 as an estimate of the unknown probability mass.

𝓡 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.
Open the corresponding slide ↗

5.7.1 · Bayesian derivationBayes’ theorem explains the neighbor fraction

01 · Estimate the input density

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

The local density is approximately probability mass divided by volume (as in the previous slides).

Replace the unknown mass Pℛ with the observed fraction K/n.

Dividing K/n by V gives the density estimate K/(nV).

Example throughout: n=100, nc=40, K=10, Kc=6, V=2. Input density = 10/(100×2)=0.05.

Evidence

02 · Estimate density within a class

pX∣Y(x∣c)≈KcncV

Now look only at the nc training observations belonging to class c.

Of those, Kc fall in the same local region. Its class-conditional fraction is Kc/nc.

Divide by the same volume V to estimate the feature density within that class.

Within class c: 6 of its 40 observations are in the region. Density = 6/(40×2)=0.075.

Likelihood

03 · Estimate the class prior

pY(c)=ncn

The class prior describes how common class c is before the query is considered.

Estimate it by the fraction of all training observations with that label.

Here nc counts the class in the whole dataset, whereas Kc counts it locally.

In the whole dataset, 40 of 100 observations belong to class c. Prior = 40/100=0.40.

Prior

04 · Substitute into Bayes’ theorem

pY∣X(c∣x)≈(Kc/(ncV))×(nc/n)(K/(nV))

Use posterior = likelihood × prior / input density.

The likelihood estimate is Kc/(ncV), the prior estimate is nc/n, and the input-density estimate is K/(nV).

All three refer to the same query and local region.

Substitute the three estimates: (0.075×0.40)/0.05=0.60.

Class posterior=Likelihood×Class priorEvidence

05 · Cancel the common factors

(Kc/(ncV))×(nc/n)(K/(nV))=Kc/(nV)K/(nV)=KcK

First, nc cancels in likelihood × prior, leaving Kc/(nV).

Then the common factor 1/(nV) cancels between numerator and denominator.

Only the local fraction Kc/K remains. It estimates the conditional class probability.

The same result is just 6/10=0.60: six of the ten neighbors belong to class c.

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)
Open the corresponding slide ↗

5.7.1 · Bayesian derivationFrom 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.

The circle is centered on the query and extends to the K-th nearest input. It contains the selected K neighbors. Choose which class c to inspect. K꜀ counts that class inside the circle, while n꜀ counts it in the whole training dataset. Here n=50 and each class has n꜀=25.

The displayed radius r is the K-th neighbor’s input distance. In this two-dimensional picture, the common region volume is the circle’s area V=πr². Use K/(nV) as the input-density estimate and K꜀/(n꜀V) as the class-conditional density estimate. The class prior is n꜀/n.

The table substitutes the actual counts and area into these expressions. Bayes’ theorem combines them as class density × prior / input density. Since both densities refer to the same circle, the factors n꜀ and 1/(nV) cancel, leaving K꜀/K. The equality is exact for these estimates, while their relationship to the unknown population posterior is approximate.

Changing K or moving the query changes the radius, area and counts. You can also switch the inspected class between 0 and 1. Density heights can exceed one because they are mass per unit of area. The final normalized class probability remains between zero and one. All calculations use unrounded values.

Interactive example · From the circle’s counts to a class probability
Initial worked example: From the circle’s counts to a class probability. The preview uses the same values and calculations as the slide.
The same controls and observations as the slide. Use Larger view for more room. Printing uses the initial-state preview.
Open the corresponding slide ↗

5.7.2 · K-NN regressorFrom voting to averaging

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

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

Select the same kind of neighborhood

Find the K nearest training inputs to xᵢ.
Their target values are now numbers, rather than class labels.

Add the targets, then divide by K

𝒩3(xi)={2,6,10}
y^i=2+6+103=6
Classification uses the majority label.
Regression uses the average numerical target.
xᵢ = query input, ŷᵢ = predicted numerical valueK = chosen number of neighbors𝒩K(xi) = collection of their numerical targetsyⱼ = one selected training target

KNN can also predict a quantitative outcome. Neighborhood selection works in the same way, but the selected targets are numbers. Instead of counting votes for classes, sum those target values and divide by K.

For three targets 2,6,10, the prediction is (2+6+10)/3=6. Thus the KNN regressor estimates the new outcome as the average of the K nearest observations’ target values.

Open the corresponding slide ↗

5.7.2 · K-NN regressorKNN 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.

This example contains 25 illustrative numerical observations. Here x is the observed input and y is the numerical target to predict. The new query is a horizontal input position. Choose its K nearest stored input values using |xⱼ−x|. The target y does not enter this distance.

Orange rings show the selected observations. The table lists each selected input xⱼ, its known numerical target yⱼ and its distance to the query. Add the table’s target values to obtain the displayed sum, then divide by K. The purple star marks this prediction at the new input.

The green curve repeats the same K-neighbor average at every input value. It is the KNN prediction curve, not a hidden true relationship. With K=1 the result copies one selected target. With K=25 it always uses all observations and therefore returns their global mean. Larger tables can be scrolled to inspect every selected target.

Interactive example · KNN regression: see every target in the average
Initial worked example: KNN regression: see every target in the average. The preview uses the same values and calculations as the slide.
The same controls and observations as the slide. Use Larger view for more room. Printing uses the initial-state preview.
Open the corresponding slide ↗

5.7.3 · ValidationWhat 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

With equal weights and K = n, every training observation contributes. The classifier uses the most represented class. The regressor returns the global mean, equivalent to a constant regression model of order zero. This endpoint has low flexibility and can have high bias.

With K=n and equal weights, every training observation contributes. Classification always chooses the most represented class. Regression always returns the global target mean, equivalent to a constant regression model of order zero. This is the least flexible endpoint and can have high bias.

With K=1, the prediction is the target of the single nearest observation. A new training sample can change that observation and its target, making predictions variable across datasets. This endpoint therefore has high variance. The bias–variance pattern is a general tendency, rather than a guarantee of monotonic improvement for every dataset.

Open the corresponding slide ↗

5.7.3 · ValidationWhat 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.

At K = 1, both classification and regression copy the target of the nearest training observation. A different sample can change which observation is nearest and therefore change the prediction. This is the high-variance end of the bias–variance trade-off.

Open the corresponding slide ↗

5.7.3 · ValidationHow 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.

A tempting comparison

Try several K values.
Check each one on the test set.
Keep whichever test result looks best.

The problem

We have used those outcomes to choose the predictor.
The “test” data have become part of model selection, so the result is no longer an independent final assessment.

K is a hyperparameter: a setting selected outside the model’s ordinary training rule.
Validation is the procedure used to choose it. Selecting K still chooses a hypothesis from the hypothesis space.
K = candidate neighbor countHyperparameter = a setting chosen by comparing candidate modelsValidation set = observations used for that comparisonTest set = observations reserved for assessing the selected modelHypothesis space = set of candidate prediction rules

It may seem natural to compare several K values on the test set and choose the best one. That contains a fallacy. Although K is not estimated by the ordinary KNN training rule, selecting it from outcomes still selects a prediction hypothesis. It can therefore influence generalization in the same way as other model fitting choices.

K is called a hyperparameter, and its selection procedure is called validation. Data used repeatedly to choose K are validation data in practice, whatever they were originally named. A final test set must remain outside that selection.

For numerical targets one can compare RMSE values. For class labels one can compare classification accuracy. The important point is that all candidates use validation observations, not the observations reserved for the final report.

Open the corresponding slide ↗

5.7.3 · ValidationThree datasets separate fitting, choosing and assessing

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

Training

Use these observations to construct each candidate predictor.
For KNN, keep the training input–target pairs.

Validation

Compare the candidate K values on these observations.
Choose the best validation result.

Test

Once K is fixed, assess the chosen model here.
Report this result as the final performance estimate.

  1. For each K, construct the predictor and evaluate it on validation data.
  2. Select the K with the best validation performance.
  3. Report that selected predictor’s performance on the test set.
Often, we reserve part of the available training data for validation.
Good validation performance should also hold on the final test observations if the procedure generalizes.

The correct procedure separates observations into training, validation and test sets. For each candidate hyperparameter configuration, construct the model from training data and evaluate it on validation data. Select the best model according to validation performance, then report the selected model’s performance on the test set.

In practice, a portion of the available training data is often reserved for validation. After achieving good validation performance, the final test checks whether that performance generalizes. Training supports the model, validation supports selection, and test supports final evaluation.

Open the corresponding slide ↗

5.7.3 · ValidationUse a metric that matches the target

Class labels: accuracy

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

What fraction of the evaluated labels are correct?
Larger is better.

Numerical targets: RMSE

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

How large are the numerical prediction errors?
Root Mean Squared Error uses the target’s units.
Smaller is better.

Use the same validation observations for every candidate K.
After choosing K, use the appropriate metric on the untouched 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

Validation applies to KNN classification and regression. For labels, accuracy counts correct predictions, as in Part 1. For numerical targets, RMSE averages the squared prediction errors and takes a square root, as introduced in regression. These are familiar metrics used here to clarify which comparison belongs to which target type.

In these evaluation formulas, n counts the cases being evaluated and i indexes them. It does not count selected neighbors. Compare all candidate K values on the same validation cases. After selecting K, evaluate the fixed predictor on test cases for the final report.

Open the corresponding slide ↗

5.7.3 · ValidationChoose 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.

This example uses 35 synthetic observations with one input score and a known class, 0 or 1. Each candidate uses the same 15 training observations to predict the same 10 validation cases. Another 10 cases are reserved for the test. Nearest means the smallest absolute difference between input scores.

Start with the validation case at input score 35. Its actual class is 0. With K = 1, the nearest training score is 34 and its class is 1, so the prediction is wrong. With K = 5, four of the five neighbors vote for class 0 and the prediction is correct. Select another case to inspect its votes.

K = 1 gets 8 of 10 validation cases right, K = 5 gets 9 of 10, and K = 15 gets 5 of 10. With K = 15, every query sees the same training majority of class 0. Choose K = 5 using validation, then lock it to reveal 8 of 10 correct on the separate test cases. Use the test score to report final performance.

Start over resets the same teaching example. In a real model comparison, choose K before looking at test labels or test accuracy.

Interactive example · Choose K using validation, then reveal the test
Initial worked example: Choose K using validation, then reveal the test. Three choices are compared on ten validation cases before revealing the test score.
The same controls and observations as the slide. Use Larger view for more room. Printing uses the initial-state preview.
Check your understanding · L05-C08

K=1 gives 100% training and 60% validation accuracy. K=9 gives 85% training and 80% validation accuracy. Which next step best estimates generalization after selecting K?

  1. Choose K=1 because training accuracy is perfect.
  2. Try many K values on the test set and report the best test result.
  3. Choose K=9 using validation, fix the procedure, then assess it on the untouched test set.
  4. Average training and validation accuracy and skip the test set.
Show the reasoning

Answer C. Training performance can be optimistic, especially when a point is its own nearest neighbor. Select K using validation evidence and reserve the final test observations for the fixed procedure.

Open the corresponding slide ↗

5.7.4 · CharacteristicsWhen might KNN be a useful choice?

A useful relationship has a known form

A parametric model builds that form into its formula.
If the assumption fits the true relationship, a compact parametric model can be preferable.

We want a more flexible shape

KNN does not commit to that fixed parameterized form.
Local examples can describe varied decision regions or numerical relationships.

The flexibility of KNN is an advantage, but it requires stored observations and work for each new prediction.
The next slide compares those costs with a compact parametric model.

KNN has the advantage of being nonparametric and versatile: it does not restrict the relationship to a particular parameterized shape. A parametric model is limited by its initial form assumption.

If the true relationship is well described by that parametric form, a parametric model may be preferable. KNN’s flexibility also brings memory and prediction-time costs, considered next.

Open the corresponding slide ↗

5.7.4 · CharacteristicsKNN stores more data and does more work at prediction time

Memory requirements

KNN keeps the training observations.
More stored examples require more space.
A parametric model instead compresses information into its fitted parameters.

Computation for a new input

Finding neighbors may require checking the whole training dataset for each query.
A large dataset can make this slow.

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
Stored distance information or clever search trees can speed up neighbor search.
These approaches also have storage costs. The central trade-off is memory and prediction time.

Memory is a main weakness of KNN. Its stored model depends on the dataset size. Increasing local data coverage can require keeping more observations, which takes space. A parametric model stores information from the training data in a compact parameter vector instead.

Prediction time is another weakness. To find a new observation’s nearest neighbors, a straightforward procedure may scan the whole dataset each time. Stored distance information and tree-based search structures can speed up suitable searches, but storage itself also has a cost.

Open the corresponding slide ↗

Lecture summaryWhat 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.

KNN classifies by combining the labels of nearby observations. The Bayesian derivation explains how their class fraction estimates a conditional probability. For a numerical target, average the neighbors’ values. Use validation to choose K and a separate test set to assess the chosen model.

For a numerical target, the same neighborhood supplies an average. K controls flexibility, so choose it using validation data and assess the selected predictor on a separate test set. KNN’s memory and prediction-time costs help decide when a parametric model may be preferable.

Open the corresponding slide ↗

Further readingContinue with probability models and nearest neighbors

The textbooks provide further background on classification, probability models and nearest neighbors. The definitions, formulas and derivation steps needed for this lecture are explained in this handout.

Open the corresponding slide ↗

Notation at a glance

SymbolMeaning
n, m, 𝒟Number of observations, number of features, dataset.
X, Y, 𝒴Random input, random outcome, set of possible class labels.
xᵢ, yᵢ, ŷᵢInput, observed target and predicted target for a query or evaluated observation.
β₀,…,βₘ, 𝛃, 𝛃^Intercept and feature coefficients, their vector, fitted coefficient vector.
σ(xᵢ), ∏, argmaxLogistic class-1 probability, product over indicated observations, return the maximizing choice.
K, i1,…,iK, 𝒩K(xi)Chosen neighbor count, selected training indices, collection of their target labels retaining repeated entries.
c, C, K꜀, n꜀Candidate class, number of classes, local class-c count, whole-dataset class-c count.
𝟙(A), ωⱼ, ‖xᵢ−xⱼ‖₂Indicator of a true condition, neighbor weight, Euclidean distance.
ℙ, pY∣X, pX∣Y, pY, pXProbability operator, posterior, likelihood, prior, input density. Subscripts name the variables.
𝓡, V, PℛLocal region, its volume, probability mass inside the region.
K ∼ Bin(n,Pℛ)In the fixed-region argument K is a random inside count. In KNN, K is chosen and the region adapts.
𝔼, Var, ≈Expectation (average), variance (spread across datasets), approximation.
ȳ, Acc, RMSEGlobal numerical target mean, fraction of correct labels, Root Mean Squared Error.
i*Index of the nearest training observation in the K=1 example.
Continue learning