ArticleslgStudy

computer science

K-nearest neighbors algorithm

K-nearest neighbors algorithm is a computer science topic covered in the lgStudy science library. This page brings together a partial reference excerpt, illustrations, worked examples, real-world applications and a short study plan, so you can understand K-nearest neighbors algorithm rather than just read about it. In short: In statistics and machine learning, the k-nearest neighbors algorithm (k-NN) is a non-parametric supervised learning method that assigns weightage only to the k (number of) nearest neighbors of an entity in making a decision about the entity. It is used both in classification -- where a new example is assigned a label based on the labels of its k nearest training examples; and in regression -- where the prediction i…

K-nearest neighbors algorithm — main illustration
K-nearest neighbors algorithm — illustration

Key takeaways

  • K-nearest neighbors algorithm belongs to computer science; place it in that map before memorising details.
  • Learn the definition first, then one example that makes the definition concrete.
  • Connect K-nearest neighbors algorithm to a quantity you can measure, compute or draw — that is where exam questions come from.
  • Reproduce the core statement of K-nearest neighbors algorithm from memory before moving on to harder problems.

Reference excerpt

In statistics and machine learning, the k-nearest neighbors algorithm (k-NN) is a non-parametric supervised learning method that assigns weightage only to the k (number of) nearest neighbors of an entity in making a decision about the entity. It is used both in classification -- where a new example is assigned a label based on the labels of its k nearest training examples; and in regression -- where the prediction is computed from the values of those neighbors. Its more frequent use is for classification, as the k-NN classifier, the output of which is a class membership decided by a plurality vote of its neighbors. k, an integer, is typically small; if k = 1, then the object is simply assigned to the class of that single nearest neighbor. It was first developed by Evelyn Fix and Joseph Hodges in 1951, and later expanded by Thomas Cover. The k-NN algorithm can also be generalized for regression. In k-NN regression, also known as nearest neighbor smoothing, the output is the property value for the object. This value is the average of the values of k nearest neighbors. If k = 1, then the output is simply assigned to the value of that single nearest neighbor, also known as nearest neighbor interpolation. For both classification and regression, a useful technique can be to assign weights to the contributions of the neighbors, so that nearer neighbors contribute more to the average than distant ones. For example, a common weighting scheme consists of giving each neighbor a weight of 1/d, where d is the distance to the neighbor. The input consists of the k closest training examples in a data set. The neighbors are taken from a set of objects for which the class (for k-NN classification) or the object property value (for k-NN regression) is known. This can be thought of as the training set for the algorithm, though no explicit training step is required. A peculiarity (sometimes even a disadvantage) of the k-NN algorithm is its sensitivity to the local structure of the data. In k-NN classification the function is only approximated locally and all computation is deferred until function evaluation. Since this algorithm relies on distance, if the features represent different physical units or come in vastly different scales, then feature-wise normalizing of the training data can greatly improve its accuracy.

Statistical setting Suppose we have pairs ( X 1 , Y 1 ) , ( X 2 , Y 2 ) , … , ( X n , Y n ) {\displaystyle (X_{1},Y_{1}),(X_{2},Y_{2}),\dots ,(X_{n},Y_{n})} taking values in R d × { 1 , 2 } {\displaystyle \mathbb {R} ^{d}\times \{1,2\}} , where Y is the class label of X, so that X | Y = r ∼ P r {\displaystyle X|Y=r\sim P_{r}} for r = 1 , 2 {\displaystyle r=1,2} (and probability distributions P r {\displaystyle P_{r}} ). Given some norm ‖ ⋅ ‖ {\displaystyle \|\cdot \|} on R d {\displaystyle \mathbb {R} ^{d}} and a point x ∈ R d {\displaystyle x\in \mathbb {R} ^{d}} , let ( X ( 1 ) , Y ( 1 ) ) , … , ( X ( n ) , Y ( n ) ) {\displaystyle (X_{(1)},Y_{(1)}),\dots ,(X_{(n)},Y_{(n)})} be a reordering of the training data such that ‖ X ( 1 ) − x ‖ ≤ ⋯ ≤ ‖ X ( n ) − x ‖ {\displaystyle \|X_{(1)}-x\|\leq \dots \leq \|X_{(n)}-x\|} .

Algorithm

The training examples are vectors in a multidimensional feature space, each with a class label. The training phase of the algorithm consists only of storing the feature vectors and class labels of the training samples. In the classification phase, k is a user-defined constant, and an unlabeled vector (a query or test point) is classified by assigning the label which is most frequent among the k training samples nearest to that query point.

