Machine Learning · 5 of 20

K-Nearest Neighbors tutorial

Predicts from the labels or values of nearby observations. Learn the concept, implement it from scratch, and apply it with scikit-learn.

Category
Supervised learning
Core idea
ŷ(x) = Aggregate({yᵢ : i ∈ Nₖ(x)})
Typical use
Simple classification, recommendation, similarity search.
Practical tool
scikit-learn

What is K-Nearest Neighbors?

K-Nearest Neighbors is a supervised learning technique. Predicts from the labels or values of nearby observations. Its central idea is summarized by ŷ(x) = Aggregate({yᵢ : i ∈ Nₖ(x)}).

This guide connects theory to practice. You will trace the input, intermediate process, and output; decode the notation; run a dependency-light implementation; then repeat the workflow with scikit-learn and evaluate the result.

By the end of this tutorial, you will be able to

  • Explain when K-Nearest Neighbors is appropriate and what assumptions it makes.
  • Read its mathematical notation or complexity statement without guessing what the symbols mean.
  • Follow and modify a from-scratch Python implementation.
  • Build a practical workflow with scikit-learn and choose useful evaluation checks.

Prerequisites and tools

You do not need an advanced software stack. Start with a recent Python environment and the fundamentals below, then install only the packages used by the practical example.

  • Comfort with Python functions, NumPy arrays, and basic descriptive statistics.
  • A clear distinction between training data, validation data, and untouched test data.
  • Familiarity with features, targets, preprocessing, and task-appropriate evaluation metrics.
LanguagePython 3
Primary libraryscikit-learn
Learning modeFrom scratch + library

How K-Nearest Neighbors works

  1. 1

    Input

    Stored examples and a new query point.

  2. 2

    Prepare and configure

    Check shapes, value ranges, ordering assumptions, missing values, and the parameters that control the algorithm’s behavior.

  3. 3

    Algorithm process

    Measure distance and select the k closest examples.

  4. 4

    Output

    A local majority class or average value.

  5. 5

    Validate

    Tune k with cross-validation and track both predictive quality and inference latency.

Formula and intuition

ŷ(x) = Aggregate({yᵢ : i ∈ Nₖ(x)})

Nₖ(x) is the set of k nearest training examples; Aggregate is a vote for classification or a mean for regression.

The notation captures the main operation or complexity statement behind K-Nearest Neighbors. Read it together with the symbol key above and the step-by-step process in this guide.

When to use K-Nearest Neighbors

Simple classification, recommendation, similarity search.

Learning tip

Change one parameter at a time in the interactive lesson, replay the animation, and connect the visible change to the input, process, and output described above.

K-Nearest Neighbors from scratch in Python

This dependency-light example emphasizes the algorithm’s mechanics so each important step remains visible.

PythonEducational implementation
import numpy as np

# labeled training points plus one new query point to classify
rng = np.random.default_rng(0)
X_train = rng.normal(0, 1, (200, 2))
y_train = (X_train[:, 0] + X_train[:, 1] > 0).astype(int)
query = np.array([0.5, 0.2])

# find the k closest training points and let them vote on the label
k = 5
distances = np.linalg.norm(X_train - query, axis=1)
nearest = np.argsort(distances)[:k]
prediction = np.bincount(y_train[nearest]).argmax()
How to use this example

Run it once unchanged, inspect the output, and then alter one input or parameter. The compact implementation is designed for learning; use the tested library workflow below for real projects.

Build K-Nearest Neighbors with scikit-learn

KNeighborsClassifier handles distance calculation, neighbor weighting, and efficient search backends behind a standard estimator interface.

Recommended environment

JupyterLab, Google Colab, or VS Code

Create an isolated virtual environment for a local project, or paste the cells into a hosted notebook. Pin package versions before deploying a reproducible application.

Install the required package python -m pip install scikit-learn
  1. Prepare the data.Stored examples and a new query point. Validate its shape, type, range, and ordering before training or execution.
  2. Configure the algorithm.Begin with explicit, conservative parameters and a fixed random seed whenever the library supports one.
  3. Fit or execute.Measure distance and select the k closest examples.
  4. Inspect the result.A local majority class or average value. Then apply the evaluation checks in the next section.
Pythonscikit-learn workflow
from sklearn.datasets import load_iris
from sklearn.metrics import classification_report
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.3, stratify=y, random_state=42
)
model = make_pipeline(
    StandardScaler(),
    KNeighborsClassifier(n_neighbors=7, weights="distance"),
)
model.fit(X_train, y_train)
print(classification_report(y_test, model.predict(X_test)))

API details and version-specific options: official scikit-learn reference →

How to evaluate the result

A successful run is not enough. Evaluate the output against the intended use, compare it with a simple baseline, and preserve a genuinely unseen test case whenever the task involves learned parameters.

  • Tune k with cross-validation and track both predictive quality and inference latency.
  • Inspect neighbor distances for uncertain queries; distant neighbors suggest poor local support.
Reproducibility check

Record the data version, package versions, parameters, random seeds, and evaluation procedure. Re-run the same workflow before publishing a benchmark or deploying a model.

Pitfalls and how to avoid them

These failure modes are common in tutorials and production systems. Treat them as review questions, not just after-the-fact debugging advice.

  • Unscaled features dominate Euclidean distance.
  • Prediction becomes expensive as the stored training set grows.
  • Distance loses discrimination in very high-dimensional spaces.

Before using K-Nearest Neighbors in a project

  • Define the prediction or discovery objective before selecting the algorithm.
  • Split data before fitting preprocessing and tune only inside cross-validation.
  • Record data versions, random seeds, features, hyperparameters, and evaluation metrics.
  • Compare against a simple baseline and inspect errors by meaningful subgroups.
  • Monitor input drift and real-world performance after deployment.

Official documentation and next steps

Primary software reference scikit-learn

Use the official documentation to confirm supported parameters, current defaults, input requirements, and version changes.

Read official documentation →

This guide is an educational introduction, not a substitute for domain validation. For consequential applications, review the source documentation, test against representative data, and involve a subject-matter expert.

See K-Nearest Neighbors in motion

Open the interactive lesson to adjust parameters, scrub through the process, replay the animation, and compare the explanation with the Python code.

Launch visualization →