LangChain-22 Text Embedding 续接21节 文本切分后 对文本进行embedding向量化处理 后续可保存到向量数据库后进行检索 从而扩展大模型的能力 原创

请添加图片描述

背景描述

介绍Embedding

Text Embedding在大模型中的应用是一个重要的技术,它涉及到将高维度的数据(如文本)映射到低维度空间的过程。这一过程不仅有助于减少数据处理的复杂性,还能够捕捉和表达数据的语义信息。在自然语言处理(NLP)和机器学习领域,Text Embedding是实现文本分类、情感分析、机器翻译等任务的基础。

工作原理

Text Embedding的核心思想是将文本中的单词或短语转换为实数向量。这些向量在高维空间中的距离和方向能够反映出单词或短语之间的语义关系。例如,语义相近的单词在向量空间中的位置也相近。这种表示方法使得机器能够理解和处理自然语言数据。

安装依赖

pip install -qU langchain-core langchain-openai

编写代码

from langchain_openai import OpenAIEmbeddings


embeddings_model = OpenAIEmbeddings()

embeddings = embeddings_model.embed_documents(
    [
        "Hi there!",
        "Oh, hello!",
        "What's your name?",
        "My friends call me World",
        "Hello World!"
    ]
)
print(len(embeddings))
print(len(embeddings[0]))

embedded_query = embeddings_model.embed_query("What was the name mentioned in the conversation?")
print(embedded_query[:5])

运行结果

➜ python3 test22.py
5
1536
[0.005339288459123527, -0.0004900397315547535, 0.03888638540715689, -0.0029435385310610336, -0.00899561173676785]

在这里插入图片描述

存储至FAISS

安装FAISS

pip install --upgrade --quiet  langchain-openai faiss-cpu

编写代码

from langchain_openai import OpenAIEmbeddings
from langchain.storage import LocalFileStore
from langchain_community.document_loaders import TextLoader
from langchain_community.vectorstores import FAISS
from langchain_text_splitters import CharacterTextSplitter


underlying_embeddings = OpenAIEmbeddings()
store = LocalFileStore("./cache/")
cached_embedder = CacheBackedEmbeddings.from_bytes_store(
    underlying_embeddings, store, namespace=underlying_embeddings.model
)
print(list(store.yield_keys()))

raw_documents = TextLoader("./state_of_the_union.txt").load()
text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
documents = text_splitter.split_documents(raw_documents)

db = FAISS.from_documents(documents, cached_embedder)
print(list(store.yield_keys())[:5])

posted @   武子康  阅读(0)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示