Cosine distance
Cosine distance is a measure of directional dissimilarity between nonzero vectors, commonly defined as one minus their cosine similarity.
Just Use Postgres!
Cosine distance is a dissimilarity measure derived from the angle between two vectors, commonly defined as one minus cosine similarity.
- How it is used
- Ranks semantically related embeddings for movie recommendations and vector similarity search in Postgres.
- How deep it goes
- Explains angle-based ranking, SQL execution, distance values, phrase refinement, and HNSW indexing without developing the underlying mathematics.
- Examples
- Uses Star Wars movie searches, explicit distance output, refined phrases, SQL queries, and HNSW execution plans.
- What you can do after
- Apply cosine distance via pgvector SQL to rank embeddings, inspect relevance, refine queries, and configure HNSW search.
Natural Language Processing in Action, Second Edition
The cosine distance metric measures the angular dissimilarity between vectors and is commonly used to estimate similarity in their encoded meanings.
- How it is used
- Estimates semantic similarity between natural-language vectors and supports efficient comparison in search and language-processing systems.
- How deep it goes
- Explains angular meaning, bounded scaling, Euclidean contrast, and similarity conversion, but does not derive the full formula.
- Examples
- Uses message-quality vectors, a two-dimensional NumPy subtraction, and a diagram of Euclidean vector distance.
- What you can do after
- Apply cosine distance to compare high-dimensional language vectors and convert it into cosine similarity when needed.
Read how Natural Language Processing in Action, Second Edition explains cosine distance →
Rearchitecting LLMs
Cosine distance measures dissimilarity between vectors based on their directional alignment.
- How it is used
- Uses cosine distance as the hidden-loss component of a compound objective for aligning student and teacher representations.
- How deep it goes
- Computes one minus mean cosine similarity after flattening and normalizing representations, then averages across mapped layers.
- Examples
- Compares [1, 2, 3] with [10, 20, 30] to illustrate equal direction despite different magnitudes.
- What you can do after
- Apply it via PyTorch tensor operations to calculate hidden-state alignment loss across mapped layers.
Software Testing with Generative AI
A distance measure derived from the cosine of the angle between vectors, where a lower value indicates greater directional similarity.
- How it is used
- Ranks user-story documents against queries to retrieve context for testing-risk prompts.
- How deep it goes
- Demonstrates implementation and selection logic but defers the mathematical workings and production-level algorithm complexity.
- Examples
- Uses user stories, document corpora, the query “I want test ideas,” and a lowest-score Java matching method.
- What you can do after
- Apply it via Apache Commons Text to select the closest document for a generated prompt.
Read how Software Testing with Generative AI explains cosine distance →
The Art of AI Product Development
Cosine distance measures the difference in orientation between two vectors and is commonly used to compare embeddings.
- How it is used
- Uses cosine distance to compare query and document embeddings during semantic search and retrieval-augmented generation.
- How deep it goes
- Explains query embedding, similarity-based top-k retrieval, tuning trade-offs, and information loss without deriving the mathematics.
- Examples
- Uses embedded queries, stored text chunks, top-k results, and Weaviate retrieval as concrete examples.
- What you can do after
- Apply it via an embedding database while tuning retrieval breadth and evaluating relevance problems.
Read how The Art of AI Product Development explains cosine distance →
Build an Advanced RAG Application (From Scratch)
Cosine distance measures vector dissimilarity based on their angular separation, commonly defined as one minus cosine similarity.
- How it is used
- Uses angular vector comparison to rank semantically related documents in a semantic-search pipeline.
- How deep it goes
- Explains angular intuition and demonstrates SciPy computation, but defers detailed metric mathematics and large-scale indexing.
- Examples
- Uses cat, dog, bird, and machine-learning sentences plus a two-dimensional pet-and-furry vector diagram.
- What you can do after
- Apply it via SciPy to rank encoded query-document pairs and select the nearest semantic match.
Read how Build an Advanced RAG Application (From Scratch) explains cosine distance →
AI Agents in Action
Cosine distance is a vector distance measure defined as one minus cosine similarity, ranging from zero for most similar vectors to two for semantically opposite vectors.
- How it is used
- Ranks document vectors by dissimilarity in similarity-search workflows, including TF–IDF comparisons and embedding-based retrieval.
- How deep it goes
- Defines distance as one minus cosine similarity and explains its 0–2 range, without deriving the underlying vector calculation.
- Examples
- Compares eight sample text documents and retrieves documents from an embedding-based query with distance scores.
- What you can do after
- Evaluate document-vector similarity with scikit-learn or inspect distance-ranked retrieval results from Chroma.
Designing AI Systems
Cosine distance measures dissimilarity between vectors based on the angle between their directions, with zero indicating identical direction.
- How it is used
- Deploys cosine distance inside database-backed vector search to rank embeddings and gate retrieved context by similarity.
- How deep it goes
- Defines distance behavior and implements operator-to-score conversion, but does not derive the underlying geometry mathematically.
- Examples
- Uses pgvector's <=> operator and the expression 1 - (embedding <=> query_embedding) in a PostgreSQL search.
- What you can do after
- Apply it via pgvector to rank stored embeddings, convert distances into scores, and enforce relevance thresholds.
AI Agents in Action, Second Edition
Cosine distance is a metric equal to one minus cosine similarity that measures angular dissimilarity between vectors.
- How it is used
- Ranks semantically retrieved documents by angular dissimilarity instead of relying only on matching terms or phrases.
- How deep it goes
- Defines the one-minus-similarity formula, explains the 0-to-2 range, and connects scores to vector retrieval without deriving implementation internals.
- Examples
- Uses TF-IDF document vectors, sentence-pair similarity matrices, and Chroma queries returning document identifiers, distances, and text.
- What you can do after
- Apply it via Chroma DB or cosine-based vector search to interpret and rank document-retrieval results.
Read how AI Agents in Action, Second Edition explains cosine distance →
Also covered in
What to know first
- embeddingAn embedding is a numerical vector representation of an item in a feature space, encoding selected properties or relationships for computational tasks such as comparison or retrieval.
- Euclidean distanceEuclidean distance is the straight-line distance between two points, calculated as the square root of the sum of squared differences between corresponding coordinates.
- term frequency-inverse document frequencyTerm frequency-inverse document frequency (TF-IDF) is a text-weighting scheme that combines a term’s frequency in a document with its inverse frequency across a document collection.
- vector databaseA vector database is a data-management system that stores and indexes numerical vector representations and supports retrieval through similarity or distance searches.
Related concepts
- cosine similarityequivalent to · Cosine similarity measures the directional alignment of two nonzero vectors as the cosine of the angle between them, equal to their dot product divided by the product of their magnitudes.
- Euclidean distancealternative to · Euclidean distance is the straight-line distance between two points, calculated as the square root of the sum of squared differences between corresponding coordinates.
- followed by operatorkind of · The PostgreSQL full-text search followed-by operator matches lexemes occurring in the specified positional sequence.
- Apache Commons Textused by · A Java library providing utilities for text processing, comparison, escaping, and related operations.
- hidden lossmeasures · A hidden loss is a loss term that measures disagreement between intermediate representations produced by a teacher and a student model.
- ivfflatuses · IVFFlat is an approximate nearest-neighbor vector index that partitions vectors into centroid-based inverted lists and compares vectors within selected lists.
Questions about cosine distance
What is cosine distance?
Cosine distance is a measure of directional dissimilarity between nonzero vectors, commonly defined as one minus their cosine similarity.
Which Manning books explain cosine distance?
Just Use Postgres!, Natural Language Processing in Action, Second Edition, Rearchitecting LLMs, Software Testing with Generative AI, The Art of AI Product Development, Build an Advanced RAG Application (From Scratch), AI Agents in Action, Designing AI Systems and 1 more.
What should I know before learning cosine distance?
Manning books that teach cosine distance usually introduce embedding, Euclidean distance, term frequency-inverse document frequency and vector database first.
What is the difference between cosine distance and Euclidean distance?
Cosine distance is a measure of directional dissimilarity between nonzero vectors, commonly defined as one minus their cosine similarity. Euclidean distance is the straight-line distance between two points, calculated as the square root of the sum of squared differences between corresponding coordinates.
What is cosine distance a kind of?
Cosine distance is a kind of followed by operator. The PostgreSQL full-text search followed-by operator matches lexemes occurring in the specified positional sequence.
These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.








