KNN

Python · Machine Learning (Scikit-Learn)

Theory

K-nearest neighbours (KNN) classifies a new point by looking at the k training points closest to it and taking a majority vote of their labels (for regression, the average of their values). There is no real training step: fit simply stores the data, and all the work happens at prediction time, when distances to every stored point are computed, usually straight-line (Euclidean) distance.

k controls the trade-off: k=1 follows every noisy point and overfits, while a very large k blurs the classes together. Odd k avoids ties in two-class problems, and a good value is chosen with cross-validation. Because it relies on distances, features must be scaled, otherwise a column in rupees swamps one in years. kneighbors(X) returns the distances and positions of the neighbours, and predict_proba gives the share of neighbours in each class.

Why we use it

KNN is intuitive ('you are like your neighbours'), needs no assumptions about the shape of the data and can capture irregular boundaries. It is a good baseline and a natural fit for similarity-based tasks such as recommendations.

When to use it

Use KNN for small to medium datasets with a few scaled numeric features. Avoid it for very large datasets (slow predictions) or many features, where distances become less meaningful; tree ensembles or linear models scale better.

How it works

  1. New point to classify
  2. Compute its distance to every training point
  3. Sort and keep the k nearest
  4. Count the labels among those k neighbours
  5. Is there a tie? Yes: Odd k avoids it; sklearn takes the first class. No: Majority label wins.
  6. Predicted class (and share of votes)

Syntax

from sklearn.neighbors import KNeighborsClassifier
knn = KNeighborsClassifier(n_neighbors=5)
knn.fit(X_train_scaled, y_train)
knn.predict(X_new)  knn.predict_proba(X_new)
dist, idx = knn.kneighbors(X_new)

Example

knn = make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=5))
knn.fit(X_train, y_train)
print(knn.predict(X_test[:3]))

Key points

Python topics

Getting Started

Variables & Data Types

Operators

Strings

Lists

Tuples

Sets

Dictionaries

Control Flow

Loops

Functions & OOP

Working with Data

Tooling & Errors

File Handling

Exception Handling

NumPy Library

Pandas Basics

Data Cleaning

Combining DataFrames (SQL Joins & Unions)

GroupBy & SQL-Style Analytics

Reshaping & Workflow

Data Visualization

Machine Learning (Scikit-Learn)

Advanced Python & AI

T
Tech Town
Log InSign Up Free
Home SQL Python DSA Power BI Snowflake Databricks Spark Gen AI Practice Problems Contest Blog

Python for Data Analysts

From basics to business insights — the complete step-by-step Python roadmap. Click any topic in the sidebar to open it right here.

{{ sectionCount }}
Sections
{{ topicCount }}
Topics
Free
Forever
Hands-on practice Practice Python Online 141 Python questions for data analysts — strings, records, dates, statistics and regex — with hidden tests and instant verdicts. Start practising →
Section {{ sec.num }}

{{ sec.label }}

Python  /  {{ current.sectionLabel }}  /  {{ current.name }}

{{ current.name }}

Theory

{{ current.def }}

Why we use it

{{ rich.why }}

When to use it

{{ rich.when }}

Diagram

{{ rich.dg.caption }}

{{ tb.title }}
{{ c.v }}
{{ rich.dg.op }}
➜
{{ rich.dg.output.title }}
{{ c.v }}
{{ nd.label }}
{{ nd.sub }}
{{ nd.label }}
{{ nd.sub }}
{{ rich.dg.left.title }}
{{ it }}
{{ rich.dg.right.title }}
{{ it }}
Flowchart — how it works
{{ nd.text }}
{{ nd.text }}
◇ {{ nd.text }}
Yes → {{ nd.yes }}
No → {{ nd.no }}
Syntax
{{ current.syntax }}
Example
{{ current.example }}
▶ Try It Live — runs real Python 3.12 in your browser (first run loads the engine)
{{ liveOutput }}
{{ liveError }}
Key Points — click to check off as you learn
  • {{ pt.mark }} {{ pt.text }}

Share this topic