使用CLIP和LLM构建多模态RAG系统

这篇具有很好参考价值的文章主要介绍了使用CLIP和LLM构建多模态RAG系统。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

在本文中我们将探讨使用开源大型语言多模态模型(Large Language Multi-Modal)构建检索增强生成(RAG)系统。本文的重点是在不依赖LangChain或LLlama index的情况下实现这一目标,这样可以避免更多的框架依赖。

什么是RAG

在人工智能领域,检索增强生成(retrieve - augmented Generation, RAG)作为一种变革性技术改进了大型语言模型(Large Language Models)的能力。从本质上讲,RAG通过允许模型从外部源动态检索实时信息来增强AI响应的特异性。

该体系结构将生成能力与动态检索过程无缝结合,使人工智能能够适应不同领域中不断变化的信息。与微调和再训练不同,RAG提供了一种经济高效的解决方案,允许人工智能在不改变整个模型的情况下能够得到最新和相关的信息。

RAG的作用

1、提高准确性和可靠性:

通过将大型语言模型(llm)重定向到权威的知识来源来解决它们的不可预测性。降低了提供虚假或过时信息的风险,确保更准确和可靠的反应。

2、增加透明度和信任:

像LLM这样的生成式人工智能模型往往缺乏透明度,这使得人们很难相信它们的输出。RAG通过允许组织对生成的文本输出有更大的控制,解决了对偏差、可靠性和遵从性的关注。

3、减轻幻觉:

LLM容易产生幻觉反应——连贯但不准确或捏造的信息。RAG通过确保响应以权威来源为基础,减少关键部门误导性建议的风险。

4、具有成本效益的适应性:

RAG提供了一种经济有效的方法来提高AI输出,而不需要广泛的再训练/微调。可以通过根据需要动态获取特定细节来保持最新和相关的信息,确保人工智能对不断变化的信息的适应性。

多模式模态模型

多模态涉及有多个输入,并将其结合成单个输出,以CLIP为例:CLIP的训练数据是文本-图像对,通过对比学习,模型能够学习到文本-图像对的匹配关系。

该模型为表示相同事物的不同输入生成相同(非常相似)的嵌入向量。

使用CLIP和LLM构建多模态RAG系统,机器学习,深度学习,人工智能,RAG,大语言模型,CLIP

多模

态大型语言(multi-modal large language)

GPT4v和Gemini vision就是探索集成了各种数据类型(包括图像、文本、语言、音频等)的多模态语言模型(MLLM)。虽然像GPT-3、BERT和RoBERTa这样的大型语言模型(llm)在基于文本的任务中表现出色,但它们在理解和处理其他数据类型方面面临挑战。为了解决这一限制,多模态模型结合了不同的模态,从而能够更全面地理解不同的数据。

多模态大语言模型它超越了传统的基于文本的方法。以GPT-4为例,这些模型可以无缝地处理各种数据类型,包括图像和文本,从而更全面地理解信息。

与RAG相结合

这里我们将使用Clip嵌入图像和文本,将这些嵌入存储在ChromDB矢量数据库中。然后将利用大模型根据检索到的信息参与用户聊天会话。

使用CLIP和LLM构建多模态RAG系统,机器学习,深度学习,人工智能,RAG,大语言模型,CLIP

我们将使用来自Kaggle的图片和维基百科的信息来创建一个花卉专家聊天机器人

首先我们安装软件包:

 ! 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

预处理数据的步骤很简单只是把图像和文本放在一个文件夹里

使用CLIP和LLM构建多模态RAG系统,机器学习,深度学习,人工智能,RAG,大语言模型,CLIP

