Bird
Raised Fist0
NLPml~8 mins

Semantic similarity with embeddings in NLP - Model Metrics & Evaluation

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Metrics & Evaluation - Semantic similarity with embeddings
Which metric matters for semantic similarity and WHY

For semantic similarity using embeddings, the key metric is cosine similarity. This measures how close two vectors point in the same direction, regardless of their length. It tells us how similar two pieces of text are in meaning.

Why cosine similarity? Because embeddings are numeric vectors representing meaning, and cosine similarity captures the angle between them, which reflects semantic closeness well.

Sometimes, we also use Euclidean distance or Manhattan distance, but cosine similarity is most common and intuitive for meaning comparison.

Confusion matrix or equivalent visualization

Semantic similarity is often a continuous score, not a classification, so confusion matrices don't directly apply. But if we set a threshold to decide if two texts are "similar" or "not similar," we can create a confusion matrix:

      | Predicted Similar | Predicted Not Similar |
      |-------------------|-----------------------|
      | True Positive (TP) | False Positive (FP)    |
      | False Negative (FN)| True Negative (TN)     |
    

For example, if cosine similarity > 0.8 means "similar," then:

  • TP: Pairs correctly identified as similar
  • FP: Pairs incorrectly identified as similar
  • FN: Pairs incorrectly identified as not similar
  • TN: Pairs correctly identified as not similar
Precision vs Recall tradeoff with examples

When deciding if two texts are similar, precision and recall matter:

  • Precision: Of all pairs predicted similar, how many truly are? High precision means few false alarms.
  • Recall: Of all truly similar pairs, how many did we find? High recall means we miss few true matches.

Example: In a plagiarism detector, high recall is important to catch all copied texts, even if some false alarms happen (lower precision).

In a recommendation system, high precision is important to avoid suggesting irrelevant items, even if some good matches are missed (lower recall).

What "good" vs "bad" metric values look like

Good semantic similarity results have:

  • Cosine similarity close to 1 for truly similar pairs (e.g., > 0.8)
  • Cosine similarity close to 0 or negative for unrelated pairs
  • High precision and recall if thresholding is used (e.g., both > 0.8)

Bad results show:

  • High similarity scores for unrelated pairs (false positives)
  • Low similarity scores for truly similar pairs (false negatives)
  • Precision or recall very low (e.g., < 0.5), meaning many mistakes
Common pitfalls in semantic similarity metrics
  • Ignoring context: Embeddings may not capture subtle meaning differences if context is missing.
  • Threshold choice: Picking a bad similarity threshold can cause many false positives or negatives.
  • Data leakage: Using test data in training embeddings inflates similarity scores unfairly.
  • Overfitting: Embeddings tuned too closely to training data may not generalize well.
  • Using only accuracy: Accuracy is less meaningful for similarity tasks without clear classes.
Self-check question

Your semantic similarity model has an average cosine similarity of 0.95 on similar pairs but 0.6 on unrelated pairs. Is this good?

Answer: Not really. While 0.95 on similar pairs is excellent, 0.6 on unrelated pairs is quite high, meaning many unrelated pairs appear similar. This can cause many false positives if thresholding is used. You should improve the model to lower similarity scores for unrelated pairs.

Key Result
Cosine similarity is key for semantic similarity; good models show high similarity for related pairs and low for unrelated pairs.

Practice

(1/5)
1. What does semantic similarity with embeddings help us do in natural language processing?
easy
A. Translate text from one language to another
B. Count the number of words in a sentence
C. Measure how similar the meanings of two texts are
D. Generate random sentences

Solution

  1. Step 1: Understand semantic similarity

    Semantic similarity means checking how close the meanings of two texts are, not just the words.
  2. Step 2: Role of embeddings

    Embeddings convert text into numbers that capture meaning, allowing comparison of texts by meaning.
  3. Final Answer:

    Measure how similar the meanings of two texts are -> Option C
  4. Quick Check:

    Semantic similarity = meaning comparison [OK]
