Skip to main content
Vectors - The Language of Similarity

Vectors: The Language of Similarity

A Problem You Already Understand

You’re looking for a new apartment. You visit Zillow and find one you love:
  • 2 bedrooms
  • 1,200 square feet
  • $2,400/month rent
  • 15 minutes from work
Now you want to find similar apartments. Not identical — just similar enough that you’d consider them. Zillow shows you a “Similar Homes” section. But how did they decide which apartments are similar? Think about it: What makes two apartments “similar”?
  • Same number of bedrooms?
  • Similar size?
  • Similar rent?
  • Similar commute?
All of the above, in some combination. And that combination is exactly what vectors and similarity measures capture.
Estimated Time: 3-4 hours
Difficulty: Beginner
Prerequisites: Basic Python
What You’ll Build: A “Find Similar Items” system that works for apartments, songs, or anything
🔗 ML Connection: Vectors are THE foundation of modern ML. Here’s where you’ll see them:After this module, you’ll understand exactly how these systems find “similar” items!

Step 1: Describe Things with Numbers

The first insight is simple: we can describe any apartment as a list of numbers. Apartment as Vector
Now every apartment is just 4 numbers:
This list of numbers is called a vector. That’s it. A vector is just an ordered list of numbers that describes something.
Key Insight: Once something is described as numbers, we can use math to compare things automatically. No human judgment needed.
Vector Math Concept

Mathematical Foundations: Vector Operations

Before we measure similarity, let’s master the fundamental operations. These are the building blocks of ALL machine learning.

Vector Addition: Combine Two Vectors

When you add vectors, you add corresponding components: a+b=[a1a2a3]+[b1b2b3]=[a1+b1a2+b2a3+b3]\mathbf{a} + \mathbf{b} = \begin{bmatrix}a_1\\a_2\\a_3\end{bmatrix} + \begin{bmatrix}b_1\\b_2\\b_3\end{bmatrix} = \begin{bmatrix}a_1 + b_1\\a_2 + b_2\\a_3 + b_3\end{bmatrix} Real Example: Combining two shopping carts:
Geometric Interpretation: Place vectors tip-to-tail; the sum goes from the first tail to the last tip.

Scalar Multiplication: Scale a Vector

Multiply every component by the same number (scalar): cv=c[v1v2v3]=[cv1cv2cv3]c \cdot \mathbf{v} = c \cdot \begin{bmatrix}v_1\\v_2\\v_3\end{bmatrix} = \begin{bmatrix}c \cdot v_1\\c \cdot v_2\\c \cdot v_3\end{bmatrix} Real Example: Double a recipe:
Geometric Interpretation: Scalar > 1 stretches the vector; 0 < scalar < 1 shrinks it; negative flips direction.

Vector Magnitude (Length)

The magnitude (or norm) measures how “big” a vector is: v=v12+v22++vn2=i=1nvi2\|\mathbf{v}\| = \sqrt{v_1^2 + v_2^2 + \cdots + v_n^2} = \sqrt{\sum_{i=1}^{n} v_i^2} Real Example: Distance from origin:
Fun fact: The 3-4-5 triangle is the most famous Pythagorean triple! Ancient Egyptians used it to create right angles in construction.

Unit Vectors: Direction Without Magnitude

A unit vector has length 1 and only represents direction: v^=vv\hat{\mathbf{v}} = \frac{\mathbf{v}}{\|\mathbf{v}\|} Real Example: Normalize for comparison:
Key insight: Normalization removes the “enthusiasm” factor and compares only the pattern of ratings.

Vector Subtraction: Finding the Difference

ab=[a1b1a2b2a3b3]\mathbf{a} - \mathbf{b} = \begin{bmatrix}a_1 - b_1\\a_2 - b_2\\a_3 - b_3\end{bmatrix} Real Example: What changed between two time periods?

Practice: Vector Arithmetic

Let’s combine these operations:

Step 2: Measure How Similar Two Apartments Are

Now the real question: Given two apartments as vectors, how do we measure their similarity? Apartment Similarity Space

Attempt 1: Just Subtract (Doesn’t Work Well)

Your first instinct might be to subtract the numbers:
But what does [0, 100, 100, -3] mean? The numbers have different units (bedrooms vs sqft vs dollars vs minutes). We can’t just add them.

Attempt 2: Euclidean Distance (Works, But Has Issues)

We could calculate the “distance” between apartments in 4D space:
B is much closer to A than C is. Good! But there’s a problem: the sqft and rent numbers are huge (1000s) while bedrooms and commute are small (single digits). The big numbers dominate everything.

