見出し画像

Google Colabでjina-embeddings-v2-base-enを使ってみた

jina-embeddings-v2-base-enというモデルを使ってみました。

Bertアーキテクチャに基づいており、8192シーケンス長をサポートしているとのことです。

また、このモデルは1億3700万パラメータでモデルサイズが小さいのも驚きです。

今回は、Hugging FaceにあるコードをGoogle Colabで実行してみます。

実行コードは、以下となります。

!pip install transformers
from transformers import AutoModel
from numpy.linalg import norm

cos_sim = lambda a,b: (a @ b.T) / (norm(a)*norm(b))
model = AutoModel.from_pretrained('jinaai/jina-embeddings-v2-base-en', trust_remote_code=True) # trust_remote_code is needed to use the encode method
embeddings = model.encode(['How is the weather today?', 'What is the current weather like today?'])
print(cos_sim(embeddings[0], embeddings[1]))

コードの内容は、How is the weather today?とWhat is the current weather like today?の文章がどれくらい似ているかを知るためにcos類似度を求めるコードとなります。

cos類似度は、より1に近ければ似ている文章で、0に近ければ似ていない文章となります。

0.9341315

コード実行結果

他にも類似文章を見てみます。

embeddings = model.encode(['I like apples.', 'I love apples.'])
print(cos_sim(embeddings[0], embeddings[1]))

0.96306086

実行結果

likeとloveの違いだけでしたので、より1に近いです。

embeddings = model.encode(['I like bananas.', 'I love apples.'])
print(cos_sim(embeddings[0], embeddings[1]))

0.78509736

実行結果

bananasとapplesの違いがあっても似ている文章に分類されるんですね。


embeddings = model.encode(['I like OpenAI.', 'I like OpenAI.'])
print(cos_sim(embeddings[0], embeddings[1]))

1.0000001

実行結果

同じ文章だと1になるかと思いきや、1.0000001となっています。1以上となるのが凄く気になります。バグですかな。


この記事が気に入ったらサポートをしてみませんか?