Comparing Vectors With Cosine Similarity

Ma Mahalakshmi V Updated 16 Sep 2026
7 min read ·Lesson 118 of 224

Comparing Vectors With Cosine Similarity

Unit 10's similarity-search pipeline used cosine similarity to compare vectors without a deep dive into why that particular measure was chosen over the alternatives, or how to compute it efficiently once the number of vectors grows past a handful. This lesson fills in that gap: what cosine similarity actually measures geometrically, why it is the standard choice for text embeddings specifically, how it compares to other distance measures, and how to compute it correctly and efficiently in Python.

What Cosine Similarity Measures

Cosine similarity measures the angle between two vectors, ignoring their length (magnitude). Two vectors pointing in exactly the same direction have a cosine similarity of 1, regardless of whether one is twice as long as the other. Two vectors at a right angle score 0. Two vectors pointing in exactly opposite directions score -1.

The formula is the dot product of the two vectors divided by the product of their magnitudes:

cosine_similarity(a, b) = (a · b) / (|a| * |b|)

Why does ignoring magnitude matter for text embeddings? An embedding model represents meaning primarily through the direction a vector points in high-dimensional space, not through how long that vector is. Two paraphrases of the same sentence should point in nearly the same direction even if, incidentally, one embedding vector happens to have a slightly larger norm than the other. Cosine similarity is invariant to that difference in scale, which makes it a measure of "do these mean the same thing" rather than "are these vectors similar in size."

Computing It in Python

import math

def dot_product(a: list[float], b: list[float]) -> float:
    return sum(x * y for x, y in zip(a, b))

def magnitude(v: list[float]) -> float:
    return math.sqrt(sum(x * x for x in v))

def cosine_similarity(a: list[float], b: list[float]) -> float:
    """Return a value in [-1, 1]. 1 means identical direction."""
    denom = magnitude(a) * magnitude(b)
    if denom == 0:
        return 0.0
    return dot_product(a, b) / denom

vec_a = [1.0, 2.0, 0.0]
vec_b = [2.0, 4.0, 0.0]     # same direction as vec_a, different length
vec_c = [0.0, 0.0, 1.0]     # perpendicular to vec_a

print(cosine_similarity(vec_a, vec_b))  # 1.0 — same direction
print(cosine_similarity(vec_a, vec_c))  # 0.0 — unrelated direction

vec_b is exactly twice the length of vec_a but points in the identical direction, and the function correctly returns 1.0 — confirming that magnitude does not affect the result. The denom == 0 guard handles the degenerate case of a zero vector (which has no direction), returning 0.0 rather than raising a division-by-zero error; a zero vector should not normally occur from a real embedding model, but defensive code should not crash on it.

This pure-Python version is useful for understanding the mechanics, but it recomputes both magnitudes and loops in Python on every call, which is slow once you are comparing one query vector against thousands of stored vectors. For anything beyond a small demo, use a numeric library.

import numpy as np

def cosine_similarity_np(a: np.ndarray, b: np.ndarray) -> float:
    denom = np.linalg.norm(a) * np.linalg.norm(b)
    if denom == 0:
        return 0.0
    return float(np.dot(a, b) / denom)

def cosine_similarity_batch(query: np.ndarray, matrix: np.ndarray) -> np.ndarray:
    """Compare one query vector against every row of `matrix` at once.

    `matrix` has shape (n_documents, n_dimensions). Returns an array
    of n_documents similarity scores.
    """
    query_norm = query / np.linalg.norm(query)
    matrix_norms = matrix / np.linalg.norm(matrix, axis=1, keepdims=True)
    return matrix_norms @ query_norm

cosine_similarity_batch is the version that matters in practice: rather than looping over each stored vector and calling cosine_similarity_np one at a time, it normalizes every row of matrix in one vectorized operation and then computes all similarity scores with a single matrix-vector multiplication (@). NumPy executes this in optimized, compiled code rather than the Python interpreter loop, which is often 10 to 100 times faster for large collections — this difference becomes the deciding factor once a corpus has more than a few thousand vectors, well before it reaches the scale that justifies a dedicated vector database (Lesson 6).

