検索
ホームページテクノロジー周辺機器AIマルチモーダル RAG システムを構築する方法: CLIP と LLM を使用する

オープンソースの大規模言語マルチモーダルを使用して、検索拡張生成 (RAG) システムを構築する方法について説明します。私たちの焦点は、フレームワークの依存関係の追加を避けるために、LangChain や LLlama インデックスに依存せずにこれを達成することです。

マルチモーダル RAG システムを構築する方法: CLIP と LLM を使用する

RAGとは

人工知能の分野で、検索拡張世代の出現RAG テクノロジーの導入により、大規模言語モデル (Large Language Model) に革命的な改善がもたらされました。 RAG の本質は、モデルが外部ソースからリアルタイム情報を動的に取得できるようにすることで、人工知能の応答性を向上させることです。この技術の導入により、AIがユーザーのニーズによりきめ細かく対応できるようになります。外部ソースから情報を取得して融合することで、RAG はより正確で包括的な回答を生成し、より価値のあるコンテンツをユーザーに提供できます。この機能の向上により、インテリジェントな顧客サービス、インテリジェントな検索、知識の質問と回答システムなど、人工知能の応用分野に幅広い展望がもたらされました。 RAG の出現は、言語モデルのさらなる開発を示し、人工知能をもたらします

このアーキテクチャは、動的検索プロセスと生成機能をシームレスに組み合わせ、人工知能が常に変化する情報のさまざまな分野に適応できるようにします。 。微調整や再トレーニングとは異なり、RAG は、AI がモデル全体を変更せずに最新の関連情報を取得できる、コスト効率の高いソリューションを提供します。この機能の組み合わせにより、RAG は急速に変化する情報環境に対応する際の利点が得られます。

RAG の役割

1. 精度と信頼性の向上:

大きな言語でモデル (LLM) は信頼できる情報源を直接導き、その予測不可能性の問題を解決し、誤った情報や古い情報を提供するリスクを軽減し、応答の正確性と信頼性を高めます。

2. 透明性と信頼性の向上:

LLM のような生成 AI モデルは透明性に欠けていることが多く、人々が信頼することが困難になります。出力。 RAG は、より優れた制御を提供することで、バイアス、信頼性、コンプライアンスに関する懸念に対処します。

3. 幻覚を減らす:

LLM は幻覚反応を起こしやすく、一貫性はあるが不正確または捏造された情報を提供します。 RAG は、信頼できる情報源に依存して対応力を確保することで、主要部門への誤解を招くアドバイスのリスクを軽減します。

4. 費用対効果の高い適応性:

RAG は、大規模な再トレーニングや罰金を必要とせずに AI 出力を向上させる費用対効果の高い方法を提供します。 -チューニング。必要に応じて特定の詳細を動的に取得することで、情報を最新かつ関連性の高い状態に保つことができ、変化する情報に対する AI の適応性を確保します。

マルチモーダル モーダル モデル

マルチモーダルには、CLIP を例として、複数の入力があり、それらを 1 つの出力に結合することが含まれます。 CLIP はテキストと画像のペアであり、モデルは比較学習を通じてテキストと画像のペアの一致関係を学習できます。

このモデルは、同じものを表す異なる入力に対して同じ (非常に類似した) 埋め込みベクトルを生成します。

マルチモーダル RAG システムを構築する方法: CLIP と LLM を使用する


##マルチモード

マルチモーダル RAG システムを構築する方法: CLIP と LLM を使用する

マルチモーダル大規模言語

GPT4v と Gemini ビジョンは、さまざまなデータ型 (画像、テキスト、言語、音声など) を統合するマルチモーダル大規模言語を探索します。 モーダル言語モデル (MLLM)。 GPT-3、BERT、RoBERTa などの大規模言語モデル (LLM) はテキストベースのタスクではうまく機能しますが、他のデータ型の理解と処理では課題に直面しています。この制限に対処するために、マルチモーダル モデルはさまざまなモダリティを組み合わせて、さまざまなデータをより包括的に理解できるようにします。

マルチモーダル大規模言語モデル 従来のテキストベースの方法を超えています。 GPT-4 を例に挙げると、これらのモデルは、画像やテキストなどのさまざまなデータ タイプをシームレスに処理して、情報をより包括的に理解できます。

RAG と組み合わせる