Attempt 3: Normalize First, Then Compare

The fix: scale all features to the same range (usually 0 to 1):
Now all features are on equal footing. A difference of 0.1 in bedrooms matters as much as 0.1 in rent.

Step 3: The Dot Product — Measuring Alignment

There’s an even better way to measure similarity: the dot product.

Mathematical Definition

The dot product (also called inner product or scalar product) of two vectors: ab=i=1naibi=a1b1+a2b2++anbn\mathbf{a} \cdot \mathbf{b} = \sum_{i=1}^{n} a_i b_i = a_1 b_1 + a_2 b_2 + \cdots + a_n b_n What it does: Multiply corresponding numbers and add them up.
Example:

Geometric Interpretation

The dot product has a beautiful geometric meaning: ab=abcos(θ)\mathbf{a} \cdot \mathbf{b} = \|\mathbf{a}\| \|\mathbf{b}\| \cos(\theta) Where θ\theta is the angle between the vectors!
Dot Product and Cosine Similarity Geometric Intuition
🎮 Interactive Visualization: Try the code below to see how the dot product changes as you rotate vectors!
What this tells us:
  • θ=0°\theta = 0° (same direction): cos(0°)=1\cos(0°) = 1 → Maximum positive dot product
  • θ=90°\theta = 90° (perpendicular): cos(90°)=0\cos(90°) = 0 → Dot product is zero
  • θ=180°\theta = 180° (opposite): cos(180°)=1\cos(180°) = -1 → Maximum negative dot product

The Dot Product in Action

Why does this measure similarity? Think about it intuitively:
  • If both apartments are high in the same features (both large, both expensive), the products are large → high dot product
  • If one is high where the other is low, products are small → low dot product
  • Apartments that are “aligned” (similar profile) have high dot products

Step 4: Cosine Similarity — The Industry Standard

The dot product has one problem: bigger vectors give bigger numbers regardless of similarity. Cosine similarity fixes this by normalizing: similarity(A,B)=ABA×B\text{similarity}(A, B) = \frac{A \cdot B}{|A| \times |B|} This gives a number between -1 and 1:
  • 1.0 = identical direction (very similar)
  • 0.0 = perpendicular (unrelated)
  • -1.0 = opposite direction (opposites)
Let’s test it on our apartments:
Output:
Wait, why is C so similar? Because cosine similarity measures direction, not magnitude. C is a “scaled up” version of A — same proportions, just bigger numbers. This is actually useful! It finds apartments with the same profile (ratio of bedrooms to sqft to rent), regardless of absolute size.

Real-World Application: Build a “Similar Apartments” Finder

Let’s build a working system:
Output:
You just built Zillow’s “Similar Homes” feature!

Now Let’s Connect This to Machine Learning

Everything we just learned about apartments applies directly to ML. The concepts are identical — only the application changes.

Pattern: Real World → Vector → Similarity

The math is identical. Once something is a vector, you can find similar items using dot products and cosine similarity.

Example: How Spotify Actually Works

Remember our apartment finder? Spotify does the exact same thing with songs:
The entire Spotify recommendation engine is built on the same vector similarity concept you just learned with apartments.

How This Applies to Neural Networks

Now let’s take the final step. In neural networks, everything is vectors, and everything is similarity and transformation.

What a Neural Network Does (Simplified)

  1. Input: Convert your data to a vector (image → pixels, text → numbers)
  2. Layers: Transform the vector through matrix multiplications (we’ll learn this next!)
  3. Output: Compare the final vector to known categories using… similarity
The core operation — vector similarity — is exactly what you learned with apartments.
Now let’s use it on our songs:
That’s the Spotify algorithm in a nutshell! Find songs with the highest cosine similarity to what you just played.

Vector Operations: The Building Blocks

Now that we can represent houses as vectors, what can we do with them?

1. Vector Addition: Combining Features

The Question: What if we want to combine two house profiles? Vector Addition Geometric Intuition: Place vectors tip-to-tail. The result is the diagonal. Algebraic Definition: Add corresponding components.
Why This Matters:
  • Feature engineering: Combine features to create new ones
  • Gradient descent: Update model parameters by adding gradients
  • Ensemble methods: Average predictions from multiple models
Real-World Example: User preferences

2. Scalar Multiplication: Scaling Features