Cosine Similarity vs. Other Distance Measures

MeasureWhat it capturesSensitive to magnitude?Typical use with text embeddings
Cosine similarityAngle between vectorsNoStandard choice — meaning is encoded in direction.
Euclidean distance (L2)Straight-line distanceYesCommon in clustering (e.g., k-means); less common for raw text similarity ranking.
Dot productAngle and magnitude combinedYesEquivalent to cosine similarity if vectors are pre-normalized to unit length — some vector databases default to this for speed.

Why do dot product and cosine similarity sometimes give the same ranking? If every vector in a collection is normalized to length 1 (unit length) before storage, then |a| * |b| in the cosine formula always equals 1, and the cosine formula reduces exactly to the plain dot product. Some vector databases and libraries normalize vectors at insertion time specifically so they can use the cheaper dot product operation internally while still producing cosine-similarity rankings. This is a performance optimization, not a different similarity concept — but it is worth knowing about, because a database's default "similarity metric" setting (dot product vs. cosine vs. Euclidean) needs to match how the vectors were prepared, or rankings will be silently wrong. Lesson 6 revisits this when configuring a real database.

Why not Euclidean distance for text? Euclidean distance is sensitive to vector length, and two embeddings of the same meaning are not guaranteed to have the same magnitude even though they point in nearly the same direction — small magnitude differences would then distort a distance-based ranking. Euclidean distance is more natural when the vectors' actual position in space (not just direction) is meaningful, such as certain geometric or clustering algorithms, but for meaning-based text comparison, cosine similarity is the established default.

Similarity Scores Are Relative, Not Absolute

A cosine similarity of 0.85 between a query and a document does not mean "85% correct" or "85% probability of relevance." It is a relative measure, useful for ranking candidates against each other, not for asserting an absolute, universal correctness threshold.

def rank_by_similarity(query_vec, candidates: dict[str, list[float]]) -> list[tuple[str, float]]:
    """Return (label, score) pairs sorted by similarity, highest first."""
    scored = [(label, cosine_similarity(query_vec, vec)) for label, vec in candidates.items()]
    return sorted(scored, key=lambda pair: pair[1], reverse=True)

def test_rank_by_similarity():
    query = [1.0, 0.0]
    candidates = {
        "close_match": [0.9, 0.1],
        "far_match": [0.0, 1.0],
        "opposite": [-1.0, 0.0],
    }
    ranked = rank_by_similarity(query, candidates)
    assert ranked[0][0] == "close_match"
    assert ranked[-1][0] == "opposite"
    print("PASS: rank_by_similarity orders candidates correctly")

test_rank_by_similarity()

This test never calls the embeddings API — it works entirely with small, hand-constructed vectors, which is the right way to test ranking logic: the correctness of rank_by_similarity does not depend on what a real embedding model produces, only on whether sorting by score works as intended. Whether a real query's top result at 0.42 similarity counts as "relevant enough" for a given application is a threshold decision that has to be calibrated against real, labeled data — exactly the evaluation process covered in Lesson 9 — rather than assumed from the raw number alone. Two different embedding models, or the same model on two different kinds of content, can produce very different "typical" similarity ranges, which is another reason a fixed universal threshold (like "always require similarity > 0.8") is a common source of bugs.

Common Mistakes

  • Treating a similarity score as a percentage of correctness. As covered above, cosine similarity is a relative ranking signal calibrated per use case, not a universal confidence percentage.
  • Comparing vectors from different embedding models or dimension settings. A vector from text-embedding-4 at 1536 dimensions and one from a different model (or the same model at a different dimensions setting) are not directionally comparable — mixing them produces meaningless scores, or an outright shape mismatch error.
  • Recomputing magnitudes inside a tight loop over many comparisons. As shown above, doing this in pure Python for large collections is needlessly slow; vectorized NumPy operations (or a proper vector index, Lesson 6) scale far better.