ここでは、Clip を使用して画像とテキストを埋め込み、これらの埋め込みを ChromDB ベクター データベースに保存します。大規模なモデルは、取得された情報に基づいてユーザー チャット セッションに参加するために利用されます。

マルチモーダル RAG システムを構築する方法: CLIP と LLM を使用する


Kaggle の画像と Wikipedia の情報を使用して、花の専門家チャットボットを作成します

最初にソフトウェア パッケージをインストールします:

! pip install -q timm einops wikipedia chromadb open_clip_torch !pip install -q transformers==4.36.0 !pip install -q bitsandbytes==0.41.3 accelerate==0.25.0

データを前処理する手順は非常に簡単です。画像とテキストをフォルダーに置くだけです

マルチモーダル RAG システムを構築する方法: CLIP と LLM を使用する

可以随意使用任何矢量数据库,这里我们使用ChromaDB。

import chromadb  from chromadb.utils.embedding_functions import OpenCLIPEmbeddingFunction from chromadb.utils.data_loaders import ImageLoader from chromadb.config import Settings   client = chromadb.PersistentClient(path="DB")  embedding_function = OpenCLIPEmbeddingFunction() image_loader = ImageLoader() # must be if you reads from URIs

ChromaDB需要自定义嵌入函数

from chromadb import Documents, EmbeddingFunction, Embeddings  class MyEmbeddingFunction(EmbeddingFunction):def __call__(self, input: Documents) -> Embeddings:# embed the documents somehow or imagesreturn embeddings

这里将创建2个集合,一个用于文本,另一个用于图像

collection_images = client.create_collection(name='multimodal_collection_images', embedding_functinotallow=embedding_function, data_loader=image_loader)  collection_text = client.create_collection(name='multimodal_collection_text', embedding_functinotallow=embedding_function, )  # Get the Images IMAGE_FOLDER = '/kaggle/working/all_data'   image_uris = sorted([os.path.join(IMAGE_FOLDER, image_name) for image_name in os.listdir(IMAGE_FOLDER) if not image_name.endswith('.txt')]) ids = [str(i) for i in range(len(image_uris))]  collection_images.add(ids=ids, uris=image_uris) #now we have the images collection

对于Clip,我们可以像这样使用文本检索图像

from matplotlib import pyplot as plt  retrieved = collection_images.query(query_texts=["tulip"], include=['data'], n_results=3) for img in retrieved['data'][0]:plt.imshow(img)plt.axis("off")plt.show()

マルチモーダル RAG システムを構築する方法: CLIP と LLM を使用する

也可以使用图像检索相关的图像

マルチモーダル RAG システムを構築する方法: CLIP と LLM を使用する

文本集合如下所示

# now the text DB from chromadb.utils import embedding_functions default_ef = embedding_functions.DefaultEmbeddingFunction()  text_pth = sorted([os.path.join(IMAGE_FOLDER, image_name) for image_name in os.listdir(IMAGE_FOLDER) if image_name.endswith('.txt')])  list_of_text = [] for text in text_pth:with open(text, 'r') as f:text = f.read()list_of_text.append(text)  ids_txt_list = ['id'+str(i) for i in range(len(list_of_text))] ids_txt_list  collection_text.add(documents = list_of_text,ids =ids_txt_list )

然后使用上面的文本集合获取嵌入

results = collection_text.query(query_texts=["What is the bellflower?"],n_results=1 )  results

结果如下:

{'ids': [['id0']],'distances': [[0.6072186183744086]],'metadatas': [[None]],'embeddings': None,'documents': [['Campanula () is the type genus of the Campanulaceae family of flowering plants. Campanula are commonly known as bellflowers and take both their common and scientific names from the bell-shaped flowers—campanula is Latin for "little bell".\nThe genus includes over 500 species and several subspecies, distributed across the temperate and subtropical regions of the Northern Hemisphere, with centers of diversity in the Mediterranean region, Balkans, Caucasus and mountains of western Asia. The range also extends into mountains in tropical regions of Asia and Africa.\nThe species include annual, biennial and perennial plants, and vary in habit from dwarf arctic and alpine species under 5 cm high, to large temperate grassland and woodland species growing to 2 metres (6 ft 7 in) tall.']],'uris': None,'data': None}

或使用图片获取文本

query_image = '/kaggle/input/flowers/flowers/rose/00f6e89a2f949f8165d5222955a5a37d.jpg' raw_image = Image.open(query_image)  doc = collection_text.query(query_embeddings=embedding_function(query_image), n_results=1,  )['documents'][0][0]

