LESSON 29 · EMBEDDINGS

Semantic Similarity

Learn how AI systems decide whether two pieces of text are similar in meaning, even when they use different words. You will connect embeddings, vector similarity, semantic search, thresholds, and practical Python evaluation.

30 min read•Beginner•Generative AI

By the end of this lesson, you will be able to:

  • Explain semantic similarity in simple terms.
  • Understand how embeddings turn meaning into comparable vectors.
  • Distinguish semantic similarity from keyword matching.
  • Calculate and interpret similarity scores with Python.
  • Choose practical thresholds and evaluate similarity results.
  • Apply semantic similarity to search, FAQs, recommendations, and RAG.
1

What Is Semantic Similarity?

Semantic similarity measures how closely two pieces of content are related in meaning. The wording does not have to be identical. Two sentences can use different vocabulary while expressing nearly the same idea.

TEXT A“How do I reset my password?”
SIMILAR MEANING
TEXT B“I forgot my password. How can I change it?”
Key idea: Semantic similarity is about meaning and relationships, not simply counting the words that two texts share.
2

Keyword Matching vs Semantic Similarity

Traditional keyword search can be excellent when users know the exact terms. Semantic similarity becomes useful when the query and the stored content use different words for the same or related idea.

KEYWORD MATCHING

Looks at words

Query: “cancel subscription”

Document: “How to cancel your subscription”

Strong word overlap
VS
SEMANTIC SIMILARITY

Looks at meaning

Query: “I don't want my plan anymore”

Document: “How to end your membership”

Related intent despite different wording
Practical value: A semantic system can retrieve relevant information when users phrase their questions differently from the source documents.
3

How Embeddings Enable Semantic Similarity

An embedding model converts text into a numerical vector. Once two texts have vectors, a similarity or distance function can compare those vectors.

01Text A“reset my password”
→
02Embedding A[0.21, -0.48, …]
→
CompareSimilarity metric
←
03Embedding B[0.18, -0.44, …]
←
04Text B“forgot my password”

The embedding model and similarity metric work together. A similarity score is only meaningful in the context of the model, metric, data, and task being used.

4

A Simple Semantic Similarity Example

Consider these three pairs. The first pair expresses almost the same request. The second pair is related but not identical. The third pair is unrelated.

HIGH
“How can I change my password?” “Where do I update my account password?”
MEDIUM
“My account is locked.” “I cannot log in to my account.”
LOW
“How can I change my password?” “What is the weather in Delhi?”
Important: These labels are intuitive examples, not fixed numerical scores. An actual model may rank the pairs differently.
5

Similarity Scores

A similarity function produces a numerical signal that can be used to rank candidate texts. With cosine similarity, for example, vectors with more aligned directions receive higher cosine values.

ILLUSTRATIVE RANKING
“Where can I reset my password?”0.94
“I cannot log in to my account.”0.78
“How do I update my profile?”0.49
“What is the weather today?”0.08

The numbers above are illustrative. Do not copy a score such as 0.80 as a universal definition of “similar.” Different embedding models and systems can produce different score distributions.

6

Cosine Similarity and Semantic Similarity

A common approach is to represent each text as an embedding and calculate cosine similarity between the two vectors.

FORMULA cos(θ) = (A · B) / (||A|| × ||B||) It compares the angle between two vectors.
A
B
θ

For embedding-based semantic comparison, cosine similarity is widely used, but it is not the only possible metric. The correct choice depends on the embedding system and application.

7

Python: Compare Two Simple Vectors

Before using a real embedding model, it helps to understand the comparison step with small vectors.

PythonCosine similarity
import numpy as np

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

a = np.array([0.8, 0.2, 0.1])
b = np.array([0.7, 0.3, 0.1])

score = cosine_similarity(a, b)

print("Similarity:", score)
What is happening? Each array represents a vector. The function compares their directions and returns a similarity score.
8

Python: Compare Multiple Text Candidates

A semantic search workflow usually compares one query against many candidate vectors and then ranks the candidates by similarity.

PythonRank candidate vectors
import numpy as np

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

query = np.array([0.8, 0.2, 0.1])

documents = {
    "password reset": np.array([0.78, 0.24, 0.12]),
    "account login": np.array([0.70, 0.30, 0.15]),
    "weather forecast": np.array([0.05, 0.90, 0.20]),
}

results = []

for name, vector in documents.items():
    score = cosine_similarity(query, vector)
    results.append((name, score))

results.sort(key=lambda item: item[1], reverse=True)

for name, score in results:
    print(f"{name}: {score:.3f}")

In production, the document vectors would normally be generated by an embedding model and stored in an appropriate vector index or database.

9

Similarity Is Not the Same as Correctness

