🚀 Zilliz Cloudを無料で試す、完全管理型のMilvus—10倍の高速パフォーマンスを体験しよう!今すぐ試す>>

milvus-logo
LFAI
  • Home
  • Blog
  • 埋め込みモデルとPyMilvusの統合の紹介

埋め込みモデルとPyMilvusの統合の紹介

  • Engineering
June 05, 2024
Stephen Batifol

Milvusは、AIアプリケーションのために特別に設計されたオープンソースのベクトルデータベースです。機械学習、ディープラーニング、その他のAI関連プロジェクトのいずれであっても、Milvusは大規模なベクトルデータを扱うための堅牢で効率的な方法を提供します。

現在、MilvusのPython SDKであるPyMilvusのモデルモジュール統合により、EmbeddingモデルとRerankingモデルの追加がさらに簡単になりました。この統合により、データを検索可能なベクトルに変換したり、RAG(Retrieval Augmented Generation)のようなより正確な結果を得るために結果を再ランキングしたりすることが簡単になります。

このブログでは、密な埋め込みモデル、疎な埋め込みモデル、そして再ランカーについてレビューし、Pythonアプリケーションでローカルに実行できるMilvusの軽量版であるMilvus Liteを使用して、実際の使い方をデモンストレーションします。

密な埋め込みと疎な埋め込み

統合機能の使い方を説明する前に、ベクトル埋込みの2つの主要なカテゴリを見てみましょう。

ベクトル埋め込みは一般的に2つの主要なカテゴリに分類されます:密な埋め込み(Dense Embeddings)と疎な埋め込み(Sparse Embeddings)です。

  • 密な埋め込みは高次元のベクトルで、要素のほとんどまたはすべてがゼロでないため、テキストのセマンティクスやファジーな意味をエンコードするのに理想的です。

  • スパース埋め込みは、多くのゼロ要素を持つ高次元ベクトルであり、厳密な概念や隣接する概念の符号化に適しています。

Milvusは両方のタイプの埋め込みをサポートし、ハイブリッド検索を提供します。ハイブリッド検索では、同じコレクション内の様々なベクトルフィールドを横断して検索を行うことができます。これらのベクトルは、データの異なる面を表したり、多様な埋め込みモデルを使用したり、異なるデータ処理方法を採用したりすることができ、再ランカーを使用して結果を組み合わせることができます。

埋め込みと再ランキング統合の使い方

以下のセクションでは、埋め込みデータを生成し、ベクトル検索を行うために統合機能を使用する3つの実用的な例を示します。

例1: デフォルトの埋め込み関数を使って高密度ベクトルを生成する

Milvusで埋め込み関数とリランキング関数を使用するには、model パッケージと一緒にpymilvus クライアントをインストールする必要があります。

pip install "pymilvus[model]"

このステップではMilvus Liteをインストールし、Pythonアプリケーション内でローカルにMilvusを実行できるようにします。また、Milvus Liteにはモデルサブパッケージが含まれており、エンベッディングとリランキングに関するすべてのユーティリティが含まれています。

モデルサブパッケージは、OpenAI、Sentence TransformersBGE-M3、BM25、SPLADE、Jina AIプレトレーニングモデルを含む様々なエンベッディングモデルをサポートしています。

この例では、DefaultEmbeddingFunctionall-MiniLM-L6-v2 Sentence Transformer モデルに基づいて、簡単にするために使用しています。モデルは約70MBで、最初の使用時にダウンロードされる:

from pymilvus import model

# This will download "all-MiniLM-L6-v2", a lightweight model.
ef = model.DefaultEmbeddingFunction()

# Data from which embeddings are to be generated
docs = [
   "Artificial intelligence was founded as an academic discipline in 1956.",
   "Alan Turing was the first person to conduct substantial research in AI.",
   "Born in Maida Vale, London, Turing was raised in southern England.",
]

embeddings = ef.encode_documents(docs)

print("Embeddings:", embeddings)
# Print dimension and shape of embeddings
print("Dim:", ef.dim, embeddings[0].shape)

期待される出力は以下のようなものである:

Embeddings: [array([-3.09392996e-02, -1.80662833e-02,  1.34775648e-02,  2.77156215e-02,
      -4.86349640e-03, -3.12581174e-02, -3.55921760e-02,  5.76934684e-03,
       2.80773244e-03,  1.35783911e-01,  3.59678417e-02,  6.17732145e-02,
...
      -4.61330153e-02, -4.85207550e-02,  3.13997865e-02,  7.82178566e-02,
      -4.75336798e-02,  5.21207601e-02,  9.04406682e-02, -5.36676683e-02],
     dtype=float32)]
Dim: 384 (384,)

