KNN Algorithm – K-Nearest Neighbors Classifiers and Model Example (2025)

The K-Nearest Neighbors (K-NN) algorithm is a popular Machine Learning algorithm used mostly for solving classification problems.

In this article, you'll learn how the K-NN algorithm works with practical examples.

We'll use diagrams, as well sample data to show how you can classify data using the K-NN algorithm. We'll also discuss the advantages and disadvantages of using the algorithm.

How Does the K-Nearest Neighbors Algorithm Work?

The K-NN algorithm compares a new data entry to the values in a given data set (with different classes or categories).

Based on its closeness or similarities in a given range (K) of neighbors, the algorithm assigns the new data to a class or category in the data set (training data).

Let's break that down into steps:

Step #1 - Assign a value to K.

Step #2 - Calculate the distance between the new data entry and all other existing data entries (you'll learn how to do this shortly). Arrange them in ascending order.

Step #3 - Find the K nearest neighbors to the new entry based on the calculated distances.

Step #4 - Assign the new data entry to the majority class in the nearest neighbors.

Don't worry if the steps above seem confusing at the moment. The examples in the sections that follow will help you understand better.

K-Nearest Neighbors Classifiers and Model Example With Diagrams

With the aid of diagrams, this section will help you understand the steps listed in the previous section.

Consider the diagram below:

KNN Algorithm – K-Nearest Neighbors Classifiers and Model Example (1)

The graph above represents a data set consisting of two classes — red and blue.

KNN Algorithm – K-Nearest Neighbors Classifiers and Model Example (2)

A new data entry has been introduced to the data set. This is represented by the green point in the graph above.

We'll then assign a value to K which denotes the number of neighbors to consider before classifying the new data entry. Let's assume the value of K is 3.

KNN Algorithm – K-Nearest Neighbors Classifiers and Model Example (3)

Since the value of K is 3, the algorithm will only consider the 3 nearest neighbors to the green point (new entry). This is represented in the graph above.

Out of the 3 nearest neighbors in the diagram above, the majority class is red so the new entry will be assigned to that class.

KNN Algorithm – K-Nearest Neighbors Classifiers and Model Example (4)

The last data entry has been classified as red.

K-Nearest Neighbors Classifiers and Model Example With Data Set

In the last section, we saw an example the K-NN algorithm using diagrams. But we didn't discuss how to know the distance between the new entry and other values in the data set.

In this section, we'll dive a bit deeper. Along with the steps followed in the last section, you'll learn how to calculate the distance between a new entry and other existing values using the Euclidean distance formula.

Note that you can also calculate the distance using the Manhattan and Minkowski distance formulas.

Let's get started!

BrightnessSaturationClass
4020Red
5050Blue
6090Blue
1025Red
7070Blue
6010Red
2580Blue

The table above represents our data set. We have two columns — Brightness and Saturation. Each row in the table has a class of either Red or Blue.

Before we introduce a new data entry, let's assume the value of K is 5.

How to Calculate Euclidean Distance in the K-Nearest Neighbors Algorithm

Here's the new data entry:

BrightnessSaturationClass
2035?

We have a new entry but it doesn't have a class yet. To know its class, we have to calculate the distance from the new entry to other entries in the data set using the Euclidean distance formula.

Here's the formula: √(X₂-X₁)²+(Y₂-Y₁)²

Where:

  • X₂ = New entry's brightness (20).
  • X₁= Existing entry's brightness.
  • Y₂ = New entry's saturation (35).
  • Y₁ = Existing entry's saturation.

Let's do the calculation together. I'll calculate the first three.

Distance #1

For the first row, d1:

BrightnessSaturationClass
4020Red

d1 = √(20 - 40)² + (35 - 20)²
= √400 + 225
= √625
= 25

We now know the distance from the new data entry to the first entry in the table. Let's update the table.

BrightnessSaturationClassDistance
4020Red25
5050Blue?
6090Blue?
1025Red?
7070Blue?
6010Red?
2580Blue?
Distance #2

For the second row, d2:

BrightnessSaturationClassDistance
5050Blue?