A high similarity score means that the vectors are close according to the selected comparison method. It does not prove that the retrieved text is the correct answer.

High similarityUseful signal for ranking.
Relevant contentShould answer the user's actual intent.
Correct answerMust be validated for the application.
Example: A query about refund eligibility might retrieve a document about refunds because it is semantically close, but the document may describe a different country or product plan. Similarity alone cannot verify the final answer.
10

Choosing a Similarity Threshold

Sometimes an application needs a decision rather than a ranking: “Is this FAQ close enough to answer the user's question?” A threshold can help, but it must be selected from evaluation data rather than guessed.

LOW EVALUATE HIGH
Below thresholdConsider no-match, fallback search, or clarification.
Above thresholdCandidate may be relevant enough for the next step.

For example, you might test thresholds such as 0.70, 0.75, 0.80, and 0.85 on a labeled set of real queries. Measure how many relevant results are retrieved and how many irrelevant results are incorrectly accepted.

11

Semantic Similarity in Semantic Search

Semantic search is one of the most common applications. The system embeds a user query, compares it with stored document embeddings, and returns the strongest candidates.

01User query“How do I change my password?”
→
02Query embeddingConvert text to vector
→
03Similarity searchCompare with stored vectors
→
04Rank resultsHighest relevance first
Think of it this way: Embedding gives you the representation; semantic similarity gives you a way to compare representations.
12

Semantic Similarity in RAG

In Retrieval-Augmented Generation, semantic similarity helps retrieve chunks that are relevant to a user's question before the language model generates an answer.

DocumentsKnowledge base
→
ChunkingSplit content
→
EmbeddingsVector representation
→
SimilarityFind relevant chunks
→
LLMGenerate response

Retrieval quality also depends on chunk size, metadata, query formulation, embedding model, indexing strategy, reranking, and evaluation. Similarity is an important component, not the entire RAG system.

13

Real-World Applications

01FAQ Search

Match natural-language questions to help articles.

02Document Search

Find relevant passages even when wording differs.

03Recommendations

Find products or content with related representations.

04Duplicate Detection

Identify records or messages that express similar ideas.

05Support Routing

Compare a support request with known issue categories.

06RAG Retrieval

Retrieve context that can support an LLM answer.

14

Common Mistakes

Using one universal threshold

Score distributions differ by model, data, metric, and task.

Ignoring the actual intent

Two texts can be related but still answer different questions.

Comparing incompatible vectors

Vectors should come from a compatible embedding space and representation pipeline.

Skipping evaluation

Use real queries and labeled examples to measure retrieval quality.

Assuming higher is always correct

A similarity score is a ranking signal, not a guarantee of factual correctness.

Using only semantic search

Hybrid approaches can combine semantic and keyword signals when exact terms matter.

HANDS-ON PRACTICE

Build a Tiny Semantic Similarity Experiment

Create a small dataset of FAQ questions and use vectors to compare a new query against the existing questions.

  1. Write five FAQ questions about one topic.
  2. Create or obtain an embedding for each question.
  3. Create an embedding for a new user query.
  4. Calculate similarity between the query and every FAQ.
  5. Sort the results from highest to lowest similarity.
  6. Test several thresholds and inspect false matches.
Challenge: Add 20 real questions, label whether the top result is relevant, and calculate a simple top-1 accuracy. Then compare the result with keyword search.
QUICK QUIZ

Test Your Understanding

1. What does semantic similarity measure?

How closely two pieces of content are related in meaning according to a chosen representation and comparison method.

2. Why can semantic similarity work when words are different?

Embeddings represent learned relationships in a vector space, allowing related wording to be compared through their vectors.

3. Is 0.80 always a “good” similarity score?

No. Score interpretation depends on the model, metric, data, and application. Thresholds should be evaluated.

4. Does high similarity guarantee a correct answer?

No. It is a useful retrieval or ranking signal, not proof of correctness.

30-SECOND RECAP

Semantic Similarity in One Flow

TextQuery + candidate
→
EmbeddingsConvert to vectors
→
SimilarityCompare meaning
→
RankingFind relevant results
→
ApplicationSearch, RAG, recommendations

Key Takeaways

  • Semantic similarity compares content by meaning rather than only exact word overlap.
  • Embeddings provide the vector representations that make numerical comparison possible.
  • Cosine similarity is a common way to compare embedding vectors.
  • Similarity scores are model- and task-dependent; there is no universal threshold.
  • High similarity does not guarantee relevance, factual correctness, or the right answer.
  • Semantic similarity is a core building block for semantic search, recommendations, duplicate detection, and RAG.
  • Always evaluate similarity and retrieval behavior using real examples from your application.