The Question: What if all house prices in a neighborhood increase by 20%? Scalar Multiplication Geometric Intuition: Stretch or shrink the vector. Direction stays the same. Algebraic Definition: Multiply each component by a number (scalar).
Why This Matters:
  • Normalization: Scale features to same range
  • Learning rate: Control how much to update parameters
  • Feature weighting: Emphasize important features
ML Application: Gradient descent
Key Insight: The learning rate controls the step size. Too large → overshoot. Too small → slow learning.

3. Dot Product: Measuring Similarity

The Big Question: How do we measure if two things are similar? This is THE most important operation in machine learning! Let’s see why through three examples. Dot Product with Houses Algebraic Definition: Multiply corresponding components and sum. Mathematical Formula: vw=i=1nviwi=v1w1+v2w2++vnwn\mathbf{v} \cdot \mathbf{w} = \sum_{i=1}^{n} v_i w_i = v_1w_1 + v_2w_2 + \ldots + v_nw_n Alternative Formula (geometric): vw=vwcos(θ)\mathbf{v} \cdot \mathbf{w} = \|\mathbf{v}\| \|\mathbf{w}\| \cos(\theta) Where θ\theta is the angle between vectors.

Example 1: Comparing Houses

Interpretation:
  • Large dot product = similar houses
  • Small dot product = different houses
  • Why? Similar houses have similar feature values, so products are large
Real application: Zillow uses this to find “similar homes” when you’re browsing!

Example 2: Matching Students for Study Groups

Interpretation: Alice and Charlie have more similar learning patterns! Why this matters:
  • Form effective study groups (similar students help each other)
  • Pair struggling students with successful ones who had similar challenges
  • Predict who will benefit from group work
Real application: Educational platforms use this for peer matching!

Example 3: Movie Recommendations

Recommendation: Watch Interstellar! (Higher similarity) Why it works: Both are:
  • High-rated sci-fi films
  • Similar runtime
  • Recent releases
  • Action-heavy with minimal romance
Real application: This is literally how Netflix, Spotify, and YouTube work!

Understanding the Dot Product Geometrically

Key Insights:
What this means:
  • Positive dot product: Vectors point in similar directions (similar items)
  • Zero dot product: Vectors are perpendicular (completely different items)
  • Negative dot product: Vectors point in opposite directions (opposite items)

Why Dot Product is Everywhere in ML

1. Neural Networks: Every layer computes dot products!
2. Similarity Search: Find similar items
3. Attention Mechanisms: How transformers (GPT, BERT) work

4. Vector Magnitude: Measuring “Size”

The Question: How “big” is a house (in feature space)? Geometric Intuition: The length of the arrow. Algebraic Definition: Square root of dot product with itself.
Mathematical Formula: v=vv=v12+v22++vn2\|\mathbf{v}\| = \sqrt{\mathbf{v} \cdot \mathbf{v}} = \sqrt{v_1^2 + v_2^2 + \ldots + v_n^2} Why This Matters: Normalization!
Key Insight: After normalization, all features contribute equally. Sqft no longer dominates!

Similarity Measures: Finding Similar Items

Cosine Similarity: Direction-Based

The Problem with Dot Product: It’s affected by magnitude!
The Solution: Cosine similarity ignores magnitude, only cares about direction (type). Cosine Similarity Formula: similarity(v,w)=vwvw=cos(θ)\text{similarity}(\mathbf{v}, \mathbf{w}) = \frac{\mathbf{v} \cdot \mathbf{w}}{\|\mathbf{v}\| \|\mathbf{w}\|} = \cos(\theta) Range: -1 (opposite) to +1 (identical direction)

Example 1: House Type Matching (Ignoring Size)

Key Insight: The two suburban houses are identical in TYPE (cosine = 1.0), even though one is twice the size! Why this matters:
  • A family looking for a suburban house doesn’t care if it’s 2000 or 4000 sqft
  • They care about the TYPE: suburban, family-friendly, good schools
  • Cosine similarity captures this!
Real application: Zillow’s “similar homes” feature uses cosine similarity to find homes of similar style, not just similar size.

Example 2: Student Learning Style (Not Just Scores)

Interpretation:
  • Alice and Alice_2x have IDENTICAL learning patterns (cosine = 1.0)
  • The magnitude doesn’t matter - it’s the PATTERN that counts
  • Alice is strong in reading, Bob is strong in math (different patterns)
Why this matters:
  • Match students with similar learning STYLES, not just similar scores
  • A student who scores 60/70/65 has the same pattern as one who scores 80/93/87
  • Recommend study materials based on learning style, not absolute performance