Best Practices

  • Normalize vectors once, at storage time, if the database's similarity metric expects it. This avoids redundant normalization work on every single query.
  • Use vectorized batch comparison (NumPy or a vector database) once a collection grows past a few thousand items. Looping with a pure-Python cosine function does not scale and will become a visible bottleneck.
  • Calibrate similarity thresholds against labeled examples, never by intuition. A "good enough" cutoff should come from the kind of evaluation described in Lesson 9, applied to the specific model, content type, and query style actually in use.

0 Comments

Reviewed before they appear

No comments yet.

OpenAI SDK
Introduction to the OpenAI SDK Setting Up Python Creating an API Key Your First Call — client.responses.create() and response.output_text Understanding Billing, Credits, and What a Request Costs Why Responses Replaced Chat Completions Anatomy of a Request: model, input, and instructions Anatomy of a Response: The Typed output Array, Not Just Text Roles: User, Assistant, and Developer/System Choosing a Model, and Reading the Models Page Instead of Memorizing Names Instructions vs. Input Writing Prompts That Get Consistent Results Few-Shot Examples Reasoning Models and the reasoning Parameter Debugging a Prompt That Misbehaves Why Streaming Matters for User Experience stream=True and Iterating Over Events Handling the Event Types You Actually Care About Background Mode for Long-Running Jobs Project — Add Live Streaming to Your Chatbot The Problem With Parsing Free Text JSON Schema and Strict Mode Pydantic Models With the SDK's Parse Helpers Handling Refusals and Validation Failures Project — A Resume-to-JSON Extractor Working With input_image input_file, PDFs, and the Files API Image Generation Speech-to-Text and Text-to-Speech Project: A PDF Question-Answering Script What Function Calling Is Defining a Tool Schema The Full Loop Multiple Tools Errors, Timeouts, and Untrusted Arguments Project: A Weather Assistant Web Search File Search and Vector Stores Code Interpreter Remote MCP Servers and Connectors Project: A Research Assistant What an Embedding Is, Without the Maths Generating and Storing Embeddings Similarity Search From Scratch Hosted Vector Stores vs. Rolling Your Own A Small RAG App Over a Folder of Notes Agents vs. a Single API Call — When You Need One pip install openai Giving Agents Tools Handoffs and Multi-Agent Triage Guardrails and Approvals Tracing and Observing What Your Agent Did A Multi-Agent Support Desk Error Codes and What Each One Means Retries, Timeouts, and Backoff Rate Limits and Spend Limits Prompt Caching and Cost Optimisation The Batch API for Bulk Work Async Clients and Concurrency Moderation and Safety Best Practices Designing the App Backend With FastAPI Streaming to a Simple Frontend Deploying and a Cost/Safety Checklist Why Web Search Is Useful for Current Information Using the Web Search Tool with the Responses API Configuring Search Behavior for Application Use Cases Understanding Citations and Source Attribution Where to Go Next Building a Research Assistant with Web Search Combining Web Search with Structured Outputs Handling Conflicting or Low-Quality Web Sources Reducing Unsupported Claims with Grounded Generation Testing Freshness-Sensitive AI Answers Production Considerations for Web-Grounded Applications Understanding File Search and Retrieval-Augmented Generation Creating and Organizing Vector Stores Uploading Documents for Retrieval Connecting Vector Stores to Responses API Requests Designing Document Metadata and Filtering Strategies Building a PDF Question-Answering Application Improving Retrieval Quality With Better Document Preparation Handling Missing Evidence and Retrieval Failures Combining File Search With Web Search Building a Production Knowledge-Base Assistant What the Code Interpreter Tool Is Designed For Running Python-Based Analysis Through the OpenAI SDK Uploading Datasets for Analysis Analyzing CSV and Spreadsheet Data Generating Charts and Data Summaries Handling Generated Files and Downloadable Artifacts Building a Data-Analysis Assistant Combining Code Execution with Structured Outputs Validating Generated Calculations and Results Security and Sandbox Considerations for Code Execution Understanding Multimodal Input with the OpenAI SDK Sending Images to a Model Image Analysis from URLs and Uploaded Files Extracting Text and Information from Screenshots Building an Image-Question-Answering Application Combining Image Input with Structured Output Analyzing Multiple Images in One Request Handling Image Quality and Input Limitations Designing Multimodal Prompts for Reliable Results Building a Practical Vision-Powered Python Application Understanding Speech-to-Text and Text-to-Speech Workflows Transcribing Audio with the OpenAI SDK Working with Uploaded Audio Files Handling Timestamps and Transcription Metadata Building a Meeting Transcription Workflow Generating Spoken Responses from Text Handling Long Audio and Processing Failures Combining Audio with Text and Tool Calling Building an End-to-End Python Voice Application What Embeddings Are and When to Use Them Generating Embeddings With the OpenAI API Preparing Text for Embedding Comparing Vectors With Cosine Similarity Building a Simple Semantic Search Engine in Python Storing Embeddings in a Database Metadata Filtering for Semantic Search Chunking Strategies for Better Retrieval Evaluating Semantic Search Quality Building a Document Similarity Application When Batch Processing Makes Sense Designing Large-Volume AI Processing Pipelines Using Asynchronous Python with the OpenAI SDK Running Concurrent Requests Safely Controlling Concurrency and Avoiding Rate Limits Tracking Batch Job Progress Handling Partial Failures in Bulk Workloads Retrying Failed Items Without Duplicating Successful Work Designing Resumable AI Processing Jobs Building a Production Batch-Processing Pipeline Batch Processing Makes Sense Large-Scale AI Processing Pipelines Async Python with OpenAI SDK Safe Concurrent Requests Concurrency & Rate Limits Batch Progress Tracking Partial Failure Handling Safe Retry Handling Resumable AI Jobs Production Batch Pipeline System–User Data Separation Reusable App Instructions Prompt Templates & Variables Extraction & Classification Prompts Summarization & Transformation Prompts Explicit Output Requirements Prompt Version Management Prompt Testing & Evaluation Reusable Python Prompt Library API Key Security Secure API Key Storage Secure Secret Management Prompt Injection Prevention Trusted vs. Untrusted Content Tool Argument Validation Sensitive Data Handling Secure Logging AI Action Authorization Production AI Security Checklist Why AI Applications Need Evaluation Beyond Unit Tests Unit Testing OpenAI SDK Integration Code Mocking API Responses in Python Tests Testing Structured Outputs Against Schemas Testing Tool-Calling Workflows Building a Small Evaluation Dataset Measuring Accuracy, Consistency, and Failure Rates Regression Testing Prompts and Model Changes Human Evaluation Versus Automated Evaluation Creating a Repeatable Evaluation Pipeline AI Request Monitoring Token Cost Management Usage Metrics Design Reducing Model Calls Prompt & Context Optimization Model Selection & Optimization AI Caching Strategies Interactive Latency Optimization Usage Dashboards & Budget Alerts Performance & Cost Checklist Every API Call Starts Fresh Fixing API Statelessness Server-Side Conversation Memory Limits of Response Chaining What We're Building Conversation Memory Challenges Preparing an OpenAI SDK Application for Deployment Environment-Specific Configuration for Development and Production Deploying a Python AI Service with Docker Container Health Checks and Startup Configuration Managing Secrets in Cloud Deployments Background Workers for Long-Running AI Tasks Queues and Asynchronous Job Architectures Scaling AI Workloads Horizontally Monitoring Production Incidents and Failures Production Deployment Checklist for OpenAI SDK Applications Reusable OpenAI Service Classes AI Client Dependency Injection Typed AI Responses Python Configuration Management AI Request Decorators Centralized AI Error Handling Clean SDK Abstractions Reusable OpenAI Utilities Internal AI Python Libraries SDK Integration Maintenance Production AI Chatbot Document Q&A System Web Research Assistant Customer Support Agent AI Data Analysis Assistant Image Analysis App Meeting Transcription & Summary Semantic Document Search Multi-Tool AI Agent Production OpenAI SDK App Why "It Looked Fine When I Tested It" Isn't Enough Timing Note Status Note Pre-Decision Status Note Current Availability Note
Ask about this post
AI Ask about this post

Ask questions about Comparing Vectors With Cosine Similarity and get answers drawn from it.

Signed-in readers only.