AWS Builder Center

Machine Learning from Scratch – Day 10: Understanding K-Nearest Neighbors (KNN)

Understanding K-Nearest Neighbors (KNN)

Series: Machine Learning From Scratch (18 articles)

  1. …
  2. 10
    Machine Learning from Scratch – Day 10: Understanding K-Nearest Neighbors (KNN) This article

Introduction

In our previous article, we explored Random Forest, an ensemble learning algorithm that combines multiple decision trees to make predictions.
Today, we are going to learn another interesting machine learning algorithm: K-Nearest Neighbors (KNN).
Imagine you move to a new city and want to find a restaurant similar to the ones you already like. What would you do?
You might look at nearby restaurants, check what they offer, and choose one based on the options around you.
KNN follows a similar idea: to predict something about a data point, it looks at the most similar data points around it.
It is one of the simplest machine learning algorithms to understand, but it can be surprisingly effective.

1. What is K-Nearest Neighbors?

K-Nearest Neighbors (KNN) is a supervised machine learning algorithm used for:
  • Classification – predicting a category.
  • Regression – predicting a numerical value.
The algorithm makes predictions by identifying the K closest data points to a new input.
Here, K represents the number of neighbors considered when making a prediction.
For example, imagine a dataset containing information about different fruits, including their weight and size.
A new fruit is introduced, and we want to determine whether it is an apple or an orange.
KNN examines the nearest fruits in the dataset and predicts the new fruit's category based on their labels.

2. How Does KNN Work?

KNN follows a simple process.
Step 1: Choose the value of K
Select how many neighboring data points the algorithm should consider.
For example, if K = 3, the algorithm examines the three nearest points.
Step 2: Calculate distances
Calculate the distance between the new data point and every point in the training dataset.
Step 3: Identify nearest neighbors
Sort the distances and select the K smallest ones.
Step 4: Make a prediction
  • For classification, choose the most common class among the neighbors.
  • For regression, calculate the average (or another suitable aggregation) of their target values.

3. Understanding Distance Calculation

KNN depends heavily on measuring the distance between data points.
One of the most commonly used distance metrics is Euclidean Distance.
The formula is:
\[ d(p,q)=\sqrt{\sum_{i=1}^{n}(p_i-q_i)^2} \]
For two-dimensional data:
\[ d=\sqrt{(x_2-x_1)^2+(y_2-y_1)^2} \]
Let's understand with an example.
Consider two points:
  • Point A = (2, 3)
  • Point B = (5, 7)
Using Euclidean distance:
\[ d=\sqrt{(5-2)^2+(7-3)^2} \]
\[ d=\sqrt{9+16} \]
\[ d=\sqrt{25}=5 \]
Therefore, the distance between the two points is 5 units.
Other distance metrics include:
  • Manhattan Distance
  • Minkowski Distance
  • Hamming Distance
The appropriate metric depends on the nature of the dataset and its features.

4. Understanding the Value of K

Choosing the correct value of K is important because it affects the model's predictions.
Let's consider two situations.
When K = 1
The algorithm considers only the closest data point.
This can make the model sensitive to noise and outliers.
When K = 5
The algorithm considers five nearby points and uses majority voting for classification.
This can produce more stable predictions, although it may also overlook smaller local patterns.

What happens when K is too small or too large?

K value
Possible effect
Very small K
Sensitive to noise; may overfit
Moderate K
Can balance local patterns and noise
Very large K
May oversmooth boundaries; may underfit
A common starting point is to experiment with odd values of K in binary classification to reduce voting ties.
However, odd K is not a universal requirement. The best value should be selected using validation or cross-validation.

5. Why Is Feature Scaling Important in KNN?

This is one of the most important concepts when working with KNN.
Imagine a dataset containing:
  • Age: 18–60
  • Annual income: ₹2,00,000–₹20,00,000
Income has much larger numerical values than age.
Since KNN calculates distances, income could dominate the distance calculation even if age is equally important.
To avoid this problem, we use feature scaling.
Two commonly used techniques are:
  1. Standardization – transforms features to have approximately zero mean and unit variance.
  1. Min-Max Scaling – transforms values into a specified range, commonly 0 to 1.
For KNN, scaling numerical features is generally important when they use different units or ranges.

