Skip to main content
Sentence embeddings convert an entire sentence or paragraph into a fixed-size numerical vector. These vectors capture semantic meaning, allowing us to compare texts and retrieve the most relevant results.

1. What are Sentence Embeddings?

For example:
A good embedding model should understand that:
  • Sentence 1 and Sentence 2 have similar meanings.
  • Sentence 3 is unrelated.
The sentences are converted into vectors:
Similar sentences produce vectors that are closer together in the vector space.

2. Sentence-Transformers

sentence-transformers is a Python library used to generate high-quality embeddings for sentences, paragraphs, and documents. Install it using:
A commonly used model is:
This model converts text into dense vector embeddings.

3. Generate Sentence Embeddings

Create a file named:

Example Output

Each sentence is represented as a vector with 384 numerical values for this model.

4. Cosine Similarity

Cosine similarity measures how similar two vectors are. The formula is: Cosine Similarity=ABAB\text{Cosine Similarity} = \frac{A \cdot B}{\|A\| \|B\|} Where:
  • A is the first embedding vector.
  • B is the second embedding vector.
  • A · B is the dot product.
  • ||A|| and ||B|| represent the magnitude of the vectors.

Interpretation

For sentence embeddings, semantically similar text generally produces a higher similarity score.

5. Compare Sentences Using Cosine Similarity

Example structure:
Interpretation:

6. Semantic Search and Retrieval

The main use of sentence embeddings is retrieval. Suppose we have a collection of documents:
A user asks:
Instead of searching only for exact keywords, we:
This is called semantic search.

7. Complete Retrieval Example

Create:

8. Expected Output

The exact scores may vary depending on the model version and environment.
The retrieval system returns documents with the highest semantic similarity.

9. Retrieve Only Top K Results

Usually, we do not need every document. We retrieve only the top results.
Output:

10. Important Concepts


11. Retrieval Workflow

Key Takeaway

Sentence embeddings are the foundation of modern semantic search and retrieval systems. Instead of matching exact words, the system compares the meaning of the query with the meaning of stored documents. This workflow is also a fundamental building block of RAG systems: