概要
ベクトルストア(Faiss)とコサイン類似度の計算をまとめる。
Faiss
「Faiss」は、Meta社が開発したライブラリで、文埋め込みのような高次元ベクトルを効率的にインデックス化し、クエリのベクトルに対して高速に検索することができる。
コサイン類似度
コサイン類似度(Cosine Similarity)は、2つのベクトル間の類似度を測定する方法の一つです。 文書をベクトル化し、コサイン類似度で文書間の類似性を計算します。
環境
Google Colaboratory
langchain==0.0.304
langchain-community==0.0.13
実装
パッケージのインストール
!pip install sentence-transformers !pip install faiss-gpu !pip install fugashi !pip install ipadic !pip install langchain==0.0.304 !pip install langchain-community==0.0.13
ライブラリのインポート
import os import pandas as pd import numpy as np from langchain_community.embeddings import HuggingFaceBgeEmbeddings from langchain.vectorstores.utils import DistanceStrategy from langchain_community.vectorstores import FAISS
テキストのサンプル
「次の日は良い天気です」と、「明日の天気は晴れです, 明日の天気は雨です, 晴れが好きです」の類似度を計算します。
sentences = ["明日の天気は晴れです", "明日の天気は雨です", "晴れが好きです"] query = "次の日は良い天気です"
Faissインデックスを作成
embeddingのモデルはsonoisaを使用しました。
コサイン類似度の場合は、distance_strategy = DistanceStrategy.MAX_INNER_PRODUCTとするようです。 詳しくは以下の記事で解説されています。
embeddings = HuggingFaceBgeEmbeddings(model_name ="sonoisa/sentence-bert-base-ja-mean-tokens-v2", encode_kwargs={"normalize_embeddings":True }) db = FAISS.from_texts(sentences, embeddings, distance_strategy = DistanceStrategy.MAX_INNER_PRODUCT)
コサイン類似度の計算
docs_and_scores = db.similarity_search_with_score(query) docs_and_scores
[(Document(page_content='明日の天気は晴れです'), 0.5200575), (Document(page_content='晴れが好きです'), 0.49400577), (Document(page_content='明日の天気は雨です'), 0.39415556)]
クエリ(次の日は良い天気です)と意味が近い、「明日の天気は晴れです」の類似度が高くなりました。
print(docs_and_scores[0][0]) print(docs_and_scores[0][1])
page_content='明日の天気は晴れです' 0.5200575
Faissの保存
保存しておけばロードして簡単に再利用することができます。
db.save_local("faiss_index")
Faissのロード
new_db = FAISS.load_local("faiss_index", embeddings)
#再度計算 docs_and_scores = new_db.similarity_search_with_score(query) print(docs_and_scores[0][0]) print(docs_and_scores[0][1])
page_content='明日の天気は晴れです' 0.5200575