Hint: Semantic similarity compares meanings, not word counts [OK]
Common Mistakes:
  • Confusing similarity with word count
  • Thinking embeddings translate text
  • Assuming semantic similarity generates text
2. Which Python library is commonly used to compute cosine similarity between embeddings?
easy
A. matplotlib
B. scikit-learn
C. pandas
D. flask

Solution

  1. Step 1: Identify cosine similarity function

    Cosine similarity is often computed using scikit-learn's metrics module.
  2. Step 2: Check other libraries

    matplotlib is for plotting, pandas for data frames, flask for web apps, so they don't compute cosine similarity.
  3. Final Answer:

    scikit-learn -> Option B
  4. Quick Check:

    Cosine similarity = scikit-learn [OK]
Hint: Use scikit-learn for cosine similarity calculations [OK]
Common Mistakes:
  • Using matplotlib for similarity
  • Confusing pandas with similarity tools
  • Thinking flask handles embeddings
3. What is the output of this Python code snippet?
from sklearn.metrics.pairwise import cosine_similarity
import numpy as np

emb1 = np.array([[1, 0, 0]])
emb2 = np.array([[0, 1, 0]])
sim = cosine_similarity(emb1, emb2)
print(sim[0][0])
medium
A. Error
B. 1.0
C. -1.0
D. 0.0

Solution

  1. Step 1: Understand cosine similarity formula

    Cosine similarity measures the cosine of the angle between two vectors. Orthogonal vectors have similarity 0.
  2. Step 2: Analyze given vectors

    emb1 is [1,0,0], emb2 is [0,1,0]. They are perpendicular, so similarity is 0.
  3. Final Answer:

    0.0 -> Option D
  4. Quick Check:

    Orthogonal vectors similarity = 0.0 [OK]
Hint: Orthogonal vectors have cosine similarity zero [OK]
Common Mistakes:
  • Assuming similarity is 1 for any vectors
  • Confusing dot product with cosine similarity
  • Expecting error due to shape
4. Identify the error in this code that tries to compute semantic similarity:
from sklearn.metrics.pairwise import cosine_similarity

emb1 = [0.1, 0.2, 0.3]
emb2 = [0.1, 0.2, 0.3]
sim = cosine_similarity(emb1, emb2)
print(sim)
medium
A. emb1 and emb2 should be 2D arrays, not 1D lists
B. cosine_similarity function does not exist in sklearn
C. embeddings must be strings, not numbers
D. print statement syntax is incorrect

Solution

  1. Step 1: Check input format for cosine_similarity

    cosine_similarity expects 2D arrays (like [[...]]), but emb1 and emb2 are 1D lists.
  2. Step 2: Confirm other options

    cosine_similarity exists, embeddings are numeric vectors, and print syntax is correct in Python 3.
  3. Final Answer:

    emb1 and emb2 should be 2D arrays, not 1D lists -> Option A
  4. Quick Check:

    Input shape must be 2D arrays [OK]
Hint: cosine_similarity needs 2D arrays, not 1D lists [OK]
Common Mistakes:
  • Passing 1D lists instead of 2D arrays
  • Thinking embeddings must be text
  • Misunderstanding print syntax
5. You have two sentences: "I love apples" and "I adore oranges". Using a pre-trained embedding model, you get vectors for both. Which approach best helps you find if these sentences have similar meaning?
hard
A. Calculate cosine similarity between their embeddings
B. Count common words between the sentences
C. Check if sentence lengths are equal
D. Compare the first letters of each word

Solution

  1. Step 1: Understand semantic similarity goal

    We want to compare meanings, not just words or sentence length.
  2. Step 2: Use embeddings and cosine similarity

    Pre-trained embeddings capture meaning; cosine similarity measures closeness of meanings numerically.
  3. Final Answer:

    Calculate cosine similarity between their embeddings -> Option A
  4. Quick Check:

    Meaning comparison = cosine similarity on embeddings [OK]
Hint: Use cosine similarity on embeddings for meaning comparison [OK]
Common Mistakes:
  • Relying on word overlap only
  • Using sentence length as similarity
  • Comparing letters instead of meaning