可以随意使用任何矢量数据库,这里我们使用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 images
         return embeddings

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

 collection_images = client.create_collection(
     name='multimodal_collection_images', 
     embedding_function=embedding_function, 
     data_loader=image_loader)
 
 collection_text = client.create_collection(
     name='multimodal_collection_text', 
     embedding_function=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()

使用CLIP和LLM构建多模态RAG系统,机器学习,深度学习,人工智能,RAG,大语言模型,CLIP

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

使用CLIP和LLM构建多模态RAG系统,机器学习,深度学习,人工智能,RAG,大语言模型,CLIP

文本集合如下所示

 # 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]

使用CLIP和LLM构建多模态RAG系统,机器学习,深度学习,人工智能,RAG,大语言模型,CLIP

上图的结果如下:

 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_id="visheratin/LLaVA-3b", filename="configuration_llava.py", local_dir="./", force_download=True)
 hf_hub_download(repo_id="visheratin/LLaVA-3b", filename="configuration_phi.py", local_dir="./", force_download=True)
 hf_hub_download(repo_id="visheratin/LLaVA-3b", filename="modeling_llava.py", local_dir="./", force_download=True)
 hf_hub_download(repo_id="visheratin/LLaVA-3b", filename="modeling_phi.py", local_dir="./", force_download=True)
 hf_hub_download(repo_id="visheratin/LLaVA-3b", 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()

得到的结果如下:

使用CLIP和LLM构建多模态RAG系统,机器学习,深度学习,人工智能,RAG,大语言模型,CLIP

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

使用CLIP和LLM构建多模态RAG系统,机器学习,深度学习,人工智能,RAG,大语言模型,CLIP

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

 prompt = """<|im_start|>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.<|im_end|>
 <|im_start|>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.<|im_end|>
 <|im_start|>assistant
 """.format(question='question', article=doc)

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

https://avoid.overfit.cn/post/c2d8059cc5c145a48acb5ecb8890dc0e

作者:Ahmed Haytham文章来源地址https://www.toymoban.com/news/detail-782900.html

到了这里,关于使用CLIP和LLM构建多模态RAG系统的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 机器学习笔记 - 什么是多模态深度学习?

            人类使用五种感官来体验和解释周围的世界。我们的五种感官从五种不同的来源和五种不同的方式捕获信息。模态是指某事发生、经历或捕捉的方式。         人工智能正在寻求模仿人类大脑,终究是跳不出这具躯壳的限制。         人脑由可以同时处理

    2024年02月09日
    浏览(33)
  • LLM之RAG实战(二十七)| 如何评估RAG系统

           有没有想过今天的一些应用程序是如何看起来几乎神奇地智能的?这种魔力很大一部分来自于一种叫做RAG和LLM的东西。把RAG(Retrieval Augmented Generation)想象成人工智能世界里聪明的书呆子,它会挖掘大量信息,准确地找到你的问题所需要的信息。然后,还有LLM(大型

    2024年02月22日
    浏览(28)
  • 多模态模型学习1——CLIP对比学习 语言-图像预训练模型

    学了一些多模态的知识,CLIP算是其中最重要也是最通用的一环,一起来看一下吧。 CLIP的全称是Contrastive Language-Image Pre-Training,中文是对比语言-图像预训练,是一个预训练模型,简称为CLIP。 该模型是 OpenAI 在 2021 年发布的,最初用于匹配图像和文本的预训练神经网络模型,

    2023年04月13日
    浏览(47)
  • RAG实战 7 - 使用llama_index实现多模态RAG

    转载自:LLM之RAG实战(七)| 使用llama_index实现多模态RAG https://mp.weixin.qq.com/s/FVF09cEO5nUipcL9R8ydXQ OpenAI开发日上最令人兴奋的发布之一是GPT-4V API(https://platform.openai.com/docs/guides/vision)的发布。GPT-4V是一个多模态模型,可以接收文本/图像,并可以输出文本响应。最近还有一些其他

    2024年01月17日
    浏览(32)
  • 机器学习30:《推荐系统-III》使用 TensorFlow 构建电影推荐系统

    本文将介绍基于 MovieLens 数据集创建一个电影推荐系统的方法。具体而言,包括探索电影数据,训练矩阵分解模型,检查嵌入,矩阵分解中的正则化,Softmax 模型训练等内容。 目录 1.准备工作 1.1 导入依赖模块 1.2 加载数据 1.3 探索电影镜头数据

    2024年02月16日
    浏览(37)
  • 机器学习笔记 - 使用CLIP在没有数据的情况下创建图像分类器

            想象一下,如果我们现在需要对人们是否戴眼镜进行分类,但您没有数据或资源来训练自定义模型。该怎么办?这里我们了解如何使用预先训练的 CLIP 模型来创建自定义分类器,而无需任何培训。这种方法称为 零样本 图像分类,它可以对原始 CLIP 模型训练期间未

    2024年02月14日
    浏览(28)
  • 使用大型语言模(LLM)构建系统(七):评估1

    今天我学习了DeepLearning.AI的 Building Systems with LLM 的在线课程,我想和大家一起分享一下该门课程的一些主要内容。之前我们已经学习了下面这些知识: 使用大型语言模(LLM)构建系统(一):分类 使用大型语言模(LLM)构建系统(二):内容审核、预防Prompt注入 使用大型语言模(LLM)构建

    2024年02月11日
    浏览(40)
  • 翻译: LLM构建 GitHub 提交记录的聊天机器人二 使用 Timescale Vector、pgvector 和 LlamaIndex

    接着上篇内容:翻译: LLM构建 GitHub 提交记录的聊天机器人一 使用 Timescale Vector、pgvector 和 LlamaIndex TSV Time Machine 示例应用有三个页面: Home主页:提供应用程序使用说明的应用程序主页。 Load Data加载数据:页面以加载所选存储库的 Git 提交历史记录。 Time Machine Demo:与加载的

    2024年01月20日
    浏览(54)
  • 【多模态】17、CORA | 将 CLIP 使用到开集目标检测

    论文:CORA: Adapting CLIP for Open-Vocabulary Detection with Region Prompting and Anchor Pre-Matching 代码:https://github.com/tgxs002/CORA 出处:CVPR2023 开集目标检测(Open-vocabulary detection,OVD)最近得到了很大的关注,CLIP 的出现让开集目标检测有了新的解决方式 CLIP 是学习图像和文本之间的关系来进

    2024年02月16日
    浏览(31)
  • 【多模态】3、CLIP | OpenAI 出品使用 4 亿样本训练的图文匹配模型

    论文:Learning Transferable Visual Models From Natural Language Supervision 代码:https://github.com/OpenAI/CLIP 官网:https://openai.com/research/clip 出处:OpenAI 时间:2021.02 贡献: 基于图文匹配,不受限于分类类别,有很强的扩展性!!!这是 CLIP 最炸裂的地方,彻底摆脱了预定义标签列表了 不仅仅

    2024年02月15日
    浏览(40)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包