Cosine similarity

Python 中文本特徵工程

Rounak Banik

Data Scientist

餘弦相似度

1 圖片來源:techninpink.com
Python 中文本特徵工程

內積(點積)

考慮兩個向量,

$$V = (v_1, v_2, \cdots, v_n), W = (w_1, w_2, \cdots, w_n)$$

則 V 與 W 的內積為,

$$V \cdot W = (v_1 \times w_1) + (v_2 \times w_2) + \cdots + (v_n \times w_n) $$

範例:

$$A = (4, 7, 1) \; , \; B = (5, 2, 3)$$

$$A \cdot B = (4 \times 5) + (7 \times 2) + \cdots (1 \times 3)$$

$$= 20 + 14 + 3 = 37 \color{white}{A \cdot B d}$$

$$$$

Python 中文本特徵工程

向量的長度

對任一向量,

$$V = (v_1, v_2, \cdots, v_n)$$

其長度定義為,

$$||\mathbf{V}|| = \sqrt{(v_1)^{2} + (v_2)^{2} + ... + (v_n)^{2}} $$

範例:

$$A = (4, 7, 1) \; , \; B = (5, 2, 3)$$

$$||\mathbf{A}|| = \sqrt{(4)^{2} + (7)^{2} + (1)^{2}} $$

$$ \color{white}{filler} = \sqrt{16 + 49 + 1} = \sqrt{66}$$

$$

Python 中文本特徵工程

餘弦分數

向量 A 與 B 的夾角

$$A: (4, 7, 1)$$

$$B: (5, 2, 3)$$

餘弦分數:

$$cos(A,B) = \frac{A \cdot B}{|A| \cdot |B|}$$

$$\color{white}{fillers lorem}= \frac{37}{\sqrt{66} \times \sqrt{38}}$$

$$\color{white}{fillers l}= 0.7388$$

Python 中文本特徵工程

餘弦分數:重點

  • 介於 -1 與 1 之間。
  • 在 NLP 中介於 0 與 1。
  • 對文件長度具魯棒性。
Python 中文本特徵工程

使用 scikit-learn 實作

# Import the cosine_similarity
from sklearn.metrics.pairwise import cosine_similarity
# Define two 3-dimensional vectors A and B
A = (4,7,1)
B = (5,2,3)

# Compute the cosine score of A and B
score = cosine_similarity([A], [B])

# Print the cosine score
print(score)
array([[ 0.73881883]])
Python 中文本特徵工程

一起來練習吧!

Python 中文本特徵工程

Preparing Video For Download...