Real application: Khan Academy matches students with similar learning patterns to suggest effective study paths.

Example 3: Movie Taste (Not Just Ratings)

Key Insight: User A and User A_harsh have the SAME TASTE, just different rating scales!
  • User A rates generously (5, 4, 3)
  • User A_harsh rates strictly (3, 2, 1)
  • But they like the SAME TYPES of movies!
Why this matters:
  • Some users rate everything 5 stars, others are harsh critics
  • Cosine similarity finds users with similar TASTE, not similar rating scales
  • Recommend movies based on taste, not rating magnitude
Real application: Netflix uses cosine similarity because users have different rating behaviors, but similar tastes should get similar recommendations.

When to Use Cosine vs. Euclidean Distance

Use Cosine Similarity when:
  • ✅ Direction matters more than magnitude
  • ✅ Different scales (harsh vs. generous raters)
  • ✅ Text similarity (document length doesn’t matter)
  • ✅ Recommendation systems (taste, not intensity)
Use Euclidean Distance when:
  • ✅ Absolute position matters
  • ✅ Same scale for all features
  • ✅ Clustering (K-means)
  • ✅ Anomaly detection (how far from normal?)
Interpretation: Euclidean distance catches the anomaly better because it cares about MAGNITUDE!

Real-World Application: Finding Similar Houses

Let’s build a simple house recommendation system!
Output:
Prediction: Based on similar houses, estimated price ≈ $337k (average of top 3)

Supporting Example 1: Document Similarity

The same vector concepts apply to text!
Key Insight: Same math, different domain!

Supporting Example 2: User Recommendations


Practice Exercises

Exercise 1: House Price Estimation


🎯 Practice Exercises & Real-World Applications

Challenge yourself! These exercises blend mathematical concepts with real-world scenarios. Try to solve them before peeking at the solutions.

Exercise 1: Music Streaming Recommendations 🎵

Spotify represents songs as vectors based on audio features. Given these song vectors: Task: Find which song is most similar to “Your Favorite” using cosine similarity.
Real-World Insight: This is exactly how Spotify’s “Discover Weekly” works! Songs are represented as 12+ dimensional vectors including tempo, key, loudness, and more.

Exercise 2: E-commerce Product Matching 🛒

Amazon wants to show “Similar Products” when a customer views an item. Products are represented as vectors: Features: [price_tier, avg_rating, num_reviews (log), category_score, brand_popularity]
Tasks:
  1. Calculate both Euclidean distance AND cosine similarity for each product
  2. Which metric gives better recommendations and why?
  3. Should we normalize the data first?
Key Insight:
  • Use Euclidean when magnitude matters (price, ratings)
  • Use Cosine when only direction matters (document topics, user preferences)
  • Always normalize features to different scales!

Exercise 3: Dating App Compatibility 💕

A dating app represents users as compatibility vectors: Features: [adventure_score, introversion, career_focus, family_values, humor_style]
Tasks:
  1. Calculate a “compatibility score” using dot product
  2. Normalize and use cosine similarity - does the ranking change?
  3. Which match is best and why?
Real-World Insight: Dating apps like Hinge and OkCupid use similar vector-based matching, but with 50+ dimensions including behavioral data from swipes and messages!

Exercise 4: Document Search Engine 📄

Build a simple search engine using TF-IDF vectors:
Tasks:
  1. Rank documents by relevance to the query
  2. What’s the top result?
  3. Why might “Data Science” rank higher than “Python Basics” even though query has “python”?
Real-World Insight: This is how Google Search worked in its early days! Modern search engines add hundreds more signals (links, freshness, user behavior).

🚨 Real-World Challenge: Handling Messy Data

In textbooks, data is clean. In production, data is messy. Here’s how to handle real-world vector problems:
Production Reality: Real data has missing values, outliers, inconsistent scales, and noise. Your similarity system will fail if you don’t handle these!

Missing Values

Outlier Detection

Feature Scaling Choices

Rule of Thumb:
  • Min-Max: Neural networks, bounded features
  • Z-Score: Most ML algorithms, normally distributed data
  • Robust: Data with outliers, skewed distributions

🔬 Advanced Deep Dive (Optional)

Why High Dimensions Are Weird

In high dimensions, our intuition breaks down completely:
Key Insight: In 10,000 dimensions, random vectors are almost perfectly orthogonal! This is why:
  • Random embeddings don’t work (everything is equally dissimilar)
  • Trained embeddings are necessary (learn meaningful directions)
  • Dimension reduction (PCA, t-SNE) helps visualization

