Classification using Nearest Neighbour (k-NN) Classifier

Foundations of the k-Nearest Neighbour (k-NN) Classifier

The kk-Nearest Neighbour (kk-NN) algorithm is a foundational supervised learning algorithm utilized primarily for pattern classification and regression tasks. Unlike unsupervised techniques such as kk-Means—which clusters unlabeled observations based on internal data distributions—kk-NN requires a designated target attribute known as the class label and relies on a labeled training set to guide predictions for unseen instances.

The algorithm is defined by two primary operational paradigms:

  • Instance-Based Learning: The algorithm does not construct an explicit, abstracted model during a training phase. Instead, it retains the entire training dataset in memory and compares unlabelled, unseen query instances directly against stored labeled records at the specific moment classification is requested.
  • Lazy Learning: Generalization beyond the training data is deferred until an explicit query is made. Consequently, the computational cost of model construction is zero, while the computational cost of querying and distance calculation scales directly with the volume of the training data (O(n)O(n) where nn is the number of training instances).

The k-NN Decision Mechanics and Voting Logic

The fundamental premise of kk-NN is that instances possessing similar attribute values reside within close proximity to one another within feature space.

Core Algorithmic Steps

  1. Receive an unseen query instance with known feature attributes but an unknown class label.
  2. Calculate the distance between the unseen instance and every labeled instance stored in the training dataset according to a defined distance metric.
  3. Rank all training instances by proximity and identify the kk training instances that possess the shortest distance to the query instance.
  4. Aggregate the class labels of these kk nearest neighbours and assign the most frequently occurring label (the statistical mode or majority vote) to the unseen instance.

Geometric example of k-NN decision boundary with k=1 and k=3

The Role of the Hyperparameter kk

The choice of the hyperparameter kk directly dictates the decision boundary and classification outcome:

  • When k=1k = 1, the query point (e.g., the green circle in the diagram) is assigned directly to the class of its single closest neighbour. In the provided geometric configuration, the single nearest neighbour is a blue square belonging to Class 1.
  • When k=3k = 3, the search radius expands to encompass the three nearest training points. In this broader neighbourhood, the instances comprise two red triangles (Class 2) and one blue square (Class 1). By majority vote (2>12 > 1), the test instance is classified as a red triangle (Class 2).

Example: Manual Instance Comparison

Consider a training dataset comprising two labeled records across five attributes alongside an unclassified third instance:

Attribute AAttribute BAttribute CAttribute DAttribute ECLASS label
YesNo100.2100.22424Anegative
NoNo50.050.01212Bpositive
YesNo80.980.92525A??

Comparing the unseen instance against the training samples:

  • Attribute A matches the first instance (Yes).
  • Attribute B matches both instances (No).
  • Attribute C (80.980.9) is substantially closer to 100.2100.2 than to 50.050.0.
  • Attribute D (2525) is substantially closer to 2424 than to 1212.
  • Attribute E matches the first instance (A).

Because the query point is markedly closer across all dimensions to the first training instance than to the second, a nearest neighbour classifier assigns the label negative.

Multi-Dimensional Spatial Representation

To compute geometric proximity, instances are conceptualized as discrete coordinate vectors within an nn-dimensional vector space (Rn\mathbb{R}^n), where nn denotes the total number of descriptive attributes:

  • Two Attributes (R2\mathbb{R}^2): Instances are plotted on a Cartesian 2D plane with Attribute 1 on the horizontal axis (xx) and Attribute 2 on the vertical axis (yy), forming coordinate pairs a=(a1,a2)\mathbf{a} = (a_1, a_2) and b=(b1,b2)\mathbf{b} = (b_1, b_2).
  • Three Attributes (R3\mathbb{R}^3): Instances occupy a 3D coordinate volume represented as triplets a=(a1,a2,a3)\mathbf{a} = (a_1, a_2, a_3).
  • nn Attributes (Rn\mathbb{R}^n): Instances are formalized as vectors in hyper-dimensional space:

a=(a1,a2,…,an)\mathbf{a} = (a_1, a_2, \dots, a_n)

