Dev.to AI πŸ€– Ai πŸ‘ 0 πŸ“– 5 min read

Understand K-Nearest Neighbors (KNN)!

πŸš€ Machine Learning Series : Let's Understand K-Nearest Neighbors (KNN)! In our last post, we explored Logistic Regression and learned how a machine uses probabilities to make classification decisions. Today, let's mov

πŸš€ Machine Learning Series : Let's Understand K-Nearest Neighbors (KNN)!

In our last post, we explored Logistic Regression and learned how a machine uses probabilities to make classification decisions.

Today, let's move to another interesting algorithm: K-Nearest Neighbors (KNN).

Before jumping into the technical part, think about this…

Imagine you move to a new city and want to find a good restaurant. What would you do? Probably ask people living nearby or check out restaurants that are popular in that area.

You are basically using the opinions of your nearest neighbours to make a decision!

Interestingly, KNN follows a similar idea. πŸ˜„

Let's break it down!

πŸ“Œ 1. What is K-Nearest Neighbors?

K-Nearest Neighbors (KNN) is a supervised Machine Learning algorithm used for both classification and regression.

The idea behind it is quite simple:

To predict something about a new data point, look at the most similar data points around it.

For example, suppose we have a dataset containing information about different fruits, including their weight and size.

Now, we receive information about a new fruit, but we don't know whether it is an Apple or an Orange.

Instead of guessing, KNN looks at the closest fruits in the existing dataset and uses their labels to make a prediction.

That's how KNN works!

πŸ” 2. Types of KNN

KNN can be used for two main tasks:

1. KNN for Classification

It predicts a category by checking the majority class among its nearest neighbours.

Example: Predicting whether an email is Spam or Not Spam.

2. KNN for Regression

Instead of predicting a category, it predicts a numerical value, usually by taking the average of the target values of its nearest neighbours.

Example: Predicting the price of a house based on similar nearby houses.

βš™οΈ 3. How Does KNN Actually Work?

Let's understand this with a simple example.

Suppose we want to classify a new fruit as an Apple or an Orange.

KNN follows these steps:

Step 1: Choose K

First, decide how many neighbours we want to consider.

Let's say K = 5.

Step 2: Calculate Distance

The algorithm calculates the distance between our new fruit and all the existing fruits in the dataset.

Step 3: Find the Nearest Neighbours

It selects the five fruits with the smallest distances.

Step 4: Majority Voting

Now, let's say among those five neighbours:

  • 3 are Apples.
  • 2 are Oranges.

Since Apples have more votes, KNN classifies our new fruit as an Apple.

And that's it! We've made a prediction using the nearest neighbours.

🎯 4. What is K in KNN?

You will see the letter K everywhere when learning this algorithm.

So, what exactly does it mean?

K simply represents the number of nearest neighbours the algorithm considers before making a prediction.

Let's understand what happens when we change its value.

  • K = 1: The prediction depends on just the closest data point.
  • K = 3: The algorithm considers the three closest points.
  • K = 5: It considers the five closest points.
  • K = 10: It considers the ten closest points.

But here's something interesting!

Choosing a very small K can make the model sensitive to noise, while choosing a very large K can make it overlook important local patterns.

This is why selecting the right value of K matters.

πŸ“ 5. How Does KNN Calculate Distance?

Now, you might have a question:

How does the algorithm know which data points are nearest?

It uses something called Distance Metrics.

Let's look at three commonly used metrics.

1. Euclidean Distance

Think of this as the straight-line distance between two points.

It is one of the most commonly used distance metrics in KNN.

Formula:

d = √[(xβ‚‚ - x₁)Β² + (yβ‚‚ - y₁)Β²]

2. Manhattan Distance

Imagine walking through city streets. You can move horizontally and vertically, but not diagonally through buildings.

That's the basic idea behind Manhattan Distance.

Formula:

d = |xβ‚‚ - x₁| + |yβ‚‚ - y₁|

3. Minkowski Distance

Think of Minkowski Distance as a generalized version of distance calculation.

By changing its parameter p, we can obtain different distance metrics.

Formula:

d = (Ξ£ |xα΅’ - yα΅’|α΅–)^(1/p)

πŸ“Š 6. Why is Feature Scaling Important in KNN?

This is something beginners often overlook!

Imagine our dataset contains two features:

  • Age: 18–60
  • Annual Income: 20,000–10,00,000

Notice the difference in their numerical ranges?

Since KNN uses distance calculations, features with much larger numerical values can dominate the distance.

As a result, the model may give too much importance to one feature.

To avoid this, we use Feature Scaling.

Two commonly used techniques are:

  • Standardization – StandardScaler
  • Normalization – MinMaxScaler

In simple words, feature scaling brings features to comparable numerical scales so that distance calculations are more balanced.

🧠 7. How Do We Choose the Best K?

Now comes another important question.

Should we always use K = 5?

Absolutely not!

The best value of K depends on our dataset.

One common way to find a suitable K is Cross-Validation.

We test different values of K, compare their performance, and select the one that performs best on validation data.

For example:

K = 1, 3, 5, 7, 9, 11

We can compare their validation accuracy or other relevant evaluation metrics.

For binary classification, odd values are sometimes preferred to reduce the possibility of tied votes.

βœ… 8. Advantages of KNN

  • Easy to understand and implement.
  • No separate model-training process is required.
  • Works for both classification and regression.
  • Can identify nonlinear patterns.
  • Useful for similarity-based predictions.

⚠️ 9. Limitations of KNN

  • Can be slow when working with large datasets.
  • Requires memory to store training data.
  • Sensitive to noisy and irrelevant features.
  • Feature scaling is important.
  • Can struggle with high-dimensional datasets.

🌍 10. Where is KNN Used in Real Life?

You might be surprised to know that this simple algorithm has several applications.

  • Healthcare – Finding patients with similar medical characteristics.
  • Recommendation Systems – Finding similar users or products.
  • Image Recognition – Classifying images based on similar patterns.
  • Finance – Supporting credit risk classification.
  • Pattern Recognition – Identifying similar data points.

πŸ’‘ What Did We Learn Today?

KNN teaches us a very interesting idea: sometimes, to understand something new, looking at what is already around it can be enough to make a useful prediction.

The four things I would remember from today's learning are:

  • K determines the number of neighbours.
  • Distance Metrics help identify the nearest points.
  • Majority Voting decides the predicted class.
  • Feature Scaling helps make distance calculations meaningful.

We'll continue exploring classification algorithms in our next post with Decision Trees, where we'll understand how a machine makes decisions by asking a series of questions.

πŸ’¬ One Question Before You Leave!

Imagine we choose K = 1 in our KNN model.

If the closest neighbour is incorrectly labelled because of noise, what do you think will happen to our prediction?

And what if we choose K = 50?

I'd love to hear your thoughts in the comments!

Let's keep learning, experimenting, and growing together. πŸš€

100DaysOfAI #MachineLearning #KNN #Classification #Python #DataScience #ArtificialIntelligence

πŸ“° Read the original article on Dev.to AI

Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.