6. KNN for Classification and Regression

KNN can solve two different types of prediction problems.

KNN Classification

It predicts a category using majority voting.
Example:
Suppose the five nearest neighbors have these labels:
  • Apple
  • Apple
  • Orange
  • Apple
  • Orange
The predicted category is Apple because it appears three times.

KNN Regression

Instead of predicting a category, KNN predicts a numerical value.
For example, suppose the prices of the three nearest houses are:
  • ₹40 lakh
  • ₹45 lakh
  • ₹50 lakh
The predicted price using their average is:
\[ \frac{40+45+50}{3}=45 \]
The predicted house price is ₹45 lakh.

7. Implementing KNN Using Python

Now let's implement KNN using Scikit-learn.
We will use the Iris dataset to classify flowers into different species.

Step 1: Import libraries

import numpy as npfrom sklearn.datasets import load_irisfrom sklearn.model_selection import train_test_splitfrom sklearn.preprocessing import StandardScalerfrom sklearn.neighbors import KNeighborsClassifierfrom sklearn.metrics import accuracy_score, classification_report

Step 2: Load the dataset

iris = load_iris()X = iris.datay = iris.target
The dataset contains four numerical features:
  • Sepal length
  • Sepal width
  • Petal length
  • Petal width
The target represents the flower species.

Step 3: Split the dataset

X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=42, stratify=y)
We use 80% of the data for training and 20% for testing.

Step 4: Apply feature scaling

scaler = StandardScaler()X_train = scaler.fit_transform(X_train)X_test = scaler.transform(X_test)
Notice that we use  fit_transform()  on training data and only  transform()  on testing data.
This prevents information from the test dataset from influencing the scaling parameters.

Step 5: Train the KNN model

model = KNeighborsClassifier(n_neighbors=5)model.fit(X_train, y_train)
Here,  n_neighbors=5  means the algorithm considers the five nearest neighbors.

Step 6: Make predictions

y_pred = model.predict(X_test)

Step 7: Evaluate the model

accuracy = accuracy_score(y_test, y_pred)print("Accuracy:", accuracy)print(classification_report(y_test, y_pred))
The accuracy and classification report help us understand how well the model performs on unseen test data.
Remember that a high accuracy on one dataset does not automatically mean the model will perform equally well on other datasets.

8. Advantages and Disadvantages of KNN

Advantages
Disadvantages
Easy to understand and implement
Prediction can be slow on large datasets
No complex training process
Requires feature scaling in many cases
Supports classification and regression
Sensitive to irrelevant features
Can model nonlinear decision boundaries
Sensitive to the choice of K
Makes few assumptions about data distribution
Can struggle with high-dimensional data

9. Real-World Applications of KNN

KNN is used in several practical applications.
7
1. Recommendation Systems
Finding users or products with similar characteristics to recommend relevant items.
2. Healthcare
Supporting classification tasks using similarities between patient data, where appropriate clinical validation is essential.
3. Image Recognition
Classifying images based on similarities between their extracted features.
4. Pattern Recognition
Recognizing patterns in handwritten characters, documents, and other data.

10. Key Takeaways

Let's summarize what we learned today:
  • KNN stands for K-Nearest Neighbors.
  • It is a supervised learning algorithm.
  • It supports classification and regression.
  • It uses distance metrics to identify nearby data points.
  • K controls how many neighbors participate in prediction.
  • Feature scaling is important because KNN relies on distance calculations.
  • Choosing the right K can improve model performance.
KNN demonstrates an important machine learning idea: sometimes, understanding the similarities between existing examples is enough to make useful predictions.

Coming Next – Day 11: Understanding Naive Bayes

In the next article, we will explore Naive Bayes, a probabilistic machine learning algorithm based on Bayes' Theorem.
We will understand conditional probability, the independence assumption, and how Naive Bayes is used in spam detection and text classification.
#MachineLearning #MachineLearningFromScratch #KNN #Python #ScikitLearn #AI #AWSBuilderCenter #LearningJourney

Series: Machine Learning From Scratch (18 articles)

  1. …
  2. 10
    Machine Learning from Scratch – Day 10: Understanding K-Nearest Neighbors (KNN) This article
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article