> ## Documentation Index
> Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Similarity Calculations

> Explains using embeddings and cosine similarity to measure semantic relevance for effective semantic search and retrieval augmented generation, improving document retrieval and grounding model outputs.

In this lesson we explain how similarity calculations let us find the most semantically relevant passages — the “needles” in a large digital haystack — without scanning every document. This is essential for semantic search and Retrieval-Augmented Generation (RAG), where the quality of retrieved context directly affects model output reliability.

A traditional keyword search matches literal characters and phrases. For example, asking about how plants communicate with a keyword search will only surface passages that contain your exact words and may miss related concepts expressed with different vocabulary.

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/jZSII6JWOjfZliaw/images/Fundamentals-of-RAG/Semantic-Search-Embeddings/Similarity-Calculations/bookshelf-books-keyword-search-plants-communicate.jpg?fit=max&auto=format&n=jZSII6JWOjfZliaw&q=85&s=aab89e48195c9c158700effc12ec8cc0" alt="The image shows a bookshelf filled with books and a stack of books in front, alongside text comparing traditional keyword search terms: &#x22;Plants&#x22; and &#x22;Communicate.&#x22;" width="1920" height="1080" data-path="images/Fundamentals-of-RAG/Semantic-Search-Embeddings/Similarity-Calculations/bookshelf-books-keyword-search-plants-communicate.jpg" />
</Frame>

Because keyword matching is literal, it can miss related concepts such as root signaling, nutrient-sharing networks, or fungal connections beneath the soil — passages that are semantically relevant but do not include your exact search terms.

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/jZSII6JWOjfZliaw/images/Fundamentals-of-RAG/Semantic-Search-Embeddings/Similarity-Calculations/bookshelf-illustration-tree-communication.jpg?fit=max&auto=format&n=jZSII6JWOjfZliaw&q=85&s=cf32a0569e1b8f1fa4e33e2791f46cc1" alt="The image shows an illustration of a bookshelf with stacked books and a list titled &#x22;What Gets Missed,&#x22; highlighting points about tree communication, forest networks, and fungal connections." width="1920" height="1080" data-path="images/Fundamentals-of-RAG/Semantic-Search-Embeddings/Similarity-Calculations/bookshelf-illustration-tree-communication.jpg" />
</Frame>

Similarity-based methods avoid this problem by measuring how close two pieces of text are in meaning rather than comparing characters. This is done by mapping words, sentences, or documents into high-dimensional vectors called embeddings.

Conceptually, embeddings are like GPS coordinates in a much higher-dimensional space. A single embedding might look like:

```python theme={null}
# Example embedding vector (truncated)
[0.2, 0.8, -0.3, 0.5, ...]
```

Each dimension can capture latent semantic features (for example “animalness”, “size”, “maturity”, “domestication”). Related terms cluster near each other in this vector space.

A simple analogy: imagine two darts thrown at a board. If they land in the same place and point the same way, the throwers were thinking similarly. In vector terms, similarity examines the direction (angle) between vectors rather than raw magnitude.

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/jZSII6JWOjfZliaw/images/Fundamentals-of-RAG/Semantic-Search-Embeddings/Similarity-Calculations/calculate-similarity-automobile-car.jpg?fit=max&auto=format&n=jZSII6JWOjfZliaw&q=85&s=314f65f5107f4a226e601c4664ba726e" alt="The image explains how to calculate similarity, using an example of &#x22;automobile&#x22; and &#x22;car&#x22; with nearly identical meanings, depicted with a similarity score of 1.0 and an angle of approximately 0 degrees." width="1920" height="1080" data-path="images/Fundamentals-of-RAG/Semantic-Search-Embeddings/Similarity-Calculations/calculate-similarity-automobile-car.jpg" />
</Frame>

The standard numerical measure for directional similarity is cosine similarity:

```text theme={null}
cosine_similarity(A, B) = (A · B) / (||A|| * ||B||)
```

Here, A · B is the dot product and ||A|| is the vector norm (magnitude). Values close to 1 indicate vectors pointing in the same direction (high semantic similarity), values near 0 indicate orthogonality (little relation), and values near -1 indicate opposite directions (opposite meanings).

You can compute cosine similarity easily in Python:

