CSCE 471 Natural Language Processing · Spring 2027

Text Similarity

Kuan-Hao Huang · Course Website

Note: This page was created with the help of AI as a supplementary reading. It may contain errors or simplifications. The lecture slides are the primary reference for this course; please refer to them first.

“If it is sunny tomorrow, we will go hiking” and “We will go hiking if tomorrow is a sunny day” mean the same thing. “How old are you?” and “What is your age?” share almost no words, yet ask the same question. Recognizing when two pieces of text mean the same thing, or something close, is one of the most useful abilities in NLP.

This reading covers where text similarity is used, how it is evaluated, why simply taking embeddings from a pretrained BERT model works surprisingly poorly, and how Sentence-BERT fixes this by training sentence embeddings so that cosine similarity becomes meaningful.

After reading this, you should be able to list applications of text similarity · explain how the STS benchmark is built and why it is evaluated with Spearman correlation · compute Pearson and Spearman correlation · explain the limits of word-overlap similarity · explain why pretrained BERT embeddings make poor similarity measures · describe how Sentence-BERT is trained and used · compare bi-encoders and cross-encoders

1Why text similarity?

The goal: given two texts, output a score for how similar their meanings are. A good similarity function shows up everywhere:

2Evaluating similarity: the STS benchmark

The Semantic Textual Similarity (STS) benchmark (Cer et al., 2017) contains sentence pairs from news, captions, and forums, each annotated by people with a similarity score from 0 (completely unrelated) to 5 (equivalent meaning):

Sentence 1Sentence 2HumanA model
A soccer player is kicking the soccer ball into the goal from a long way down the field.A soccer player kicks the ball into the goal.3.253.94
Earlier this month, RIM had said it expected to report second-quarter earnings of between 7 cents and 11 cents a share.Excluding legal fees and other charges it expected a loss of between 1 and 4 cents a share.1.20.5
David Beckham Announces Retirement From Soccer.David Beckham retires from football.4.43.8

