SeeingML
Working With Data Guide 6 of 8 · tap to switch
✦ Interactive Visual Guide 8 min · 4 hands-on labs · Beginner friendly

Euclidean Distance & Cosine Similarity

How recommenders, search engines, and AI embeddings measure closeness, and why high dimensions distort everyday geometry.

How does Spotify queue up the next track, or how does an AI search bar find the exact policy paragraph you meant? Both start by turning every item into a feature vector: a list of numbers treated as coordinates on a map so “similar” simply means “nearby.” Once items live in vector space, distance and angle rulers measure how close two songs, users, or documents really are.

Grab the glowing purple dot below (or nudge the sliders) to move across the song map (Energy vs. Tempo). Watch your coordinates [energy, tempo] update live while the recommender automatically locks onto the two nearest songs.

Interactive Lab 1: Feature Vectors in Space (Drag Your Mood Dot)
Vector: [55, 115]
60801001201401600255075100Tempo (BPM)Song Energy (0 to 100)Lo-Fi RainAcoustic CaféEvening JazzIndie DrivePop AnthemHouse ClubSprint TechnoCalm Ambient
55 / 100
115 BPM
Your mood vector [55, 115] sits in the mid-energy groove zone. Its two nearest neighbors are Indie Drive (distance 4.2) and Evening Jazz (distance 19.8). Every row in a dataset is simply a coordinate in space!

Euclidean Distance (L2) vs. Manhattan Distance (L1)

Even on a flat 2D street map, “distance” is a choice, not a single law of nature. Imagine traveling from corner A to corner B across a grid of city streets:

  • Straight-line distance (Euclidean, or L2): The shortest diagonal route straight from A to B, like a delivery drone flying over rooftops.
  • City-block distance (Manhattan, or L1): Driving strictly along east/west and north/south streets, adding horizontal steps plus vertical steps. Because it does not square large jumps, it stays gentler when one feature has an extreme outlier.
  • Chess-king distance (Chebyshev, or L∞): A chess king can step one square sideways, up, down, or diagonally in a single move, so total moves equal whichever single coordinate jump is largest.

Slide Blocks East (Δx, where Δ simply means “change in”) and Blocks North (Δy, change in y) below, then switch between all three rulers. Watch both the highlighted route on the street grid and the equal-distance shape on the right morph from Circle to Diamond to Square.

Interactive Lab 2: Three Rulers on a City Street Grid
Street Grid: Route from A to BA (0,0)B (4,3)Straight-Line (L2): diagonal = 5 unitsAll Points at Distance = 1L2 Circle (Straight ruler)
4 East
3 North
Straight-Line (Euclidean / L2) cuts diagonally across rooftops in 5 units, beating City-Block (7) because diagonal travel saves steps. It shines when features share a balanced scale and diagonal combinations matter equally, such as 2D maps or song coordinates.

Why text search and AI embeddings rely on Cosine Similarity

In text search and AI embeddings (lists of meaning coordinates learned by neural networks), a straight-line ruler can get tricked by document length.

Imagine plotting three documents on two clean word axes: X = mentions of "Football" and Y = mentions of "Recipe":

  • Short Match Tweet [4, 0.5]: Mentions Football 4 times with a tiny 0.5 Recipe score (a single passing food joke).
  • Long Match Report [16, 2]: Covers the exact same match at 4× the length ([4 × s, 0.5 × s]), so every word count scales up together.
  • Cooking Blog [0.5, 8]: Barely mentions Football (0.5) and mentions Recipe 8 times.

Look at the trap below when the Long Match Report is set to 4× length: straight-line Euclidean distance gets completely fooled by total word count and claims the Short Match Tweet is closer to the unrelated Cooking Blog than to the Match Report! Cosine Similarity ignores arrow length and looks strictly at the angle between arrows. Both football texts point in the exact same direction (0° apart, Cosine = 1.00), while the Cooking Blog points steeply upward along Recipe (~79° away, Cosine = 0.19, truly unrelated).

Slide Long Match Report Length down to 1× and back up to 5× to watch document length fool Euclidean distance while Cosine stays locked on topic.

Interactive Lab 3: Document Length vs. Topic Angle (Cosine Similarity)
Cosine(Tweet, Report) = 1.00
0246810048121620Mentions of "Recipe" (Y)Mentions of "Football" (X)θ = 79°(wide angle = unrelated)Euclidean: 8.30° angle · Euclidean: 12.1Tweet vs. Report: 0° (Cosine 1.00)Tweet vs. Cooking: 79° (Cosine 0.19)Long Report [16, 2]Short Tweet [4, 0.5]Cooking Blog [0.5, 8]
Euclidean (Smaller = closer)Fooled by length!
Tweet vs. Report: 12.1 | Tweet vs. Cooking: 8.3
Cosine (1.00 = exact same topic)Locked on topic!
Tweet vs. Report: 1.00 | Tweet vs. Cooking: 0.19
4x longer
Look at that Euclidean failure! Because the Long Match Report is 4x longer, straight-line Euclidean distance claims the Short Tweet is closer to the unrelated Cooking Blog (8.3) than to the Match Report about the exact same game (12.1)! Meanwhile Cosine Similarity checks only the angle: 0° for Tweet vs. Report (1.00) and a wide 79° for Tweet vs. Cooking (0.19).
✓ Tip

