Working With Data Guide 6 of 8 · tap to switch
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.
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.
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 Football4times with a tiny0.5Recipe score (a single passing food joke). - Long Match Report
[16, 2]: Covers the exact same match at4×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 Recipe8times.
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.
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.
See Minkowski Lp norms, Cosine geometry & Beyer's distance concentrationThesis / Reference
1. Minkowski () Distance Family: For feature vectors :
Setting yields Manhattan, yields Euclidean, and yields Chebyshev ().
2. Cosine Similarity & Unit-Sphere Equivalence:
When vectors are L2-normalized (), squared Euclidean distance reduces identically to , 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 :
Additionally, the fraction of a -dimensional ball’s volume lying in its outer -shell is exponentially fast. Aggarwal et al. (2001) further showed that fractional/Manhattan norms () degrade more slowly than Euclidean () in high dimensions.
See Euclidean, Manhattan & Cosine similarity in PythonOptional Code
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.
Quick Intuition Check
Four quick real-world scenarios. No scores, just test your intuition.
You are building a document search engine comparing short 2-sentence user queries against 10-page manuals. Which similarity metric ignores length differences best?
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?
What happens to a K-Nearest Neighbors classifier when you append 150 random noise columns to a 5-feature dataset?
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.
Common Questions
What is cosine similarity in plain English?
Can cosine similarity be negative or greater than 1?
What is the difference between Euclidean distance and Manhattan distance?
Why do text search and LLM embeddings use Cosine Similarity instead of Euclidean distance?
What is a feature vector in machine learning?
What is the Curse of Dimensionality in simple terms?
When are Euclidean distance and Cosine distance equivalent?
Related Visual Guides
K-Nearest Neighbors (KNN Algorithm)
Predict a new example simply by asking its K closest neighbors to vote, and see why choosing K and scaling features make or break the result.
Vector Databases & HNSW
Fly inside a 3D multi-layer HNSW skip graph to see how vector databases search millions of embeddings in milliseconds, compare IVF vs. HNSW, and shrink RAM 32x with Product Quantization.
Vectors, Norms & Dot Products
See every ML data row and embedding as an arrow in space, add and scale vectors visually, and feel why Dot Products measure alignment.
Written & illustrated by Muhammad Aashir Irshad · Updated December 2026 · Free open-access reference
Cite this guide in a paper, thesis, or course (BibTeX & APA)
@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}
} Irshad, M. A. (2026). Euclidean Distance & Cosine Similarity: Interactive Visual Guide. SeeingML. https://seeingml.com/learn/similarity-distance/