A model produces its own score for each pair. We do not require its scores to equal the human scores exactly (a model's cosine similarities are on a different scale anyway). Instead we measure how well the two lists of scores agree, using a correlation coefficient.

Pearson and Spearman correlation

Pearson's correlation measures how well the points fall on a straight line:

$$r = \frac{\sum_i (x_i-\bar x)(y_i-\bar y)}{\sqrt{\sum_i (x_i-\bar x)^2}\,\sqrt{\sum_i (y_i-\bar y)^2}},$$

ranging from $-1$ (perfect negative line) through $0$ (no linear relationship) to $+1$ (perfect positive line).

Spearman's correlation is Pearson's correlation computed on the ranks instead of the raw scores. It asks only whether the two lists put the pairs in the same order, so it measures any monotonic relationship, linear or not. STS results are usually reported with Spearman correlation, because what matters is that more similar pairs get higher scores, not the exact scale.

Model scores:
Figure 1 (interactive). Five sentence pairs scored by people and by a model (the example from the lecture). Rescaling the model's scores with a monotonic function changes Pearson but not Spearman, because the order is unchanged. Swapping two scores changes the order, so both drop.

3First attempts

The general recipe: encode each sentence into a vector, then compare the vectors with cosine similarity:

$$E_1=\text{Encoder}(S_1),\quad E_2=\text{Encoder}(S_2),\qquad \text{Similarity}(S_1,S_2)=\frac{E_1\cdot E_2}{\|E_1\|\,\|E_2\|}.$$

Word overlap

The simplest encoder is a bag-of-words or TF-IDF vector. Cosine similarity then measures word overlap. This captures topic, but it fails in two directions:

Pretrained BERT embeddings

A natural next step: use a pretrained BERT model as the encoder, taking either the output vector of the [CLS] token or the average of all token output vectors. Surprisingly, this performs poorly on STS, sometimes worse than simply averaging GloVe word vectors. Two reasons:

Encoder:
Figure 2 (interactive). Cosine similarities between 12 sentences under four encoders. Click a row to see that sentence's nearest neighbors. The BERT values were computed with bert-base-uncased; the sentence embedding values with all-MiniLM-L6-v2, a Sentence-Transformers model trained for similarity. Bag of words uses raw word counts (lowercased, punctuation removed). Colors use the same scale for every encoder, so notice how uniformly high BERT [CLS] is.

4Sentence-BERT

Sentence-BERT (SBERT; Reimers & Gurevych, 2019) fine-tunes BERT specifically to produce sentence embeddings whose cosine similarity reflects meaning. The key idea is a siamese network: the same BERT model (shared weights) encodes each sentence separately, followed by a pooling layer (usually mean pooling) that produces one vector per sentence, $u$ and $v$.

Training data: natural language inference

SBERT is trained on the Stanford Natural Language Inference (SNLI) dataset (and its multi-genre extension MNLI). Each example is a premise, a hypothesis, and a label saying whether the hypothesis follows from the premise:

PremiseHypothesisLabel
A boy is jumping on skateboard in the middle of a red bridge.The boy does a skateboarding trick.entailment
The boy is wearing safety equipment.neutral
The boy skates down the sidewalk.contradiction

Predicting these labels requires understanding meaning, which is exactly what the embeddings should capture.

Training objectives

Using the model (inference)

After training, each sentence is encoded independently and compared with cosine similarity; a value close to 1 means similar meaning. Training pulled paraphrases together in the embedding space and pushed unrelated sentences apart.

Margin $\epsilon$:Drag the positive (green) and negative (red) points
Figure 3 (interactive). The triplet loss in a 2-D embedding space. The loss is zero only when the negative is farther from the anchor than the positive by at least $\epsilon$ (outside the dashed circle). Training moves the points until this holds for the training triplets.

Results

Average Spearman correlation (×100) over seven STS datasets, without using any STS training data (Reimers & Gurevych, 2019, Table 1):

ModelAvg. Spearman
BERT [CLS] vector29.19
Average BERT embeddings54.81
Average GloVe embeddings61.32
InferSent (GloVe)65.01
Universal Sentence Encoder71.22
SBERT-NLI-base74.89
SBERT-NLI-large76.55

Raw BERT embeddings are worse than averaged GloVe vectors; after SBERT training, the same BERT model is the best of all.

5Bi-encoders vs. cross-encoders

There is another way to use BERT for similarity: feed both sentences into BERT together, separated by [SEP], and predict a score from the output. This cross-encoder lets every word of one sentence attend to every word of the other, so it is usually more accurate. SBERT is a bi-encoder: each sentence is encoded alone.

Cross-encoderBi-encoder (SBERT)
Inputboth sentences togethereach sentence separately
Accuracyhigherslightly lower
Cost to compare $n$ sentencesone BERT pass per pair: $n(n-1)/2$one BERT pass per sentence: $n$
Reusable vectorsnoyes: encode once, store, compare cheaply
Number of sentences $n$:
Figure 4 (interactive). Time to find the most similar pair among $n$ sentences. The per-pass times are calibrated from the SBERT paper's example (10,000 sentences: about 65 hours with a BERT cross-encoder, about 5 seconds with SBERT) and are rough estimates.

In practice the two are often combined: a fast bi-encoder retrieves a short list of candidates from millions of documents, and a cross-encoder re-ranks that short list. This is the basis of modern semantic search and of the retrieval step in retrieval-augmented generation.

6In practice and beyond

The Sentence-Transformers library makes this a few lines of code:

from sentence_transformers import SentenceTransformer
model = SentenceTransformer("all-MiniLM-L6-v2")
emb = model.encode(["The weather is lovely today.",
                    "It's so sunny outside!",
                    "He drove to the stadium."])   # shape (3, 384)
print(model.similarity(emb, emb))                  # 3 x 3 cosine similarities

7Summary

8Practice

Exercise 1: Spearman by hand

Human scores for three pairs are $[4.5, 1.0, 3.0]$ and model scores are $[0.9, 0.7, 0.2]$. Rank both lists (1 = highest) and decide whether Spearman correlation is perfect.

Human ranks: $[1, 3, 2]$. Model ranks: $[1, 2, 3]$. The model swaps the second and third pairs, so the correlation is not perfect; Spearman equals the Pearson correlation of the ranks, which is $0.5$ here.

Exercise 2: bag-of-words cosine

Using raw word counts, compute the cosine similarity of “how old are you” and “what is your age”, and of “the dog bit the man” and “the man bit the dog”.

The first pair shares no words (you ≠ your), so the cosine is $0$ despite the same meaning. The second pair has identical counts ({the: 2, dog: 1, bit: 1, man: 1}), so the cosine is $1$ despite opposite meanings.

Exercise 3: cost

You want to find, for each of 1,000 user questions, the most similar of 100,000 FAQ entries. How many BERT passes does a cross-encoder need? A bi-encoder?

Cross-encoder: one pass per (question, entry) pair, $1{,}000\times 100{,}000=10^8$ passes. Bi-encoder: encode each text once, $1{,}000+100{,}000=101{,}000$ passes (and the FAQ vectors can be computed in advance), followed by cheap vector comparisons.

Quick quiz

9Further reading