Classification and regression with nearest neighbors
A complete companion to the lecture, with the same chapter sequence, worked mathematics and interactive examples.
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.
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.
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.
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.
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.
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.
Lecture mapWhat can we learn from nearby examples?
| Chapter | Question we will answer |
|---|---|
| 5.7 · K-Nearest Neighbors | What do nearby examples suggest for a new input? |
| 5.7.1 · Bayesian derivation | Why does a neighbor fraction estimate a class probability? |
| 5.7.2 · K-NN regressor | What if the target is a number? |
| 5.7.3 · Validation | How do we choose K? |
| 5.7.4 · Characteristics | When 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.
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.
Static preview. Open handout.html to use the interactive example.
5.7 · K-Nearest NeighborsThe neighborhood contains the nearest examples’ targets
First: select nearby inputs
Compare query xᵢ with the stored training inputs.
Select the K smallest distances.
identify those K observations.
Then: read their targets
Keep one target entry for each neighbor.
Three entries are 1 and two are 0.
Repeated labels count separately: the braces describe the selected collection, with one entry per neighbor.
The neighborhood contains the targets of the K nearest training observations to input xᵢ. The indices identify the selected observations, and 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.
5.7 · K-Nearest NeighborsClassify an input by the majority label nearby
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
Class 0: 2 votes. Class 1: 3 votes.
argmax returns class 1, so ŷᵢ=1.
No learnable coefficients appear in the rule.
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 . 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.
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.
Static preview. Open handout.html to use the interactive example.
5.7 · K-Nearest Neighbors“Nearest” needs a distance between input measurements
Euclidean distance
For these two-feature inputs:
subtract corresponding feature values,
square the differences, add, and take the square root.
A small coordinate example
Euclidean distance is one possible metric. Feature units affect what counts as close.
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.
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.
Static preview. Open handout.html to use the interactive example.
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.
Predict the class with the largest fraction.
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, (y | x)=ℙ(Y=y | X=x). With continuous inputs, and are densities, rather than point probabilities.
5.7.1 · Bayesian derivationStart with Bayes’ theorem
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.
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.
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.

The integral adds up the density across 𝓡 to give the shaded area.
Begin with the input density (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 =ℙ(X∈𝓡) is the integral of 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 (x)≈/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 .
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
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.
This one-dimensional example illustrates the small-region approximation. The derivation that follows explains how the observed fraction K/n estimates that mass.
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 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.
5.7.1 · Bayesian derivationWhy can a count estimate the region’s probability?
01 · Count inside a fixed region
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 of an inside outcome.
Teaching example: independent inputs and . The count K changes from sample to sample.
02 · Find the expected count
An individual observation has probability of falling inside.
Across n observations, the expected number inside is n times that probability.
For example, if n=100 and =0.20, the expected count is 20.
Example: expected points inside the fixed region.
03 · Divide by the sample size
K/n is the observed fraction inside the region.
Divide the expected count n by the fixed number n. The n factors cancel.
The expected fraction is therefore the true probability mass .
Example: . This is an average over repeated samples.
04 · Measure the spread
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) = n(1 − ).
Dividing K by n divides its variance by n². The variance of K/n shrinks as n grows.
Example: . With the variance is .
05 · Estimate the probability
Step 3 tells us where K/n is centered. Its average is the true probability mass .
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 .
For example, an observed gives as an estimate of the unknown probability mass.
5.7.1 · Bayesian derivationBayes’ theorem explains the neighbor fraction
01 · Estimate the input density
The local density is approximately probability mass divided by volume (as in the previous slides).
Replace the unknown mass with the observed fraction K/n.
Dividing K/n by V gives the density estimate K/(nV).
Example throughout: . Input density = .
Evidence02 · Estimate density within a class
Now look only at the training observations belonging to class c.
Of those, fall in the same local region. Its class-conditional fraction is /.
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 = .
Likelihood03 · Estimate the class prior
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 counts the class in the whole dataset, whereas counts it locally.
In the whole dataset, 40 of 100 observations belong to class c. Prior = .
Prior04 · Substitute into Bayes’ theorem
Use posterior = likelihood × prior / input density.
The likelihood estimate is /(V), the prior estimate is /n, and the input-density estimate is K/(nV).
All three refer to the same query and local region.
Substitute the three estimates: .
05 · Cancel the common factors
First, cancels in likelihood × prior, leaving /(nV).
Then the common factor 1/(nV) cancels between numerator and denominator.
Only the local fraction /K remains. It estimates the conditional class probability.
The same result is just : six of the ten neighbors belong to class c.
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.
Static preview. Open handout.html to use the interactive example.
5.7.2 · K-NN regressorFrom voting to averaging
The same nearest neighbors can predict a number by averaging their target values.
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
Regression uses the average numerical 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.
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.
Static preview. Open handout.html to use the interactive example.
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.
Regression predicts the global mean. Classification predicts the global majority class.
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.
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.
A different sample can change the nearest target. This highly local rule typically has higher variance.
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.
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.
Validation is the procedure used to choose it. Selecting K still chooses a hypothesis from the hypothesis space.
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.
5.7.3 · ValidationThree datasets separate fitting, choosing and assessing
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.
- For each K, construct the predictor and evaluate it on validation data.
- Select the K with the best validation performance.
- Report that selected predictor’s performance on the test set.
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.
5.7.3 · ValidationUse a metric that matches the target
Class labels: accuracy
What fraction of the evaluated labels are correct?
Larger is better.
Numerical targets: RMSE
How large are the numerical prediction errors?
Root Mean Squared Error uses the target’s units.
Smaller is better.
After choosing K, use the appropriate metric on the untouched test set.
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.
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.

Static preview. Open handout.html to use the interactive example.
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?
- Choose K=1 because training accuracy is perfect.
- Try many K values on the test set and report the best test result.
- Choose K=9 using validation, fix the procedure, then assess it on the untouched test set.
- 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.
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 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.
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 example | Logistic regression | KNN |
|---|---|---|
| What is stored for prediction? | 3 fitted coefficients: intercept + 2 slopes | 50 input pairs and their 50 labels |
| What happens for one new input? | Evaluate the fitted probability formula | Compare input distances and combine nearby labels |
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.
Lecture summaryWhat nearest neighbors can tell us
| Idea | What to explain |
|---|---|
| KNN classification | Nearby labels vote, optionally with distance weights. |
| Bayesian derivation | Local density estimates lead to the neighbor fraction . |
| KNN regression | Average the nearest observations’ numerical targets. |
| Validation | Choose 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.
Further readingContinue with probability models and nearest neighbors
- An Introduction to Statistical Learning · Classification
- Pattern Recognition and Machine Learning · Probability and classification
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.
Notation at a glance
| Symbol | Meaning |
|---|---|
| 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ᵢ), ∏, argmax | Logistic class-1 probability, product over indicated observations, return the maximizing choice. |
| K, , | 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. |
| ℙ, , , , | Probability operator, posterior, likelihood, prior, input density. Subscripts name the variables. |
| 𝓡, V, | Local region, its volume, probability mass inside the region. |
| K ∼ Bin(n,) | 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, RMSE | Global numerical target mean, fraction of correct labels, Root Mean Squared Error. |
| i* | Index of the nearest training observation in the K=1 example. |