```python theme={null}
import numpy as np

def cosine_similarity(a: np.ndarray, b: np.ndarray) -> float:
    return float(np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b)))

# Example (small synthetic vectors)
vec_cat = np.array([0.9, 0.1, 0.0])
vec_kitten = np.array([0.88, 0.12, -0.01])
vec_dog = np.array([0.7, 0.2, 0.1])

print(cosine_similarity(vec_cat, vec_kitten))  # close to 1.0
print(cosine_similarity(vec_cat, vec_dog))     # lower than cat/kitten
```

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/jZSII6JWOjfZliaw/images/Fundamentals-of-RAG/Semantic-Search-Embeddings/Similarity-Calculations/similarity-calculation-vectors-explanation.jpg?fit=max&auto=format&n=jZSII6JWOjfZliaw&q=85&s=dee9027f918144efcbac8b74f05c2705" alt="The image explains how to calculate similarity using vectors, highlighting that opposite meanings have a 180-degree angle with a similarity of approximately -1.0, using &#x22;hot&#x22; and &#x22;cold&#x22; as examples." width="1920" height="1080" data-path="images/Fundamentals-of-RAG/Semantic-Search-Embeddings/Similarity-Calculations/similarity-calculation-vectors-explanation.jpg" />
</Frame>

Why this matters: similarity calculations are the core of retrieval. If retrieved documents are irrelevant or only weakly related, the language model receives poor context and may generate incorrect or confidently wrong answers (hallucinations). Accurate similarity scoring improves the relevance of retrieved context, which in turn strengthens factual grounding for RAG systems.

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/jZSII6JWOjfZliaw/images/Fundamentals-of-RAG/Semantic-Search-Embeddings/Similarity-Calculations/puppy-training-search-query-results.jpg?fit=max&auto=format&n=jZSII6JWOjfZliaw&q=85&s=5f90b8548417d4c5d656a76d1845cd22" alt="The image displays a search query &#x22;How do I train my puppy?&#x22; with three document results showing their similarity scores. Document 2, &#x22;Puppy obedience and behavior basics,&#x22; has the highest similarity score of 0.94." width="1920" height="1080" data-path="images/Fundamentals-of-RAG/Semantic-Search-Embeddings/Similarity-Calculations/puppy-training-search-query-results.jpg" />
</Frame>

High-quality similarity transforms retrieval into reliable context for generation. Poor similarity produces weak or misleading context and degrades model outputs.

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/jZSII6JWOjfZliaw/images/Fundamentals-of-RAG/Semantic-Search-Embeddings/Similarity-Calculations/good-vs-poor-similarity-document-retrieval.jpg?fit=max&auto=format&n=jZSII6JWOjfZliaw&q=85&s=9c4f1886e522946d207f712acec157a2" alt="The image contrasts the effects of poor versus good similarity in document retrieval, highlighting improved context and trustworthy results with good similarity." width="1920" height="1080" data-path="images/Fundamentals-of-RAG/Semantic-Search-Embeddings/Similarity-Calculations/good-vs-poor-similarity-document-retrieval.jpg" />
</Frame>

Quick reference — interpreting cosine similarity scores:

| Cosine similarity range | Interpretation                                              |
| ----------------------- | ----------------------------------------------------------- |
| 0.8 — 1.0               | Very high semantic similarity (near-synonyms, same concept) |
| 0.5 — 0.8               | Moderate similarity (related topics, overlapping concepts)  |
| 0.0 — 0.5               | Weak or tangential relation                                 |
| -1.0 — 0.0              | Opposite or unrelated meanings                              |

For more on embeddings and cosine similarity, see:

* [Vector embeddings overview](https://en.wikipedia.org/wiki/Word_embedding)
* [Cosine similarity explanation](https://en.wikipedia.org/wiki/Cosine_similarity)
* [Retrieval-augmented generation (RAG)](https://en.wikipedia.org/wiki/Retrieval-augmented_generation)

Key takeaways:

* Similarity calculations measure semantic closeness, not string equality.
* Embeddings map text into vectors that capture meaning; similar meanings occupy similar directions in vector space.
* Cosine similarity compares vector directions and is robust to differences in document length.
* Retrieval quality determines RAG quality: good similarity → better context → more accurate model answers.

<Callout icon="lightbulb" color="#1CB2FE">
  Focus on semantic meaning rather than exact keywords. Proper embeddings plus cosine-based retrieval are fundamental to building reliable, well-grounded RAG systems.
</Callout>

<CardGroup>
  <Card title="Watch Video" icon="video" cta="Learn more" href="https://learn.kodekloud.com/user/courses/fundamentals-of-rag/module/14bc5c47-4554-4c21-9f00-67c0f7e7f17d/lesson/918af3c5-7cd1-42a2-9fc7-92c19a962982" />
</CardGroup>
