3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【RAG入門・Python実装】第3回

3
Posted at

【RAG入門・Python実装】第3回 RAGとは何か?仕組みを図解でやさしく解説 パート2

前回の復習

スクリーンショット 2025-09-04 085329.png
前回で①、②を説明した。
②で何をしていたか覚えているだろうか?
②ではユーザーの質問はベクトル化され、DBに検索をかけている。
ベクトル化されると、以下のようになる。詳しくは前回の記事を見てほしい。
出力結果

テキスト1のEmbedding(最初の5要素): [-0.40521955490112305, 0.2711377739906311, -0.010199081152677536, 0.2498672902584076, -0.4358774721622467]
テキスト2のEmbedding(最初の5要素): [0.31985199451446533, 0.07074873149394989, 0.5577247142791748, 0.43831667304039, -0.5286954641342163]
テキスト3のEmbedding(最初の5要素): [0.5985070466995239, -0.20873668789863586, -0.19458788633346558, 0.21659620106220245, 0.06730994582176208]

DBでの類似度の検索方法

②と③の間ではDBにある情報もベクトル化しておき、
ベクトル化されたユーザーの質問と比較する。ベクトル空間で「どれだけ近いか(類似度)」を比較することで関連する文章を探す。
この比較する時に使われるのがコサイン類似度です。

コサイン類似度

二つの指すベクトルがどれだけ似ているかを示す指標である。ベクトルの大きさに影響をされず、類似性のみで評価する。これは-1~1の間で評価する。

  • 1(2つのベクトルのなす角が0度)に近い:ベクトルが同じ向き(似ている)
  • 0(2つのベクトルのなす角が90度)に近い:ベクトルが直交(無関係)
  • -1(2つのベクトルのなす角が180度)に近い:ベクトルが逆向き(正反対)

実際にコードでコサイン類似度を実行

import ollama
import numpy as np

EMBED_MODEL = "nomic-embed-text" 

def get_embedding(text, model="nomic-embed-text"):
    try:
        response = ollama.embeddings(model=model, prompt=text)
        return response["embedding"]
    except Exception as e:
        print(f"Ollama Embedding API呼び出し中にエラーが発生しました: {e}")
        return None
    
text1 = "Pythonは汎用プログラミング言語です"   
text2 = "JavaScriptはウェブ開発によく使われるスクリプト言語です"
text3 = "機械学習にはPythonがよく利用されます" 

embedding1 = get_embedding(text1)
embedding2 = get_embedding(text2)
embedding3 = get_embedding(text3)

if embedding1 and embedding2 and embedding3:
    print(f"テキスト1のEmbedd0ingの次元数: {len(embedding1)}")
    print(f"テキスト2のEmbedd0ingの次元数: {len(embedding2)}")
    print(f"テキスト3のEmbedd0ingの次元数: {len(embedding3)}")

    print(f"テキスト1のEmbedding(最初の5要素): {embedding1[:5]}")
    print(f"テキスト2のEmbedding(最初の5要素): {embedding2[:5]}")
    print(f"テキスト3のEmbedding(最初の5要素): {embedding3[:5]}")

embedding1 = np.array(embedding1)
embedding2 = np.array(embedding2)
embedding3 = np.array(embedding3)

cosine_similarity1 = np.dot(embedding1, embedding3) / (np.linalg.norm(embedding1) * np.linalg.norm(embedding3))  
cosine_similarity2 = np.dot(embedding1, embedding2) / (np.linalg.norm(embedding1) * np.linalg.norm(embedding2))    
cosine_similarity3 = np.dot(embedding2, embedding3) / (np.linalg.norm(embedding2) * np.linalg.norm(embedding3))

print(f"テキスト1とテキスト3のコサイン類似度: {cosine_similarity1:.4f}")
print(f"テキスト1とテキスト3のコサイン類似度: {cosine_similarity2:.4f}")
print(f"テキスト2とテキスト3のコサイン類似度: {cosine_similarity3:.4f}")

出力結果

テキスト1のEmbedd0ingの次元数: 768
テキスト2のEmbedd0ingの次元数: 768
テキスト3のEmbedd0ingの次元数: 768
テキスト1のEmbedding(最初の5要素): [0.0860874131321907, 1.3446776866912842, -2.727231025695801, -1.229341745376587, 0.20239733159542084]
テキスト2のEmbedding(最初の5要素): [-0.2803836464881897, 0.38521626591682434, -2.932075262069702, -0.7829883098602295, -0.3412156105041504]
テキスト3のEmbedding(最初の5要素): [0.22783248126506805, 1.15288245677948, -2.971783399581909, -1.4897303581237793, 0.8548974990844727]
テキスト1とテキスト3のコサイン類似度: 0.7786
テキスト1とテキスト3のコサイン類似度: 0.7060
テキスト2とテキスト3のコサイン類似度: 0.6706

コード解説

EMBED_MODEL = "nomic-embed-text" 

これは埋め込みモデルを指定している。
ベクトル化するために"nomic-embed-text" というモデルを使用するという意味

埋め込みモデルの種類(例)

  • nomic-embed-text:軽量・高速なテキスト埋め込みモデル
  • mxbai-embed-large:高精度な埋め込みを生成できる大規模モデル
  • OpenAIの text-embedding-3-large:業界標準的に使われる高性能モデル
cosine_similarity1 = np.dot(embedding1, embedding3) / (np.linalg.norm(embedding1) * np.linalg.norm(embedding3))  
cosine_similarity2 = np.dot(embedding1, embedding2) / (np.linalg.norm(embedding1) * np.linalg.norm(embedding2))    
cosine_similarity3 = np.dot(embedding2, embedding3) / (np.linalg.norm(embedding2) * np.linalg.norm(embedding3))

ここは公式に基づいてコサイン類似度を計算している。
unicos_002.jpg

まとめ

ユーザーの質問はDBの情報とコサイン類似度による比較により、検索をかけて関連性の
高い文章を返却していることが分かった。

👉次回は図の④と➄について解説する。

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?