d2 = √(20 - 50)² + (35 - 50)²
= √900 + 225
= √1125
= 33.54

Here's the table with the updated distance:

BrightnessSaturationClassDistance
4020Red25
5050Blue33.54
6090Blue?
1025Red?
7070Blue?
6010Red?
2580Blue?
Distance #3

For the third row, d3:

BrightnessSaturationClassDistance
6090Blue?

d2 = √(20 - 60)² + (35 - 90)²
= √1600 + 3025
= √4625
= 68.01

Updated table:

BrightnessSaturationClassDistance
4020Red25
5050Blue33.54
6090Blue68.01
1025Red?
7070Blue?
6010Red?
2580Blue?

At this point, you should understand how the calculation works. Attempt to calculate the distance for the last four rows.

Here's what the table will look like after all the distances have been calculated:

BrightnessSaturationClassDistance
4020Red25
5050Blue33.54
6090Blue68.01
1025Red10
7070Blue61.03
6010Red47.17
2580Blue45

Let's rearrange the distances in ascending order:

BrightnessSaturationClassDistance
1025Red10
4020Red25
5050Blue33.54
2580Blue45
6010Red47.17
7070Blue61.03
6090Blue68.01

Since we chose 5 as the value of K, we'll only consider the first five rows. That is:

BrightnessSaturationClassDistance
1025Red10
4020Red25
5050Blue33.54
2580Blue45
6010Red47.17

As you can see above, the majority class within the 5 nearest neighbors to the new entry is Red. Therefore, we'll classify the new entry as Red.

Here's the updated table:

BrightnessSaturationClass
4020Red
5050Blue
6090Blue
1025Red
7070Blue
6010Red
2580Blue
2035Red

How to Choose the Value of K in the K-NN Algorithm

There is no particular way of choosing the value K, but here are some common conventions to keep in mind:

  • Choosing a very low value will most likely lead to inaccurate predictions.
  • The commonly used value of K is 5.
  • Always use an odd number as the value of K.

Advantages of K-NN Algorithm

  • It is simple to implement.
  • No training is required before classification.

Disadvantages of K-NN Algorithm

  • Can be cost-intensive when working with a large data set.
  • A lot of memory is required for processing large data sets.
  • Choosing the right value of K can be tricky.

Summary

In this article, we talked about the K-Nearest Neighbors algorithm. It is often used for classification problems.

We saw an example using diagrams to explain how the algorithms works.

We also saw an example using sample data to see the steps involved in classifying a new data entry.

Lastly, we discussed the advantages and disadvantages of the algorithm, and how you can choose the value of K.

Happy coding!

KNN Algorithm – K-Nearest Neighbors Classifiers and Model Example (2025)

FAQs

KNN Algorithm – K-Nearest Neighbors Classifiers and Model Example? ›

KNN algorithm at the training phase just stores the dataset and when it gets new data, then it classifies that data into a category that is much similar to the new data. Example: Suppose, we have an image of a creature that looks similar to cat and dog, but we want to know either it is a cat or dog.

What is the KNN classifier for nearest neighbor? ›

The K-Nearest Neighbors (KNN) algorithm is a popular machine learning technique used for classification and regression tasks. It relies on the idea that similar data points tend to have similar labels or values.

What is the example of KNN algorithm? ›

In classification tasks, KNN counts the class labels of the "K" nearest neighbours. The class label that occurs most frequently among these neighbors is assigned to the new data point. Example: If out of the "K" neighbors, 5 belong to Class A and 3 belong to Class B, the prediction for the new data point is Class A.

How does the k nearest neighbors KNN algorithm work? ›

The kNN algorithm works as a supervised learning algorithm, meaning it is fed training datasets it memorizes. It relies on this labeled input data to learn a function that produces an appropriate output when given new unlabeled data. This enables the algorithm to solve classification or regression problems.

What is the difference between KNN and nearest neighbors? ›

In short, KNN involves classifying a data point by looking at the nearest annotated data point, also known as the nearest neighbor. Don't confuse K-NN classification with K-means clustering. KNN is a supervised classification algorithm that classifies new data points based on the nearest data points.

What is the KNN algorithm for dummies? ›

