余弦相似度

Python 中的 NLP 特征工程

Rounak Banik

Data Scientist

余弦相似度

1 图片来源 techninpink.com
Python 中的 NLP 特征工程

点积

设两个向量,

$$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 中的 NLP 特征工程

向量的模长

对任意向量,

$$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 中的 NLP 特征工程

余弦分数

向量 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 中的 NLP 特征工程

余弦分数:要点

  • 取值在 -1 到 1。
  • 在 NLP 中,取值在 0 到 1。
  • 对文档长度不敏感。
Python 中的 NLP 特征工程

使用 scikit-learn 实现

# 导入 cosine_similarity
from sklearn.metrics.pairwise import cosine_similarity
# 定义两个三维向量 A 和 B
A = (4,7,1)
B = (5,2,3)

# 计算 A 与 B 的余弦分数
score = cosine_similarity([A], [B])

# 打印余弦分数
print(score)
array([[ 0.73881883]])
Python 中的 NLP 特征工程

让我们练习!

Python 中的 NLP 特征工程

Preparing Video For Download...