Skip to main content

K-Nearest Neighbors (KNN)


K-Nearest Neighbors (KNN) Algorithm: Simple Math and Example

Let's break down the mathematical concept behind the KNN algorithm and go through a simple example.

1. Mathematical Concept

KNN works by finding the K closest points in the feature space (based on distance metrics such as Euclidean distance) to classify or predict a new data point.

  • Step 1: Choose a number K (the number of nearest neighbors).
  • Step 2: Calculate the distance between the new data point and all other points in the training dataset.
  • Step 3: Sort the distances and pick the K smallest distances.
  • Step 4: For classification, assign the class label based on the majority of the K neighbors.
  • Step 5: For regression, calculate the average value of the K neighbors and assign it as the prediction.

2. Distance Metric: Euclidean Distance

For classification and regression, KNN typically uses the Euclidean distance to measure how "far" a point is from others.

The Euclidean distance between two points (x₁, y₁) and (x₂, y₂) in 2D space is given by:

            d = √((x₁ - x₂)² + (y₁ - y₂)²)
        

For higher-dimensional spaces (e.g., 3D, 4D), it’s generalized as:

            d = √((x₁ - x₂)² + (y₁ - y₂)² + (z₁ - z₂)² + ...)
        

3. Example of KNN for Classification (2D Space)

Imagine you have a simple 2D dataset with two classes: Red and Blue. Your goal is to classify a new point based on its K nearest neighbors.

Step-by-Step Example:

Dataset:

We have a set of 6 points in 2D space with labels:

X₁ X₂ Label
1 2 Red
2 3 Red
3 3 Blue
6 6 Blue
7 8 Blue
8 8 Red

New Point:

Let's classify the new point P = (5, 5).

Distance Calculation (using Euclidean distance):

            d(P, (1, 2)) = √((5 - 1)² + (5 - 2)²) = √(16 + 9) = √25 = 5
        
            d(P, (2, 3)) = √((5 - 2)² + (5 - 3)²) = √(9 + 4) = √13 ≈ 3.61
        
            d(P, (3, 3)) = √((5 - 3)² + (5 - 3)²) = √(4 + 4) = √8 ≈ 2.83
        
            d(P, (6, 6)) = √((5 - 6)² + (5 - 6)²) = √(1 + 1) = √2 ≈ 1.41
        
            d(P, (7, 8)) = √((5 - 7)² + (5 - 8)²) = √(4 + 9) = √13 ≈ 3.61
        
            d(P, (8, 8)) = √((5 - 8)² + (5 - 8)²) = √(9 + 9) = √18 ≈ 4.24
        

Find K Nearest Neighbors:

Let’s choose K = 3. The 3 closest points to P = (5, 5) are:

  • (6, 6) with distance 1.41 (Label: Blue)
  • (3, 3) with distance 2.83 (Label: Blue)
  • (2, 3) with distance 3.61 (Label: Red)

Majority Voting:

Among the 3 nearest neighbors, 2 are Blue and 1 is Red. According to majority voting, we classify the point P = (5, 5) as Blue.

Final Classification:

The new point P = (5, 5) is classified as Blue based on the majority label of its K nearest neighbors.

4. Example of KNN for Regression (1D Space)

Let’s now use KNN for regression to predict a value instead of a class label.

Step-by-Step Example:

Dataset:

We have a dataset of 5 data points:

X Y
1 2
2 3
3 4
5 7
6 8

New Point:

The goal is to predict the value of Y for a new point X = 4.

Distance Calculation:

            d(4, 1) = |4 - 1| = 3
        
            d(4, 2) = |4 - 2| = 2
        
            d(4, 3) = |4 - 3| = 1
        
            d(4, 5) = |4 - 5| = 1
        
            d(4, 6) = |4 - 6| = 2
        

Find K Nearest Neighbors:

Let’s choose K = 3. The 3 closest points to X = 4 are:

  • (3, 4) with distance 1
  • (5, 7) with distance 1
  • (2, 3) with distance 2

Prediction (Regression):

The predicted value of Y is the average of the 3 nearest neighbors' Y-values:

            Ypred = (4 + 7 + 3) / 3 = 14 / 3 ≈ 4.67
        

Final Prediction:

The predicted value for X = 4 is approximately 4.67.

Further Reading




Contact Us

Name

Email *

Message *

Popular Posts

UGC NET Electronic Science Previous Year Question Papers with Solutions

Home / Engineering & Other Exams / UGC NET 2026 PYQ ⬇️ Download Papers and Solutions 📋 Exam Pattern 💡 Preparation Tips ❓ FAQs 📊 Exam Highlights: Electronic Science (88) Feature Details Junior Research Fellowship (JRF) ₹37,000 + HRA per month Eligibility M.Sc/M.Tech in Electronics (55%) Validity of Certificate JRF (3 Years) | Lectureship (Lifetime) 📥 Download UGC NET Electronics PDFs Complete collection of previous year question papers, answer keys and explanations for Subject Code 88. Start Downloading 📂 View All Question Papers June 2025 - Question Paper Download PDF June 2025 - Solved Paper + Explanation ...

MUSIC Algorithm Explained (with MATLAB + Simulator)

Practical Implementation of the MUSIC Algorithm The focus is on how the algorithm works computationally , not just theory, and it explains the denominator (a H E n E n H a) mathematically and intuitively. 1. Introduction The MUSIC (Multiple Signal Classification) algorithm is a high-resolution method used in signal processing and array processing to estimate the Direction of Arrival (DOA) of signals received by a sensor array. Unlike classical beamforming methods, MUSIC uses eigenvector decomposition of the covariance matrix to separate the signal subspace and noise subspace , allowing it to achieve much higher angular resolution. In practical implementations, MUSIC works by: Simulating or collecting array signals Computing the covariance matrix Performing eigenvalue decomposition Separating signal and noise subspaces Scanning possible angles using a steering vector Constructing a pseudo-spectrum where peaks indicate signal directions 2. Signal Mo...

BER vs SNR for M-ary QAM, M-ary PSK, QPSK, BPSK, ...(MATLAB Code + Simulator)

Bit Error Rate (BER) & SNR Guide Analyze communication system performance with our interactive simulators and MATLAB tools. 📘 Theory 🧮 Simulators 💻 MATLAB Code 📚 Resources BER Definition SNR Formula BER Calculator MATLAB Comparison 📂 Explore M-ary QAM, PSK, and QPSK Topics ▼ 🧮 Constellation Simulator: M-ary QAM 🧮 Constellation Simulator: M-ary PSK 🧮 BER calculation for ASK, FSK, and PSK 🧮 Approaches to BER vs SNR Calculation What is Bit Error Rate (BER)? The BER indicates how many corrupted bits are received compared to the total number of bits sent. It is the primary figur...

MATLAB Code for ASK, FSK, and PSK (with Online Simulator)

MATLAB Code for ASK, FSK, and PSK Comprehensive implementation of digital modulation and demodulation techniques with simulation results. 📘 Theory 📡 ASK Code 📶 FSK Code 🎚️ PSK Code 🕹️ Simulator 📚 Further Reading Amplitude Shift Frequency Shift Phase Shift Live Simulator ASK, FSK & PSK HomePage MATLAB Code MATLAB Code for ASK Modulation and Demodulation COPY % The code is written by SalimWireless.Com clc; clear all; close all; % Parameters Tb = 1; fc = 10; N_bits = 10; Fs = 100 * fc; Ts = 1/Fs; samples_per_bit = Fs * Tb; rng(10); binar...