A handy geometric shortcut (unit vectors): What happens if you first shrink or stretch every vector to exact length 1 (called unit vectors)? Once all arrows end on the same circle of radius 1, a smaller angle automatically means a shorter straight-line distance between their tips, so Euclidean distance and Cosine Similarity rank neighbors in the exact same order.


When too many columns break distance: the Curse of Dimensionality

If 2 clues are good and 10 clues are better, why not feed 100 or 200 columns into a nearest-neighbor model like K-Nearest Neighbors (KNN)?

Think of a thin 10% peel on an orange: on a flat 2D coin, that outer rim holds only 19% of the coin; on a 3D orange it holds ~27% of the orange; in 100 dimensions, 99.997% of the entire space sits inside that thin outer crust! Each new dimension multiplies the shrinking interior by 0.9, leaving 1 - 0.9^d of the space pushed into the outer shell. At the same time, piling on noisy columns makes every pair of points accumulate random differences across dozens of axes, so the gap between your nearest and farthest neighbor collapses toward 1.0× and nearest-neighbor classifiers lose their ability to tell true matches from strangers.

Slide Number of Feature Columns (d) from 2 up to 100 (or tap the quick presets) below to watch the orange peel swallow the interior while all 44 neighbors bunch together near the far edge.

Interactive Lab 4: The Curse of Dimensionality (When Distances Collapse)
Columns: d = 2
Farthest ÷ Nearest Distance Ratio
10.31×
YouNearestFarthest
Watch the 44 gray neighbors march to the far edge as columns grow, shrinking the gap toward 1.0×.
Volume Inside Outer 10% Orange Peel
19.0%
Only 81.0% stays in the cozy interior core.
Orange dots sit in the outer peel; green dots sit in the core. In high dimensions, nearly every point gets pushed to the lonely crust.
In 2D space (like a flat coin), your nearest neighbor is 10.31x closer than your farthest neighbor, and only 19.0% of volume sits in the outer 10% peel. Everyday distance intuition works cleanly here!
See Minkowski Lp norms, Cosine geometry & Beyer's distance concentrationThesis / Reference

1. Minkowski (LpL_p) Distance Family: For feature vectors u,v∈Rd\mathbf{u}, \mathbf{v} \in \mathbb{R}^d:

dp(u,v)=(∑j=1d∣uj−vj∣p)1/pd_p(\mathbf{u}, \mathbf{v}) = \left(\sum_{j=1}^{d} |u_j - v_j|^p\right)^{1/p}

Setting p=1p = 1 yields Manhattan, p=2p = 2 yields Euclidean, and p→∞p \to \infty yields Chebyshev (max⁡j∣uj−vj∣\max_j |u_j - v_j|).

2. Cosine Similarity & Unit-Sphere Equivalence:

cosine(u,v)=u⋅v∥u∥2 ∥v∥2=cos⁡θ∈[−1,1]\text{cosine}(\mathbf{u}, \mathbf{v}) = \frac{\mathbf{u} \cdot \mathbf{v}}{\|\mathbf{u}\|_2 \,\|\mathbf{v}\|_2} = \cos\theta \in [-1, 1]

When vectors are L2-normalized (∥u^∥2=∥v^∥2=1\|\hat{\mathbf{u}}\|_2 = \|\hat{\mathbf{v}}\|_2 = 1), squared Euclidean distance reduces identically to ∥u^−v^∥22=2(1−cos⁡θ)\|\hat{\mathbf{u}} - \hat{\mathbf{v}}\|_2^2 = 2(1 - \cos\theta), which is why Vector Databases & HNSW (FAISS, Qdrant, pgvector) normalize embeddings once at indexing time.

3. High-Dimensional Distance Concentration (Beyer et al., 1999; Aggarwal et al., 2001): Under broad i.i.d. coordinate distributions, as d→∞d \to \infty:

dmax⁡−dmin⁡dmin⁡→  P  0\frac{d_{\max} - d_{\min}}{d_{\min}} \xrightarrow{\;P\;} 0

