コサイン類似度

Pythonで学ぶNLPの特徴量エンジニアリング

Rounak Banik

Data Scientist

コサイン類似度

1 画像提供 techninpink.com
Pythonで学ぶNLPの特徴量エンジニアリング

内積

2つのベクトルを考えます。

$$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での実装

# 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で学ぶNLPの特徴量エンジニアリング

練習してみましょう!

Pythonで学ぶNLPの特徴量エンジニアリング

Preparing Video For Download...