マルチモーダル RAG システムを構築する方法: CLIP と LLM を使用する

上图的结果如下:

A rose is either a woody perennial flowering plant of the genus Rosa (), in the family Rosaceae (), or the flower it bears. There are over three hundred species and tens of thousands of cultivars. They form a group of plants that can be erect shrubs, climbing, or trailing, with stems that are often armed with sharp prickles. Their flowers vary in size and shape and are usually large and showy, in colours ranging from white through yellows and reds. Most species are native to Asia, with smaller numbers native to Europe, North America, and northwestern Africa. Species, cultivars and hybrids are all widely grown for their beauty and often are fragrant. Roses have acquired cultural significance in many societies. Rose plants range in size from compact, miniature roses, to climbers that can reach seven meters in height. Different species hybridize easily, and this has been used in the development of the wide range of garden roses.

这样我们就完成了文本和图像的匹配工作,其实这里都是CLIP的工作,下面我们开始加入LLM。

from huggingface_hub import hf_hub_download  hf_hub_download(repo_, filename="configuration_llava.py", local_dir="./", force_download=True) hf_hub_download(repo_, filename="configuration_phi.py", local_dir="./", force_download=True) hf_hub_download(repo_, filename="modeling_llava.py", local_dir="./", force_download=True) hf_hub_download(repo_, filename="modeling_phi.py", local_dir="./", force_download=True) hf_hub_download(repo_, filename="processing_llava.py", local_dir="./", force_download=True)

我们是用visheratin/LLaVA-3b

from modeling_llava import LlavaForConditionalGeneration import torch  model = LlavaForConditionalGeneration.from_pretrained("visheratin/LLaVA-3b") model = model.to("cuda")

加载tokenizer

from transformers import AutoTokenizer  tokenizer = AutoTokenizer.from_pretrained("visheratin/LLaVA-3b")

然后定义处理器,方便我们以后调用

from processing_llava import LlavaProcessor, OpenCLIPImageProcessor  image_processor = OpenCLIPImageProcessor(model.config.preprocess_config) processor = LlavaProcessor(image_processor, tokenizer)

下面就可以直接使用了

question = 'Answer with organized answers: What type of rose is in the picture? Mention some of its characteristics and how to take care of it ?'  query_image = '/kaggle/input/flowers/flowers/rose/00f6e89a2f949f8165d5222955a5a37d.jpg' raw_image = Image.open(query_image)  doc = collection_text.query(query_embeddings=embedding_function(query_image), n_results=1,  )['documents'][0][0]  plt.imshow(raw_image) plt.show() imgs = collection_images.query(query_uris=query_image, include=['data'], n_results=3) for img in imgs['data'][0][1:]:plt.imshow(img)plt.axis("off")plt.show()

得到的结果如下:

マルチモーダル RAG システムを構築する方法: CLIP と LLM を使用する

结果还包含了我们需要的大部分信息

マルチモーダル RAG システムを構築する方法: CLIP と LLM を使用する

这样我们整合就完成了,最后就是创建聊天模板,

prompt = """system A chat between a curious human and an artificial intelligence assistant. The assistant is an exprt in flowers , and gives helpful, detailed, and polite answers to the human's questions. The assistant does not hallucinate and pays very close attention to the details. user <image> {question} Use the following article as an answer source. Do not write outside its scope unless you find your answer better {article} if you thin your answer is better add it after document. assistant """.format(questinotallow='question', article=doc)</image>

如何创建聊天过程我们这里就不详细介绍了,完整代码在这里:

https://www.php.cn/link/71eee742e4c6e094e6af364597af3f05

以上がマルチモーダル RAG システムを構築する方法: CLIP と LLM を使用するの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明
この記事は51CTO.COMで複製されています。侵害がある場合は、admin@php.cn までご連絡ください。
ほとんどが使用されています10 Power BIチャート - 分析Vidhyaほとんどが使用されています10 Power BIチャート - 分析VidhyaApr 16, 2025 pm 12:05 PM

Microsoft PowerBIチャートでデータ視覚化の力を活用する 今日のデータ駆動型の世界では、複雑な情報を非技術的な視聴者に効果的に伝えることが重要です。 データの視覚化は、このギャップを橋渡しし、生データを変換するi