Volume Concentration

Implications for ML

  1. Nearest Neighbors degrades: All points become equidistant
  2. More data needed: Exponentially more samples to cover space
  3. Regularization essential: Prevents overfitting in sparse spaces
  4. Feature selection matters: Irrelevant features hurt more in high-D

The Problem: Brute Force Doesn’t Scale

Finding similar vectors in a billion-vector database takes forever with brute force:

LSH: Approximate but Fast

Locality-Sensitive Hashing groups similar vectors into the same “bucket”:
Trade-off: Speed vs accuracy. LSH might miss some true neighbors, but it’s 100-1000x faster!Production systems (Pinecone, Milvus, Faiss) use sophisticated variants of LSH and graph-based methods.

Key Takeaways

Vectors represent data - Houses, images, text all become vectors
Dot product measures similarity - Foundation of neural networks
Cosine similarity - Direction-based (ignores magnitude)
Euclidean distance - Position-based (includes magnitude)
Normalization matters - Prevent one feature from dominating
Same math, different domains - Vectors work everywhere!
Handle messy data - Missing values, outliers, and scaling are production realities
High dimensions are weird - Curse of dimensionality affects all similarity search

🔗 Math → ML Connection Summary

What you learned in this module powers these ML systems:Next time you use any ML model, remember: it’s operating on vectors using these exact operations!

For learners who want the mathematical foundations:

Vector Spaces: The Abstract View

A vector space is a set of objects (vectors) with two operations (addition and scalar multiplication) that satisfy certain axioms. This abstraction lets us apply vector math to surprising domains:

Linear Independence & Basis

A set of vectors is linearly independent if no vector can be written as a combination of others:If c1v1+c2v2++cnvn=0, then all ci=0\text{If } c_1\mathbf{v}_1 + c_2\mathbf{v}_2 + \cdots + c_n\mathbf{v}_n = \mathbf{0} \text{, then all } c_i = 0A basis is a minimal set of linearly independent vectors that span the space.ML Application: In neural networks, we’re essentially finding a good basis to represent data. Autoencoders find compressed bases; attention mechanisms dynamically select relevant basis directions.

Inner Product Spaces

Our dot product is a specific inner product. More generally, an inner product ⟨·,·⟩ satisfies:
  1. ⟨u, v⟩ = ⟨v, u⟩ (symmetry)
  2. ⟨au + bv, w⟩ = a⟨u, w⟩ + b⟨v, w⟩ (linearity)
  3. ⟨v, v⟩ ≥ 0, with equality iff v = 0 (positive definiteness)
Why this matters: Different inner products define different notions of similarity! Kernel methods in ML use custom inner products to find nonlinear patterns.
  • Gilbert Strang’s Linear Algebra (MIT OpenCourseWare) - Rigorous but intuitive
  • 3Blue1Brown: Essence of Linear Algebra - Visual understanding
  • Mathematics for Machine Learning book, Ch. 2-3 - ML-focused treatment

Word Embeddings: Vectors in NLP

Mind-blowing application: Words are vectors, and vector math works on meaning!
Modern AI (GPT-4, Claude) uses this same principle with transformer embeddings of 12,000+ dimensions!

Interview Questions: Vectors

Answer: The dot product ab=aibi\mathbf{a} \cdot \mathbf{b} = \sum a_i b_i measures alignment between vectors. In ML:
  • Neural networks: Every neuron computes a dot product (weights · inputs)
  • Attention mechanisms: Query-key dot products determine what to focus on
  • Similarity search: Cosine similarity uses normalized dot products
  • Loss functions: Many involve dot products (cross-entropy, hinge loss)
Answer:
  • Cosine: When magnitude doesn’t matter (text similarity, user preferences, normalized data)
  • Euclidean: When absolute values matter (physical distance, raw measurements)
  • Example: Two documents about ML with different lengths should be similar (cosine), but two GPS coordinates need actual distance (Euclidean)
Answer: In high dimensions:
  • All points become roughly equidistant (“curse of dimensionality”)
  • Random vectors are almost orthogonal (cosine ≈ 0)
  • This is why PCA/dimension reduction is important
  • Modern embeddings (512-4096 dim) are trained to preserve meaningful similarity

What’s Next?

You now understand how to represent houses as vectors and measure similarity. But how do we actually predict the price? That’s where matrices come in. A matrix is a function that transforms input (house features) into output (price prediction). This is exactly how neural networks work!

Next: Matrices & Transformations

Learn how matrices transform house features into price predictions