b=(b1,b2,…,bn)\mathbf{b} = (b_1, b_2, \dots, b_n)

Mathematical Foundations of Distance Metrics

Any distance function Distance(A,B)\text{Distance}(A, B) used to evaluate proximity in kk-NN must satisfy the formal mathematical axioms of a metric space:

  1. Identity of Indiscernibles (Self-Distance): The distance from any point AA to itself is zero:

Distance(A,A)=0\text{Distance}(A, A) = 0

  1. Symmetry Condition: The distance from point AA to point BB is identical to the distance from BB to AA:

Distance(A,B)=Distance(B,A)\text{Distance}(A, B) = \text{Distance}(B, A)

  1. Triangle Inequality: The direct distance between two points is always less than or equal to the route traversing an intermediate third point CC (the shortest path between two points is a straight line):

Distance(A,B)≤Distance(A,C)+Distance(C,B)\text{Distance}(A, B) \le \text{Distance}(A, C) + \text{Distance}(C, B)

Euclidean Distance

Euclidean distance represents the straight-line geometric distance between two points based on the generalized Pythagorean Theorem.

Euclidean distance between two points in 2D space

  • In a 2-dimensional space between a=(a1,a2)\mathbf{a} = (a_1, a_2) and b=(b1,b2)\mathbf{b} = (b_1, b_2):

dEuclidean(a,b)=(a1−b1)2+(a2−b2)2d_{\text{Euclidean}}(\mathbf{a}, \mathbf{b}) = \sqrt{(a_1 - b_1)^2 + (a_2 - b_2)^2}

  • In a 3-dimensional space between a=(a1,a2,a3)\mathbf{a} = (a_1, a_2, a_3) and b=(b1,b2,b3)\mathbf{b} = (b_1, b_2, b_3):

dEuclidean(a,b)=(a1−b1)2+(a2−b2)2+(a3−b3)2d_{\text{Euclidean}}(\mathbf{a}, \mathbf{b}) = \sqrt{(a_1 - b_1)^2 + (a_2 - b_2)^2 + (a_3 - b_3)^2}

  • In an nn-dimensional feature space between a=(a1,a2,…,an)\mathbf{a} = (a_1, a_2, \dots, a_n) and b=(b1,b2,…,bn)\mathbf{b} = (b_1, b_2, \dots, b_n):

dEuclidean(a,b)=∑i=1n(ai−bi)2d_{\text{Euclidean}}(\mathbf{a}, \mathbf{b}) = \sqrt{\sum_{i=1}^n (a_i - b_i)^2}

Manhattan Distance (City Block Distance)

Manhattan distance measures the path traversed along grid lines aligned strictly with orthogonal coordinate axes, mirroring navigation through a city grid.

Manhattan distance visualization between coordinates (4, 2) and (10, 8)

For two instances a=(a1,a2)\mathbf{a} = (a_1, a_2) and b=(b1,b2)\mathbf{b} = (b_1, b_2), the distance is the sum of absolute coordinate differences:

dManhattan(a,b)=∣a1−b1∣+∣a2−b2∣d_{\text{Manhattan}}(\mathbf{a}, \mathbf{b}) = |a_1 - b_1| + |a_2 - b_2|

For an nn-dimensional space:

dManhattan(a,b)=∑i=1n∣ai−bi∣d_{\text{Manhattan}}(\mathbf{a}, \mathbf{b}) = \sum_{i=1}^n |a_i - b_i|

Worked Example

Given two data points a=(4,2)\mathbf{a} = (4, 2) and b=(10,8)\mathbf{b} = (10, 8):

dManhattan=∣10−4∣+∣8−2∣=6+6=12d_{\text{Manhattan}} = |10 - 4| + |8 - 2| = 6 + 6 = 12

Maximum Dimension Distance (Chebyshev Distance)

Maximum dimension distance is defined as the largest absolute difference observed across any single corresponding attribute dimension between two instances.

Maximum dimension distance calculation across corresponding vector elements

Formally, for vectors a\mathbf{a} and b\mathbf{b}:

