Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Text Similarity Computation

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


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

)

print

(

X.

toarray

(

)

)

TF-IDF Method

Example

from

sklearn.

feature_extraction

.

text

import

TfidfVectorizer

tfidf

=

TfidfVectorizer

(

)

tfidf_matrix

=

tfidf.

fit_transform

(

corpus

)

print

(

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

]

)

print

(

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

)

print

(

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

  1. Data preprocessing is important

  2. Normalize case
  3. Remove stop words
  4. Stemming/Lemmatization
  5. - Normalize case - Remove stop words - Stemming/Lemmatization
    1. Choose methods according to the scenario

    2. Short texts: pre-trained models such as BERT
    3. Long documents: TF-IDF + cosine similarity
    4. Real-time systems: lightweight models such as Word2Vec
    5. - Short texts: pre-trained models such as BERT - Long documents: TF-IDF + cosine similarity - Real-time systems: lightweight models such as Word2Vec
      1. Consider computational efficiency

      2. Use Approximate Nearest Neighbor (ANN) algorithms for large-scale data
      3. Consider using efficient similarity search libraries such as Faiss
      4. - Use Approximate Nearest Neighbor (ANN) algorithms for large-scale data - Consider using efficient similarity search libraries such as Faiss
        1. Continuous evaluation and optimization

        2. Build a human evaluation set
        3. Monitor production environment performance
        4. Regularly update the model
        5. - Build a human evaluation set - Monitor production environment performance - Regularly update the model

          Recommended learning resources

          1. Gensim Official Documentation
          2. Hugging Face Transformers Library
          3. Scikit-learn Text Processing Tutorial
          4. BERT paper "Attention Is All You Need"