A commonly used distance metric for continuous variables is Euclidean distance. For discrete variables, such as for text classification, another metric can be used, such as the overlap metric (or Hamming distance). In the context of gene expression microarray data, for example, k-NN has been employed with correlation coefficients, such as Pearson and Spearman, as a metric. Often, the classification accuracy of k-NN can be improved significantly if the distance metric is learned with specialized algorithms such as large margin nearest neighbor or neighborhood components analysis.

… excerpt ends here. Continue reading the full article.

Illustrations

K-nearest neighbors algorithm: Application of a k-NN classifier considering k = 3 neighbors. Left - Given the test point "?", the algorithm seeks the 3 closest points in the training set, and adopts the majority vote to classify it as "class red". Right - By iteratively repeating the prediction over the whole feature space (X1, X2), one can depict the "decision surface".
Application of a k-NN classifier considering k = 3 neighbors. Left - Given the test point "?", the algorithm seeks the 3 closest points in the training set, and adopts the majority vote to classify it as "class red". Right - By iteratively repeating the prediction over the whole feature space (X1, X2), one can depict the "decision surface".
K-nearest neighbors algorithm: An animated visualization of k-means clustering with k = 3, grouping countries based on life expectancy, GDP, and happiness—demonstrating how k-NN operates in higher dimensions. Click to view the animation.[6]
An animated visualization of k-means clustering with k = 3, grouping countries based on life expectancy, GDP, and happiness—demonstrating how k-NN operates in higher dimensions. Click to view the animation.[6]
K-nearest neighbors algorithm: Calculation of the border ratio
Calculation of the border ratio
K-nearest neighbors algorithm: Three types of points: prototypes, class-outliers, and absorbed points.
Three types of points: prototypes, class-outliers, and absorbed points.
K-nearest neighbors algorithm illustration

Worked examples

Example 1 — a first encounter with K-nearest neighbors algorithm

Start with the simplest possible case. Write down what K-nearest neighbors algorithm claims or describes in one sentence, then invent the smallest concrete situation in which that sentence is true. In computer science, the smallest case is usually a single object, a single equation or a single measurement. Check that every symbol or term in your sentence has a meaning in that case.

Example 2 — changing one variable

Take the situation from Example 1 and change exactly one quantity: double it, halve it, or set it to zero. Predict what should happen to K-nearest neighbors algorithm before you calculate. Comparing your prediction with the result is the fastest way to find out whether you understand the idea or only the words.

Example 3 — an exam-style question

Typical questions about K-nearest neighbors algorithm ask you to (a) state it precisely, (b) apply it to given data, and (c) explain a limitation. Practise writing all three answers in under five minutes; the third part is what separates a full-mark answer from an average one.

Applications of K-nearest neighbors algorithm

In research
K-nearest neighbors algorithm appears in computer science research whenever the underlying quantities have to be modelled precisely. Papers usually cite it as a starting assumption and then explore where it breaks down.
In technology and industry
Engineering practice reuses K-nearest neighbors algorithm in design rules, simulations and safety margins. Knowing the idea lets you read a specification sheet and understand why the numbers look the way they do.
In the classroom
K-nearest neighbors algorithm is common in secondary-school and first-year university syllabi. It links to neighbouring topics Classification algorithms, Machine learning algorithms, Nonparametric statistics, so understanding it makes those chapters shorter.
In everyday life
Look for K-nearest neighbors algorithm outside the textbook — in sport, cooking, traffic, electronics or the sky above you. An example you found yourself is remembered far longer than one you were given.

Affiliate

Preply — study more efficiently by working with a personal tutor. 50% off.

How to study K-nearest neighbors algorithm in 20 minutes

  1. Read the reference excerpt below once, without taking notes.
  2. Close the page and write down what K-nearest neighbors algorithm means in your own words.
  3. Compare your version with the excerpt and mark what you missed.
  4. Work through the three examples above with pen and paper.
  5. Explain K-nearest neighbors algorithm out loud to somebody else — or to Teacher Smith in the lgStudy chat.

Frequently asked questions

What is K-nearest neighbors algorithm in simple terms?

In statistics and machine learning, the k-nearest neighbors algorithm (k-NN) is a non-parametric supervised learning method that assigns weightage only to the k (number of) nearest neighbors of an entity in making a decision about the entity. It is used both in classification -- where a new example…

Why does K-nearest neighbors algorithm matter?

Because it connects several computer science ideas at once: it gives you a definition you can apply, a quantity you can calculate, and a way to check whether a result is plausible.

How should I study K-nearest neighbors algorithm?

Read the excerpt, restate it from memory, then work through the examples and applications listed on this page. The five-step study plan above takes about twenty minutes.

What does this page cover?

It gives you a compact reference excerpt plus original lgStudy explanations, examples, applications and study material on K-nearest neighbors algorithm.

Tags

  • Classification algorithms
  • Machine learning algorithms
  • Nonparametric statistics
  • Search algorithms
  • Statistical classification

Keep exploring