NLP Text Similarity Calculation
Text similarity calculation is a fundamental task in Natural Language Processing (NLP) that aims to quantify the degree of similarity between two text fragments. This technique is widely used in information retrieval, question answering systems, plagiarism detection, recommendation systems, and many other fields.
Core Concepts
- Semantic similarity: Measure how close texts are in meaning
- Literal Similarity: Measure the degree of overlap of texts in surface vocabulary
- Vector Space Model: Represent texts as vectors in a high-dimensional space
- Distance metric: Compute the distance or similarity between vectors
Common Text Similarity Calculation Methods
1. Word-Frequency-Based Methods
Bag of Words Model
Example
from
sklearn.
feature_extraction
.
text
import
CountVectorizer
corpus
=
[
'I like natural language processing'
,
'I love learning NLP techniques'
,
'Text similarity computation is interesting'
]
vectorizer
=
CountVectorizer
(
)
X
=
vectorizer.
fit_transform
(
corpus
)
(
X.
toarray
(
)
)
TF-IDF Method
Example
from
sklearn.
feature_extraction
.
text
import
TfidfVectorizer
tfidf
=
TfidfVectorizer
(
)
tfidf_matrix
=
tfidf.
fit_transform
(
corpus
)
(
tfidf_matrix.
toarray
(
)
)
2. Word-Vector-Based Methods
Word2Vec Similarity
Example
from
gensim.
models
import
Word2Vec
sentences
=
[
[
'Wo' (a Chinese character)
,
'Xi huan' (a Chinese phrase)
,
'Zi ran yu yan chu li' (a Chinese phrase)
]
,
[
'Wo' (a Chinese character)
,
'Ai' (a Chinese character)
,
'Xue xi' (a Chinese phrase)
,
'NLP'
,
'Ji shu' (a Chinese phrase)
]
,
[
'Wen ben' (a Chinese phrase)
,
'Xiang si du' (a Chinese phrase)
,
'Ji suan' (a Chinese phrase)
,
'Hen' (a Chinese character)
,
'You qu' (a Chinese phrase)
]
]
model
=
Word2Vec
(
sentences
,
vector_size
=
100
,
window
=
5
,
min_count
=
1
,
workers
=
4
)
vector
=
model.
wv
[
'Zi ran yu yan chu li' (a Chinese phrase)
]
Obtain word vectors
Sentence Vector Computation
Example
import
numpy
as
np
def
sentence_vector
(
sentence
,
model
)
:
vectors
=
[
model.
wv
[
word
]
for
word
in
sentence
if
word
in
model.
wv
]
return
np.
mean
(
vectors
,
axis
=
0
)
if
vectors
else
np.
zeros
(
model.
vector_size
)
sentence_vec1
=
sentence_vector
(
[
'Wo' (a Chinese character)
,
'Xi huan' (a Chinese phrase)
,
'Zi ran yu yan chu li' (a Chinese phrase)
]
,
model
)
sentence_vec2
=
sentence_vector
(
[
'Wo' (a Chinese character)
,
'Ai' (a Chinese character)
,
'NLP'
]
,
model
)
3. Pre-trained-Model-Based Methods
BERT Similarity Calculation
Example
from
transformers
import
BertTokenizer
,
BertModel
import
torch
tokenizer
=
BertTokenizer.
from_pretrained
(
'bert-base-chinese'
)
model
=
BertModel.
from_pretrained
(
'bert-base-chinese'
)
inputs
=
tokenizer
(
"This is an example sentence"
,
return_tensors
=
"pt"
)
outputs
=
model
(
**inputs
)
last_hidden_states
=
outputs.
last_hidden_state
Similarity Measurement Metrics
Common Distance Measurement Methods
| Method Name | Formula | Feature |
|---|---|---|
| Cosine similarity | cos(θ) = (A·B)/(|A||B|) | Ignore vector length, focus on direction |
| Euclidean distance | √Σ(Ai-Bi)² | Consider the absolute position of vectors |
| Manhattan Distance | Σ|Ai-Bi| | Insensitive to outliers |
| Jaccard Similarity | |A∩B|/|A∪B| | Suitable for set similarity |
Code Implementation Example
Example
from
sklearn.
metrics
.
pairwise
import
cosine_similarity
Compute cosine similarity
similarity
=
cosine_similarity
(
tfidf_matrix
[
0
:
1
]
,
tfidf_matrix
[
1
:
2
]
)
(
f
"Text similarity: {similarity[0][0]:.4f}"
)
Practical Application Example
News Headline Similarity Detection
Example
import
pandas
as
pd
from
sklearn.
metrics
.
pairwise
import
cosine_similarity
Sample data
titles
=
[
"Apple launches a new iPhone"
,
"Apple launches the latest smartphone"
,
"Microsoft announces quarterly financial results"
,
"Google announces a new artificial intelligence plan"
]
Compute the similarity matrix
tfidf
=
TfidfVectorizer
(
)
tfidf_matrix
=
tfidf.
fit_transform
(
titles
)
similarities
=
cosine_similarity
(
tfidf_matrix
)
Display Results
df
=
pd.
DataFrame
(
similarities
,
columns
=
titles
,
index
=
titles
)
(
df
)
Result Analysis
苹果发布新款iPhone手机 苹果公司推出最新智能手机 微软公布季度财报 谷歌宣布新的人工智能计划
苹果发布新款iPhone手机 1.000000 0.723417 0.000000 0.000000
苹果公司推出最新智能手机 0.723417 1.000000 0.000000 0.000000
微软公布季度财报 0.000000 0.000000 1.000000 0.204598
谷歌宣布新的人工智能计划 0.000000 0.000000 0.204598 1.000000
Advanced Techniques and Challenges
1. Handling texts that are semantically similar but lexically different
Example
text1
=
"I like cats"
text2
=
"I hate dogs"
Low surface similarity, but semantically both express an attitude toward animals
2. Solving the problem of word polysemy
Example
"Apple" can refer to the fruit or the company
text1
=
"Apples are sweet"
text2
=
"Apple's market capitalization hits a new high"
3. Long-text similarity calculation

Best Practice Recommendations
-
Data preprocessing is important
-
Choose methods according to the scenario
-
Consider computational efficiency
-
Continuous evaluation and optimization