Classification using Nearest Neighbour (k-NN) Classifier
Foundations of the k-Nearest Neighbour (k-NN) Classifier
The -Nearest Neighbour (-NN) algorithm is a foundational supervised learning algorithm utilized primarily for pattern classification and regression tasks. Unlike unsupervised techniques such as -Means—which clusters unlabeled observations based on internal data distributions—-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 ( where is the number of training instances).
The k-NN Decision Mechanics and Voting Logic
The fundamental premise of -NN is that instances possessing similar attribute values reside within close proximity to one another within feature space.
Core Algorithmic Steps
- Receive an unseen query instance with known feature attributes but an unknown class label.
- Calculate the distance between the unseen instance and every labeled instance stored in the training dataset according to a defined distance metric.
- Rank all training instances by proximity and identify the training instances that possess the shortest distance to the query instance.
- Aggregate the class labels of these nearest neighbours and assign the most frequently occurring label (the statistical mode or majority vote) to the unseen instance.

The Role of the Hyperparameter
The choice of the hyperparameter directly dictates the decision boundary and classification outcome:
- When , 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 , 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 (), 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 A | Attribute B | Attribute C | Attribute D | Attribute E | CLASS label |
|---|---|---|---|---|---|
| Yes | No | A | negative | ||
| No | No | B | positive | ||
| Yes | No | A | ?? |
Comparing the unseen instance against the training samples:
- Attribute A matches the first instance (
Yes). - Attribute B matches both instances (
No). - Attribute C () is substantially closer to than to .
- Attribute D () is substantially closer to than to .
- 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 -dimensional vector space (), where denotes the total number of descriptive attributes:
- Two Attributes (): Instances are plotted on a Cartesian 2D plane with Attribute 1 on the horizontal axis () and Attribute 2 on the vertical axis (), forming coordinate pairs and .
- Three Attributes (): Instances occupy a 3D coordinate volume represented as triplets .
- Attributes (): Instances are formalized as vectors in hyper-dimensional space:
Mathematical Foundations of Distance Metrics
Any distance function used to evaluate proximity in -NN must satisfy the formal mathematical axioms of a metric space:
- Identity of Indiscernibles (Self-Distance): The distance from any point to itself is zero:
- Symmetry Condition: The distance from point to point is identical to the distance from to :
- Triangle Inequality: The direct distance between two points is always less than or equal to the route traversing an intermediate third point (the shortest path between two points is a straight line):
Euclidean Distance
Euclidean distance represents the straight-line geometric distance between two points based on the generalized Pythagorean Theorem.

- In a 2-dimensional space between and :
- In a 3-dimensional space between and :
- In an -dimensional feature space between and :
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.

For two instances and , the distance is the sum of absolute coordinate differences:
For an -dimensional space:
Worked Example
Given two data points and :
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.

Formally, for vectors and :
Worked Example
Consider two multi-dimensional feature vectors:
Computing the absolute difference for each attribute index:
- Attribute 1:
- Attribute 2:
- Attribute 3:
- Attribute 4:
- Attribute 5:
- Attribute 6:
The maximum difference occurs in the third dimension, yielding:
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 :
- 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 .
Feature Weighting
When specific attributes hold greater domain relevance, non-uniform weights can be integrated into the distance calculation:
Subject to the constraint that weights sum to unity:
Distance Between Categorical Attributes
A notable theoretical limitation of -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 , and distance between non-identical values equals :
For example, evaluating the attribute Colour:
Ordinal Categorical Difference Scheme
When categories possess an intrinsic natural order (e.g., Small, Medium, Large), fractional intermediate distances can be defined:
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 / Description | Values / Range | Raw Data Type | Transformed Data Type | Role |
|---|---|---|---|---|---|
| 1 | English Speaker (TA is native speaker or not) | , | Integer | Binominal | Regular |
| 2 | Instructor ID | Discrete identifier ranging from to | Integer | Polynominal | Regular |
| 3 | Course ID | Discrete identifier ranging from to | Integer | Polynominal | Regular |
| 4 | Summer (Course offered in summer or other semester) | , | Integer | Binominal | Regular |
| 5 | Class Size | Numeric student count per section | Integer | Integer | Regular |
| 6 | Score Category (Evaluation rating given to TA) | , , | Integer | Polynominal | Label |
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 IDandCourse IDare qualitative categorical identifiers; calculating an arithmetic mean or sum across instructor IDs is mathematically meaningless. These attributes must be transformed topolynominal(nominal variables possessing more than two distinct states). - Attributes
English SpeakerandSummerreflect two-state qualitative indicators and must be mapped tobinominal. Score Categoryrepresents the categorical outcome to predict and must be assigned the special role oflabel.Class Sizeis the only true continuous integer attribute representing a scalar magnitude.
RapidMiner Implementation Workflow
The construction of an end-to-end -NN workflow in RapidMiner requires explicit data ingestion, type preprocessing, role configuration, model training, and performance validation.

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 namesis unchecked because the source file does not contain a header row.
2. Attribute Renaming (Rename)
Assigns descriptive names to default headers Att1 through Att6:
Att1English SpeakerAtt2InstructorAtt3CourseAtt4SummerAtt5Class SizeAtt6Score Category
3. Converting Multi-Valued Attributes (Numerical to Polynominal)
- Parameter
attribute filter typeset tosubset. - Selected attributes:
Course,Instructor,Score Category. - Converts these integer encodings into nominal factors.
4. Converting Binary Attributes (Numerical to Binominal)
- Parameter
attribute filter typeset tosubset. - Selected attributes:
English Speaker,Summer. - Configuration thresholds:
min = 2.0,max = 2.0. - Conversion mechanism: All values falling within the range (the value ) are converted to
false; all remaining values outside this range (the value ) are converted totrue.
5. Setting Target Label (Set Role)
- Parameter
attribute nameset toScore Category. - Parameter
target roleset tolabel.
6. Validation Subprocess Architecture (Split Validation)
- Splits the preprocessed dataset into two independent subsets:
- Training subset: of instances (
split ratio = 0.7,split = relative,sampling type = automatic). - Testing subset: Remaining of instances ( instances).
- Training subset: of instances (

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 thek-NNoperator (configured with hyperparameter ). The resulting trained model object passes to the output port (mod). - Testing Phase: The trained model from
modand the unseen test partition fromtesare passed into theApply Modeloperator. The resulting classified dataset passes via its labeled output port (lab) into thePerformance (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 test instances.

Confusion Matrix Table ()
| True 3 (Good) | True 2 (Medium) | True 1 (Low) | Class Precision | |
|---|---|---|---|---|
| pred. 3 | 7 | 5 | 5 | |
| pred. 2 | 7 | 6 | 4 | |
| pred. 1 | 2 | 4 | 6 | |
| Class Recall | 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:
- instances of class
3correctly predicted as3. - instances of class
2correctly predicted as2. - instances of class
1correctly predicted as1. - Total correct predictions: .
Class Precision
Precision measures the proportion of positive identifications that were correct for a given predicted class:
- Precision (Class 3):
- Precision (Class 2):
- Precision (Class 1):
Class Recall
Recall measures the proportion of actual positives that were identified correctly:
- Recall (Class 3):
- Recall (Class 2):
- Recall (Class 1):
Hyperparameter Tuning
A baseline model evaluated at is sensitive to localized data noise and outliers. Systematically modifying 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.