PSD Calculation with FFT: MATLAB Tutorial for Signal Analysis

  Implementation Steps 1. FFT Computes the Frequency Content of a Signal FFT converts a time-domain signal to the frequency domain. If: The signal is sampled at rate $f_s$ You compute an $N_{\text{FFT}}$-point FFT Then each FFT bin corresponds to a frequency resolution of: $$\Delta f = \frac{f_s}{N_{\text{FFT}}}$$ So the FFT gives you accurate frequency content, assuming the signal is stationary and adequately sampled (Nyquist criterion met).  2. Magnitude Squared Gives Power (Not Amplitude) $$P[k] = |X[k]|^2$$ This gives power at each frequency bin, not just amplitude. It represents how much energy is present at each frequency. It's a key step for PSD.  3. Normalization Makes the PSD Physically Meaningful The equation: $$\text{PSD}[k] = \frac{|X[k]|^2}{N_{\text{FFT}} \cdot f_s \cdot U}$$ is derived from first principles and ensures that the u...

Constellation Diagrams of ASK, PSK, and FSK (with MATLAB Code + Simulator)

Constellation Diagrams: ASK, FSK, and PSK Comprehensive guide to signal space representation, including interactive simulators and MATLAB implementations. 📘 Overview 🧮 Simulator ⚖️ Theory 📈 Q-function 📚 Resources BASK Modulation Transmits one of two signals: 0 or $\sqrt{E_b}$, representing binary 0 and 1. Simple but sensitive to noise. BFSK Modulation Transmits one of two signals: $\sqrt{E_b}$ on the Y-axis or $\sqrt{E_b}$ on the X-axis. These are orthogonal signals. BPSK Modulation Transmits $+\sqrt{E_b}$ or $-\sqrt{E_b}$ (antipodal signaling). Most efficient binary scheme. ...

MATLAB code for BER vs SNR for M-QAM, M-PSK, QPSK, BPSK (with Simulation)

🧮 MATLAB Code for BPSK, M-ary PSK, and M-ary QAM Together 🧮 MATLAB Code for M-ary QAM 🧮 MATLAB Code for M-ary PSK 📚 Further Reading MATLAB Script for BER vs. SNR for M-QAM, M-PSK, QPSK, BPSK % Written by Salim Wireless clc; clear; close all; snr_db = -5:2:25; psk_orders = [2, 4, 8, 16, 32]; qam_orders = [4, 16, 64, 256]; ber_psk_results = zeros(length(psk_orders), length(snr_db)); ber_qam_results = zeros(length(qam_orders), length(snr_db)); for i = 1:length(psk_orders) ber_psk_results(i, :) = berawgn(snr_db, 'psk', psk_orders(i), 'nondiff'); end for i = 1:length(qam_orders) ber_qam_results(i, :) = berawgn(snr_db, 'qam', qam_orders(i)); end figure; semilogy(snr_db, ber_psk_results(1, :), 'o-', 'LineWidth', 1.5, 'DisplayName', 'BPSK'); hold on; for i = 2:length(psk_orders) semilogy(snr_db, ber_psk_results(i, :), 'o-', 'DisplayName', sprintf('%d-PSK', psk_or...

OFDM Symbols and Subcarriers Explained

This article explains how OFDM (Orthogonal Frequency Division Multiplexing) symbols and subcarriers work. It covers modulation, mapping symbols to subcarriers, subcarrier frequency spacing, IFFT synthesis, cyclic prefix, and transmission. Step 1: Modulation First, modulate the input bitstream. For example, with 16-QAM , each group of 4 bits maps to one QAM symbol. Suppose we generate a sequence of QAM symbols: s0, s1, s2, s3, s4, s5, …, s63 Step 2: Mapping Symbols to Subcarriers Assume N sub = 8 subcarriers. Each OFDM symbol in the frequency domain contains 8 QAM symbols (one per subcarrier): Mapping (example) OFDM symbol 1 → s0, s1, s2, s3, s4, s5, s6, s7 OFDM symbol 2 → s8, s9, s10, s11, s12, s13, s14, s15 … OFDM sym...