例2:BM25モデルを使った疎ベクトルの生成

BM25は、単語の出現頻度を用いてクエリと文書の関連性を決定するよく知られた手法です。この例では、BM25EmbeddingFunction を使って、クエリとドキュメントのスパース埋め込みを生成する方法を示します。

BM25では、文書のパターンを表すことができるIDF(逆文書出現頻度)を得るために、文書の統計量を計算することが重要です。IDFは、その単語が全文書で一般的か稀少か、どれだけの情報を提供するかを測定します。

from pymilvus.model.sparse import BM25EmbeddingFunction

# 1. Prepare a small corpus to search
docs = [
   "Artificial intelligence was founded as an academic discipline in 1956.",
   "Alan Turing was the first person to conduct substantial research in AI.",
   "Born in Maida Vale, London, Turing was raised in southern England.",
]
query = "Where was Turing born?"
bm25_ef = BM25EmbeddingFunction()

# 2. Fit the corpus to get BM25 model parameters on your documents.
bm25_ef.fit(docs)

# 3. Store the fitted parameters to expedite future processing.
bm25_ef.save("bm25_params.json")

# 4. Load the saved params
new_bm25_ef = BM25EmbeddingFunction()
new_bm25_ef.load("bm25_params.json")

docs_embeddings = new_bm25_ef.encode_documents(docs)
query_embeddings = new_bm25_ef.encode_queries([query])
print("Dim:", new_bm25_ef.dim, list(docs_embeddings)[0].shape)

例3:ReRankerを使う

検索システムは、最も関連性の高い結果を迅速かつ効率的に見つけることを目的としている。伝統的に、BM25やTF-IDFのような方法は、キーワードのマッチングに基づいて検索結果をランク付けするために使用されてきました。埋め込みベースのコサイン類似度のような最近の方法は簡単ですが、言語の微妙なニュアンスや、最も重要なことですが、文書とクエリの意図の相互作用を見逃すことがあります。

そこで役立つのが、リランカーである。リランカーは高度なAIモデルで、検索結果の初期セット(多くの場合、エンベッディング/トークン・ベースの検索で提供される)を受け取り、ユーザーの意図により近いものになるよう再評価する。表面的な用語のマッチングにとどまらず、検索クエリとドキュメントのコンテンツとのより深い相互作用を考慮する。

この例では、Jina AI Rerankerを使用する。

from pymilvus.model.reranker import JinaRerankFunction

jina_api_key = "<YOUR_JINA_API_KEY>"

rf = JinaRerankFunction("jina-reranker-v1-base-en", jina_api_key)

query = "What event in 1956 marked the official birth of artificial intelligence as a discipline?"

documents = [
   "In 1950, Alan Turing published his seminal paper, 'Computing Machinery and Intelligence,' proposing the Turing Test as a criterion of intelligence, a foundational concept in the philosophy and development of artificial intelligence.",
   "The Dartmouth Conference in 1956 is considered the birthplace of artificial intelligence as a field; here, John McCarthy and others coined the term 'artificial intelligence' and laid out its basic goals.",
   "In 1951, British mathematician and computer scientist Alan Turing also developed the first program designed to play chess, demonstrating an early example of AI in game strategy.",
   "The invention of the Logic Theorist by Allen Newell, Herbert A. Simon, and Cliff Shaw in 1955 marked the creation of the first true AI program, which was capable of solving logic problems, akin to proving mathematical theorems."
]

results = rf(query, documents)

for result in results:
   print(f"Index: {result.index}")
   print(f"Score: {result.score:.6f}")
   print(f"Text: {result.text}\n")

期待される出力は以下のようなものだ:

Index: 1
Score: 0.937096
Text: The Dartmouth Conference in 1956 is considered the birthplace of artificial intelligence as a field; here, John McCarthy and others coined the term 'artificial intelligence' and laid out its basic goals.

Index: 3
Score: 0.354210
Text: The invention of the Logic Theorist by Allen Newell, Herbert A. Simon, and Cliff Shaw in 1955 marked the creation of the first true AI program, which was capable of solving logic problems, akin to proving mathematical theorems.

Index: 0
Score: 0.349866
Text: In 1950, Alan Turing published his seminal paper, 'Computing Machinery and Intelligence,' proposing the Turing Test as a criterion of intelligence, a foundational concept in the philosophy and development of artificial intelligence.

Index: 2
Score: 0.272896
Text: In 1951, British mathematician and computer scientist Alan Turing also developed the first program designed to play chess, demonstrating an early example of AI in game strategy.

GitHubにスターをつけ、Discordに参加しよう!

このブログ記事が気に入ったら、MilvusをGitHubでスター登録してください!💙

Like the article? Spread the word

続けて読む