Additionally, the fraction of a dd-dimensional ball’s volume lying in its outer ϵ\epsilon-shell is 1−(1−ϵ)d→11 - (1 - \epsilon)^d \to 1 exponentially fast. Aggarwal et al. (2001) further showed that fractional/Manhattan norms (L1L_1) degrade more slowly than Euclidean (L2L_2) in high dimensions.

See Euclidean, Manhattan & Cosine similarity in PythonOptional Code
python
import numpy as np
from sklearn.metrics.pairwise import cosine_similarity

tweet  = np.array([[3, 2]])
report = np.array([[12, 8]])
recipe = np.array([[1, 8]])

print("Euclidean (tweet vs report):", round(np.linalg.norm(tweet - report), 2))
print("Euclidean (tweet vs recipe):", round(np.linalg.norm(tweet - recipe), 2))
print("Cosine    (tweet vs report):", round(cosine_similarity(tweet, report)[0, 0], 2))
print("Cosine    (tweet vs recipe):", round(cosine_similarity(tweet, recipe)[0, 0], 2))

Next step: crafting smarter clues and trimming noisy ones

Since adding noisy columns weakens geometry and invites overfitting, real machine learning wins by building a handful of high-signal clues and cutting redundant junk. Next up in Feature Engineering & Selection, we build smarter clues visually and see how correlation and Lasso pick the winners.

✓ Self-Check

Quick Intuition Check

Four quick real-world scenarios. No scores, just test your intuition.

1

You are building a document search engine comparing short 2-sentence user queries against 10-page manuals. Which similarity metric ignores length differences best?

Pick an option first, or peek anytime
2

A delivery drone flies diagonally across rooftops while a courier van drives strictly north/south and east/west on city streets. Which pair of distances matches them?

Pick an option first, or peek anytime
3

What happens to a K-Nearest Neighbors classifier when you append 150 random noise columns to a 5-feature dataset?

Pick an option first, or peek anytime
4

If all vectors are first scaled to length 1 (unit vectors), ranking neighbors by straight-line Euclidean distance produces the exact same order as ranking by Cosine Similarity.

Pick an option first, or peek anytime
Quick Reference

Common Questions

What is cosine similarity in plain English?
Cosine similarity measures the cosine of the angle between two vectors, ignoring their lengths. A score of +1 means two vectors point in the exact same direction, 0 means they are perpendicular (unrelated), and -1 means they point in opposite directions.
Can cosine similarity be negative or greater than 1?
Cosine similarity can never exceed +1 because the cosine of any angle lies between -1 and +1. It can be negative (down to -1) whenever embeddings contain negative coordinates and point in opposite semantic directions, though bag-of-words counts with only non-negative numbers stay between 0 and +1.
What is the difference between Euclidean distance and Manhattan distance?
Euclidean distance (L2) measures the straight diagonal line between two points, as the crow flies. Manhattan distance (L1) adds up axis-by-axis steps like driving around city blocks, making it less sensitive to single-feature spikes in high dimensions.
Why do text search and LLM embeddings use Cosine Similarity instead of Euclidean distance?
Cosine Similarity measures the angle between two vectors rather than their lengths. A 20-word tweet and a 2,000-word article on the exact same topic point in the same direction (Cosine = 1.0), whereas Euclidean distance penalizes the difference in document length.
What is a feature vector in machine learning?
A feature vector is simply an ordered list of numbers describing one item, such as [Energy: 74, Tempo: 122] for a song. Treating every row as a point in space lets algorithms measure similarity using geometry.
What is the Curse of Dimensionality in simple terms?
When you add dozens or hundreds of feature columns, the volume of space grows exponentially while your dataset stays fixed. Almost every point becomes isolated near the outer edges, and the gap between your nearest neighbor and farthest neighbor shrinks toward zero.
When are Euclidean distance and Cosine distance equivalent?
When every vector is first L2-normalized to unit length (||x|| = 1), squared Euclidean distance equals 2 * (1 - Cosine Similarity), so both rank neighbors in the exact same order.

Written & illustrated by Muhammad Aashir Irshad · Updated December 2026 · Free open-access reference

https://seeingml.com/learn/similarity-distance/ Open GitHub issue Suggest an edit
Cite this guide in a paper, thesis, or course (BibTeX & APA)
BibTeX
@misc{irshad2026similaritydistance,
  author       = {Irshad, Muhammad Aashir},
  title        = {Euclidean Distance & Cosine Similarity: Interactive Visual Guide},
  howpublished = {SeeingML},
  year         = {2026},
  month        = {dec},
  url          = {https://seeingml.com/learn/similarity-distance/},
  note         = {Interactive visual guide}
}
APA

Irshad, M. A. (2026). Euclidean Distance & Cosine Similarity: Interactive Visual Guide. SeeingML. https://seeingml.com/learn/similarity-distance/