The K-NN algorithm works by finding the K nearest neighbors to a given data point based on a distance metric, such as Euclidean distance. The class or value of the data point is then determined by the majority vote or average of the K neighbors.

What is KNN used for in real life? ›

K Nearest Neighbor (KNN) is a very simple, easy-to-understand, and versatile machine learning algorithm. It's used in many different areas, such as handwriting detection, image recognition, and video recognition.

How to create a KNN model? ›

Creating a K-Nearest Neighbors (KNN) model with split data involves the following steps:
  1. Import necessary libraries.
  2. Load and preprocess the dataset.
  3. Split the dataset into training and testing sets.
  4. Create and train the KNN model using the training data.
  5. Evaluate the model's performance using the testing data.
Jul 20, 2023

When to use KNN model? ›

KNN tends to perform well when you have many instances (points) and few dimensions but you have to be very careful about performance because a brute-force version of KNN can be very slow when you have a lot of data. So KNN is good when you have many points but at the same time it becomes too slow a catch-22 scenario.

What is simple K nearest neighbors algorithm? ›

The K-NN algorithm compares a new data entry to the values in a given data set (with different classes or categories). Based on its closeness or similarities in a given range (K) of neighbors, the algorithm assigns the new data to a class or category in the data set (training data).

What are the disadvantages of KNN? ›

3 Disadvantages of KNN

KNN has some drawbacks and challenges, such as computational expense, slow speed, memory and storage issues for large datasets, sensitivity to the choice of k and the distance metric, and susceptibility to the curse of dimensionality.

What is an example of KNN? ›

Example: Suppose, we have an image of a creature that looks similar to cat and dog, but we want to know either it is a cat or dog. So for this identification, we can use the KNN algorithm, as it works on a similarity measure.

How to do nearest neighbor algorithm? ›

These are the steps of the algorithm:
  1. Initialize all vertices as unvisited.
  2. Select an arbitrary vertex, set it as the current vertex u. ...
  3. Find out the shortest edge connecting the current vertex u and an unvisited vertex v.
  4. Set v as the current vertex u. ...
  5. If all the vertices in the domain are visited, then terminate.

What are outliers in K nearest neighbors? ›

k-NN outlier

The distance to the kth nearest neighbor can also be seen as a local density estimate and thus is also a popular outlier score in anomaly detection. The larger the distance to the k-NN, the lower the local density, the more likely the query point is an outlier.

What is KNN nearest neighbor regression? ›

In the context of regression, KNN is often referred to as “K-Nearest Neighbors Regression” or “KNN Regression.” It's a simple and intuitive algorithm that makes predictions by finding the K nearest data points to a given input and averaging their target values (for numerical regression) or selecting the majority class ...

What is the KNN nearest neighbor graph? ›

The k-nearest neighbors graph (k-NNG) is a graph in which two vertices p and q are connected by an edge, if the distance between p and q is among the k-th smallest distances from p to other objects from P.

What is the nearest neighbor NN algorithm? ›

A nearest neighbor algorithm plots all vectors in a multi-dimensional space and uses each of the points to find a neighboring point that is nearest. Different types of nearest neighbor algorithms consider a neighboring point differently (more on that later).

What is the train k-nearest neighbor classifier? ›

The K-Nearest Neighbor classifier is a nonparametric classification method that classifies a pixel or segment by a plurality vote of its neighbors. K is the defined number of neighbors used in voting.

Top Articles
Latest Posts
Recommended Articles
Article information

Author: Edwin Metz

Last Updated:

Views: 5861

Rating: 4.8 / 5 (78 voted)

Reviews: 93% of readers found this page helpful

Author information

Name: Edwin Metz

Birthday: 1997-04-16

Address: 51593 Leanne Light, Kuphalmouth, DE 50012-5183

Phone: +639107620957

Job: Corporate Banking Technician

Hobby: Reading, scrapbook, role-playing games, Fishing, Fishing, Scuba diving, Beekeeping

Introduction: My name is Edwin Metz, I am a fair, energetic, helpful, brave, outstanding, nice, helpful person who loves writing and wants to share my knowledge and understanding with you.