dmax⁡(a,b)=max⁡1≤i≤n∣ai−bi∣d_{\max}(\mathbf{a}, \mathbf{b}) = \max_{1 \le i \le n} |a_i - b_i|

Worked Example

Consider two multi-dimensional feature vectors:

a=[6.3, 10, 20, −3.1, 6.2, 9]\mathbf{a} = [6.3,\, 10,\, 20,\, -3.1,\, 6.2,\, 9]

b=[4.2, 12, 3.0, 4.7, 6.6, 3]\mathbf{b} = [4.2,\, 12,\, 3.0,\, 4.7,\, 6.6,\, 3]

Computing the absolute difference for each attribute index:

  • Attribute 1: ∣6.3−4.2∣=2.1|6.3 - 4.2| = 2.1
  • Attribute 2: ∣10−12∣=2.0|10 - 12| = 2.0
  • Attribute 3: ∣20−3.0∣=17.0|20 - 3.0| = 17.0
  • Attribute 4: ∣−3.1−4.7∣=7.8|-3.1 - 4.7| = 7.8
  • Attribute 5: ∣6.2−6.6∣=0.4|6.2 - 6.6| = 0.4
  • Attribute 6: ∣9−3∣=6.0|9 - 3| = 6.0

The maximum difference occurs in the third dimension, yielding:

dmax⁡(a,b)=17.0d_{\max}(\mathbf{a}, \mathbf{b}) = 17.0

Data Preprocessing: Normalisation and Categorical Distances

Attribute Normalisation and Scaling

A critical vulnerability of distance metrics like Euclidean distance is sensitivity to feature scale. Attributes with large continuous numerical ranges (e.g., annual income ranging in tens of thousands) mathematically swamp attributes defined over smaller ranges (e.g., age ranging from 0 to 100), rendering the smaller attributes negligible in proximity calculations.

To prevent feature dominance, attributes are normalized so that all values span an identical range, typically [0,1][0, 1]:

  • One common approach calculates the spread (range) of all observed values for a given attribute and divides the shifted values by that range, mapping values to the interval [0,1][0, 1].

Feature Weighting

When specific attributes hold greater domain relevance, non-uniform weights w1,w2,…,wnw_1, w_2, \dots, w_n can be integrated into the distance calculation:

dw(a,b)=∑i=1nwi(ai−bi)2d_w(\mathbf{a}, \mathbf{b}) = \sqrt{\sum_{i=1}^n w_i (a_i - b_i)^2}

Subject to the constraint that weights sum to unity:

∑i=1nwi=1\sum_{i=1}^n w_i = 1

Distance Between Categorical Attributes

A notable theoretical limitation of kk-NN is the absence of an inherent spatial metric for categorical attributes. Several conversion heuristics are employed:

Binary Nominal Difference Scheme

For unordered nominal categories, distance between two identical values equals 00, and distance between non-identical values equals 11:

diff(x,y)={0if x=y1if x≠y\text{diff}(x, y) = \begin{cases} 0 & \text{if } x = y \\ 1 & \text{if } x \ne y \end{cases}

For example, evaluating the attribute Colour:

  • diff(Blue,Blue)=0\text{diff}(\text{Blue}, \text{Blue}) = 0
  • diff(Red,Blue)=1\text{diff}(\text{Red}, \text{Blue}) = 1
  • diff(Pink,Red)=1\text{diff}(\text{Pink}, \text{Red}) = 1
Ordinal Categorical Difference Scheme

When categories possess an intrinsic natural order (e.g., Small, Medium, Large), fractional intermediate distances can be defined:

  • diff(Large,Large)=0\text{diff}(\text{Large}, \text{Large}) = 0
  • diff(Large,Medium)=0.5\text{diff}(\text{Large}, \text{Medium}) = 0.5
  • diff(Large,Small)=1.0\text{diff}(\text{Large}, \text{Small}) = 1.0

Case Study: Teaching Assistant Evaluation (TAE) Dataset

The Teaching Assistant Evaluation (TAE) dataset (archived at the UCI Machine Learning Repository) consists of 151 records collected across five academic semesters at the University of Wisconsin-Madison. The dataset evaluates teaching performance of Teaching Assistants (TAs) broken down roughly equally into low, medium, and high scores.

  • Dataset Repository: http://archive.ics.uci.edu/ml/datasets/Teaching+Assistant+Evaluation
  • Raw Data Endpoint: http://archive.ics.uci.edu/ml/machine-learning-databases/tae/tae.data
  • Class Target: TA performance score (Score Category)

Attribute Specifications and Required Transformations

Attribute No.Attribute Name / DescriptionValues / RangeRaw Data TypeTransformed Data TypeRole
1English Speaker (TA is native speaker or not)1=native speaker1 = \text{native speaker}, 2=non-native speaker2 = \text{non-native speaker}IntegerBinominalRegular
2Instructor IDDiscrete identifier ranging from 11 to 2525IntegerPolynominalRegular
3Course IDDiscrete identifier ranging from 11 to 2626IntegerPolynominalRegular
4Summer (Course offered in summer or other semester)1=summer1 = \text{summer}, 2=other2 = \text{other}IntegerBinominalRegular
5Class SizeNumeric student count per sectionIntegerIntegerRegular
6Score Category (Evaluation rating given to TA)1=low1 = \text{low}, 2=medium2 = \text{medium}, 3=good3 = \text{good}IntegerPolynominalLabel

Rationale for Data Type Transformations

Machine learning algorithms interpret integer types numerically, which permits mathematical operations such as addition, subtraction, or multiplication.

  • Attributes such as Instructor ID and Course ID are qualitative categorical identifiers; calculating an arithmetic mean or sum across instructor IDs is mathematically meaningless. These attributes must be transformed to polynominal (nominal variables possessing more than two distinct states).
  • Attributes English Speaker and Summer reflect two-state qualitative indicators and must be mapped to binominal.
  • Score Category represents the categorical outcome to predict and must be assigned the special role of label.
  • Class Size is the only true continuous integer attribute representing a scalar magnitude.

RapidMiner Implementation Workflow

The construction of an end-to-end kk-NN workflow in RapidMiner requires explicit data ingestion, type preprocessing, role configuration, model training, and performance validation.

RapidMiner end-to-end k-NN process workflow

Step-by-Step Operator Pipeline

1. Data Ingestion (Read URL)
  • Retrieves the raw data table from http://archive.ics.uci.edu/ml/machine-learning-databases/tae/tae.data.
  • Column separators configured using the regular expression:
,\s*|;\s*|\s+
  • The parameter read attribute names is unchecked because the source file does not contain a header row.
2. Attribute Renaming (Rename)

Assigns descriptive names to default headers Att1 through Att6:

  • Att1 →\rightarrow English Speaker
  • Att2 →\rightarrow Instructor
  • Att3 →\rightarrow Course
  • Att4 →\rightarrow Summer
  • Att5 →\rightarrow Class Size
  • Att6 →\rightarrow Score Category
3. Converting Multi-Valued Attributes (Numerical to Polynominal)
  • Parameter attribute filter type set to subset.
  • Selected attributes: Course, Instructor, Score Category.
  • Converts these integer encodings into nominal factors.
4. Converting Binary Attributes (Numerical to Binominal)
  • Parameter attribute filter type set to subset.
  • Selected attributes: English Speaker, Summer.
  • Configuration thresholds: min = 2.0, max = 2.0.
  • Conversion mechanism: All values falling within the range [2.0,2.0][2.0, 2.0] (the value 22) are converted to false; all remaining values outside this range (the value 11) are converted to true.
5. Setting Target Label (Set Role)
  • Parameter attribute name set to Score Category.
  • Parameter target role set to label.
6. Validation Subprocess Architecture (Split Validation)
  • Splits the preprocessed dataset into two independent subsets:
    • Training subset: 70%70\% of instances (split ratio = 0.7, split = relative, sampling type = automatic).
    • Testing subset: Remaining 30%30\% of instances (4646 instances).

Split Validation sub-process architecture for training and testing phases

The internal architecture of the Split Validation operator contains two nested windows:

  • Training Phase: Receives the training data partitioned from the input port (tra) and feeds it into the k-NN operator (configured with hyperparameter k=1k = 1). The resulting trained model object passes to the output port (mod).
  • Testing Phase: The trained model from mod and the unseen test partition from tes are passed into the Apply Model operator. The resulting classified dataset passes via its labeled output port (lab) into the Performance (Classification) operator, which generates the statistical performance vector (per).

Performance Evaluation and Confusion Matrix Analysis

The classifier's predictive capability is evaluated using a Confusion Matrix (Performance Vector) across the 4646 test instances.

Annotated confusion matrix highlighting correctly predicted instances along the diagonal

Confusion Matrix Table (k=1k = 1)

True 3 (Good)True 2 (Medium)True 1 (Low)Class Precision
pred. 375541.18%41.18\%
pred. 276435.29%35.29\%
pred. 124650.00%50.00\%
Class Recall43.75%43.75\%40.00%40.00\%40.00%40.00\%Overall Accuracy: 41.30%

Analysis of Metric Calculations

Overall Accuracy

Accuracy is the ratio of total correct predictions to the total number of test instances:

Accuracy=∑Diagonal ElementsTotal Instances=7+6+646=1946≈41.30%\text{Accuracy} = \frac{\sum \text{Diagonal Elements}}{\text{Total Instances}} = \frac{7 + 6 + 6}{46} = \frac{19}{46} \approx 41.30\%

  • 77 instances of class 3 correctly predicted as 3.
  • 66 instances of class 2 correctly predicted as 2.
  • 66 instances of class 1 correctly predicted as 1.
  • Total correct predictions: 1919.
Class Precision

Precision measures the proportion of positive identifications that were correct for a given predicted class:

Precision=True Positives for Class cTotal Instances Predicted as Class c\text{Precision} = \frac{\text{True Positives for Class } c}{\text{Total Instances Predicted as Class } c}

  • Precision (Class 3):

77+5+5=717≈41.18%\frac{7}{7 + 5 + 5} = \frac{7}{17} \approx 41.18\%

  • Precision (Class 2):

67+6+4=617≈35.29%\frac{6}{7 + 6 + 4} = \frac{6}{17} \approx 35.29\%

  • Precision (Class 1):

62+4+6=612=50.00%\frac{6}{2 + 4 + 6} = \frac{6}{12} = 50.00\%

Class Recall

Recall measures the proportion of actual positives that were identified correctly:

Recall=True Positives for Class cTotal Actual Instances of Class c\text{Recall} = \frac{\text{True Positives for Class } c}{\text{Total Actual Instances of Class } c}

  • Recall (Class 3):

77+7+2=716=43.75%\frac{7}{7 + 7 + 2} = \frac{7}{16} = 43.75\%

  • Recall (Class 2):

65+6+4=615=40.00%\frac{6}{5 + 6 + 4} = \frac{6}{15} = 40.00\%

  • Recall (Class 1):

65+4+6=615=40.00%\frac{6}{5 + 4 + 6} = \frac{6}{15} = 40.00\%

Hyperparameter Tuning

A baseline model evaluated at k=1k = 1 is sensitive to localized data noise and outliers. Systematically modifying kk alters the smoothing of the decision boundary, affecting accuracy, precision, and recall.

Alternative Supervised Classifiers: Naïve Bayes

An alternative classification method to nearest neighbour approaches is the Naïve Bayes classifier:

  • Historical Origin: Named after 18th-century English statistician, philosopher, and Presbyterian minister Thomas Bayes.
  • Theoretical Basis: Grounded in Bayes' Theorem of conditional probability.
  • Data Requirements: Operates intrinsically on categorical attributes. Any continuous numerical attributes must undergo discretization (binning) prior to modeling.
  • Core Assumption: Assumes strong conditional independence among all feature attributes given the class label.

Academic Literature and References

  • Bramer, M. (2016). Principles of Data Mining (3rd ed.). London: Springer-Verlag, Chapter 3.
  • North, M. (2016). Data Mining for the Masses (2nd ed.), Chapter 7.
  • RapidMiner Studio Operator Reference Documentation.