Runoob Tutorial ArchiveEnglish

Cosine similarity for text recommendation

Cosine similarity for text recommendation

Represent sentences using bag-of-words vectors, calculate cosine similarity, and find the most similar sentences.

After learning this case study, you will understand the mathematical foundation of search and recommendation systems—dot product measures "direction," and magnitude is used for normalization.


Real-life introduction

**Taobao search for "Bluetooth headphones"

When you enter "Bluetooth headphones," Taobao instantly finds the most relevant items from millions of products. It doesn't sort based on whether the title contains an exact match—instead, it converts each product title into a sequence of numbers (a vector) and then compares whether the "direction" of your search term matches the direction of each title.

The closer the directions, the more similar the meanings. Whether the title is long or short does not affect the judgment—this is the intuition of cosine similarity.


Intuitive understanding

Imagine two arrows shot from a bow. The more consistent the direction of the two arrows, the closer the cosine of the angle between them is to 1; if the two arrows are perpendicular, the cosine is 0; if the two arrows are in opposite directions, the cosine is -1.

~ 1

Same direction

The two sentences mean the same thing

~ 0

Perpendicular to each other

Two sentences are completely unrelated

~ -1

Opposite directions

Rare in bag-of-words models

The key question is: how to "turn" a piece of text into an arrow? This requires introducing the bag-of-words model.


Mathematical definition

Cosine similarity formula

[ \cos(\theta) = \frac{\mathbf{a} \cdot \mathbf{b}}{|\mathbf{a}| \cdot |\mathbf{b}|} = \frac{\sum_{i=1}^{n} a_i \cdot b_i}{\sqrt{\sum a_i^2} \cdot \sqrt{\sum b_i^2}} ]

The numerator is the dot product (measuring how "aligned" two vectors are), and the denominator is the product of the magnitudes of the two vectors (to eliminate the effect of vector length).

Bag of Words

A method to turn a sentence into a vector:

  1. Determine a vocabulary (all possible words that might appear)
  2. For each sentence, mark 1 if a word appears and 0 if it does not appear
  3. Obtain a vector whose length equals the size of the vocabulary

Here we use the most simplified "presence" (one-hot bag of words); in practical applications, TF-IDF or Word Embedding is commonly used instead. However, the core idea is the same: turning text into a vector that can participate in mathematical operations.


Python hands-on practice

Construct a bag-of-words vector using 5 Chinese sentences, calculate the cosine similarity with the query sentence, and find the most similar sentence.

Example

import

numpy

as

np

1. Prepare corpus—5 Chinese sentences covering two topics: AI learning and daily life

sentences

=

[

   

"I like using python to learn machine learning"

,

   

"Python is a good tool for learning artificial intelligence"

,

   

The weather is nice today, perfect for a walk.

,

   

Deep learning requires a large amount of data and computing power.

,

   

Walking is a great way to relax.

,

]

2. Build vocabulary (simplified teaching version, manually define possible words)

vocab_words

=

[

"I"

,

"Like"

,

"Use"

,

"python"

,

"Learn"

,

"Machine learning"

,

"is"

,

               

"Artificial intelligence"

,

"good"

,

"Tools"

,

"Today"

,

"Weather"

,

"Very"

,

"suitable"

,

               

"go out"

,

"take a walk"

,

"Deep learning"

,

"requires"

,

"large amounts of"

,

"of"

,

"Data"

,

               

"Computing Power"

,

"A type of"

,

"Relaxation"

,

"method"

]

def

to_vector

(

sentence

,

vocab

)

:

   

"""Convert sentence to bag-of-words vector—mark words that appear as 1"""

vec

=

np.

zeros

(

len

(

vocab

)

)

   

for

i

,

w

in

enumerate

(

vocab

)

:

       

if

w

in

sentence:

vec

[

i

]

=

1

 

Count 1 when a word appears

   

return

vec

5 sentences -> 5 vectors

vectors

=

np.

array

(

[

to_vector

(

s

,

vocab_words

)

for

s

in

sentences

]

)

print

(

"RUNOOB vector dimension for each sentence:"

,

vectors.

shape

[

1

]

,

     

(vocabulary size)

)

3. Handwritten cosine similarity function (without calling sklearn)

def

cosine_similarity

(

a

,

b

)

:

dot

=

np.

dot

(

a

,

b

)

           

Dot product

norm_a

=

np.

linalg

.

norm

(

a

)

   

length of a

norm_b

=

np.

linalg

.

norm

(

b

)

   

the modulus of b

   

if

norm_a

==

0

or

norm_b

==

0

:

       

return

0.0

               

The zero vector has no direction

   

return

dot /

(

norm_a * norm_b

)

4. Given a query sentence, find the most similar sentence

query

=

"I am learning python and artificial intelligence"

query_vec

=

to_vector

(

query

,

vocab_words

)

sims

=

[

cosine_similarity

(

query_vec

,

v

)

for

v

in

vectors

]

print

(

f

"\nRUNOOB Query sentence: {query!r}\n"

)

for

s

,

sim

in

sorted

(

zip

(

sentences

,

sims

)

,

key

=

lambda

x: -x

[

1

]

)

:

   

print

(

f

" Similarity {sim:.3f} <- {s}"

)

5. Verification: The similarity of unrelated sentences is 0

print

(

"RUNOOB verification: two completely unrelated sentences"

)

v1

=

to_vector

(

"python machine learning"

,

vocab_words

)

v2

=

to_vector

(

"Stroll and relax"

,

vocab_words

)

print

(

f

" 'python machine learning' vs 'walking and relaxing': "

f

"cos = {cosine_similarity(v1, v2):.3f}"

)

Original prompt (Chinese, left untranslated)



RUNOOB 每句话的向量维度: 25 (词表大小)



RUNOOB 查询句子: '我在学习python和人工智能'



  相似度 0.577  <-  python是学习人工智能的好工具

  相似度 0.500  <-  我喜欢用python学习机器学习

  相似度 0.000  <-  今天天气很好适合出去散步

  相似度 0.000  <-  深度学习需要大量的数据和算力

  相似度 0.000  <-  散步是一种很好的放松方式



RUNOOB 验证:两个完全不相关的句子

  'python机器学习' vs '散步放松': cos = 0.000

The result is intuitive: sentences containing the same keywords have high similarity, and sentences with completely unrelated content have a similarity of 0.


Application scenarios in AI

AI scenarios How to use cosine similarity
Search engine Convert both search terms and documents into vectors, and return results sorted by cosine similarity.
Recommendation system Find products most similar to the user's historical behavior vector
Semantic search Vectorization using word embeddings (Word2Vec/BERT) to capture synonyms—"Bluetooth headphones" and "wireless earbuds" will also match
Face recognition Encode face images into vectors (Face Embedding) and compare the cosine similarity of two faces to determine if they are the same person
RAG retrieval In large model applications, use cosine similarity to retrieve the most relevant document snippets from the knowledge base

The dot product of Q and K (QK^T) in the "attention mechanism" used in large models like GPT is essentially also calculating similarity—cosine similarity omits the normalization of the denominator's magnitude.