AIのエキスパートシステムAIのエキスパートシステムApr 16, 2025 pm 12:00 PM

エキスパートシステム:AIの意思決定力に深く飛び込みます 医療診断から財務計画まで、あらゆることに関する専門家のアドバイスにアクセスできることを想像してください。 それが人工知能の専門家システムの力です。 これらのシステムはプロを模倣します

3人の最高の雰囲気コーダーがこのAI革命をコードで分解する3人の最高の雰囲気コーダーがこのAI革命をコードで分解するApr 16, 2025 am 11:58 AM

まず第一に、これがすぐに起こっていることは明らかです。さまざまな企業が、現在AIによって書かれているコードの割合について話しており、これらは迅速なクリップで増加しています。すでに多くの仕事の移動があります

滑走路AIのGen-4:AIモンタージュはどのように不条理を超えることができますか滑走路AIのGen-4:AIモンタージュはどのように不条理を超えることができますかApr 16, 2025 am 11:45 AM

映画業界は、デジタルマーケティングからソーシャルメディアまで、すべてのクリエイティブセクターとともに、技術的な岐路に立っています。人工知能が視覚的なストーリーテリングのあらゆる側面を再構築し始め、エンターテイメントの風景を変え始めたとき

5日間のISRO AI無料コースを登録する方法は? - 分析Vidhya5日間のISRO AI無料コースを登録する方法は? - 分析VidhyaApr 16, 2025 am 11:43 AM

ISROの無料AI/MLオンラインコース:地理空間技術の革新へのゲートウェイ インド宇宙研究機関(ISRO)は、インドのリモートセンシング研究所(IIRS)を通じて、学生と専門家に素晴らしい機会を提供しています。

AIのローカル検索アルゴリズムAIのローカル検索アルゴリズムApr 16, 2025 am 11:40 AM

ローカル検索アルゴリズム:包括的なガイド 大規模なイベントを計画するには、効率的なワークロード分布が必要です。 従来のアプローチが失敗すると、ローカル検索アルゴリズムは強力なソリューションを提供します。 この記事では、Hill ClimbingとSimulについて説明します

OpenaiはGPT-4.1でフォーカスをシフトし、コーディングとコスト効率を優先しますOpenaiはGPT-4.1でフォーカスをシフトし、コーディングとコスト効率を優先しますApr 16, 2025 am 11:37 AM

このリリースには、GPT-4.1、GPT-4.1 MINI、およびGPT-4.1 NANOの3つの異なるモデルが含まれており、大規模な言語モデルのランドスケープ内のタスク固有の最適化への動きを示しています。これらのモデルは、ようなユーザー向けインターフェイスをすぐに置き換えません

プロンプト:ChatGptは偽のパスポートを生成しますプロンプト:ChatGptは偽のパスポートを生成しますApr 16, 2025 am 11:35 AM

Chip Giant Nvidiaは、月曜日に、AI Supercomputersの製造を開始すると述べました。これは、大量のデータを処理して複雑なアルゴリズムを実行できるマシンを初めて初めて米国内で実行します。発表は、トランプSI大統領の後に行われます

See all articles

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

AI Hentai Generator

AI Hentai Generator

AIヘンタイを無料で生成します。

ホットツール

VSCode Windows 64 ビットのダウンロード

VSCode Windows 64 ビットのダウンロード

Microsoft によって発売された無料で強力な IDE エディター

DVWA

DVWA

Damn Vulnerable Web App (DVWA) は、非常に脆弱な PHP/MySQL Web アプリケーションです。その主な目的は、セキュリティ専門家が法的環境でスキルとツールをテストするのに役立ち、Web 開発者が Web アプリケーションを保護するプロセスをより深く理解できるようにし、教師/生徒が教室環境で Web アプリケーションを教え/学習できるようにすることです。安全。 DVWA の目標は、シンプルでわかりやすいインターフェイスを通じて、さまざまな難易度で最も一般的な Web 脆弱性のいくつかを実践することです。このソフトウェアは、

SublimeText3 Linux 新バージョン

SublimeText3 Linux 新バージョン

SublimeText3 Linux 最新バージョン

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

MantisBT

MantisBT

Mantis は、製品の欠陥追跡を支援するために設計された、導入が簡単な Web ベースの欠陥追跡ツールです。 PHP、MySQL、Web サーバーが必要です。デモおよびホスティング サービスをチェックしてください。