返回顶部
热门问答 更多热门问答
技术文章 更多技术文章

改进向量搜索-使用PostgresML和LlamaIndex重新排名

[复制链接]
链载Ai 显示全部楼层 发表于 昨天 10:50 |阅读模式 打印 上一主题 下一主题

搜索和重新排名:提高结果相关性

搜索系统通常采用两种主要方法:关键字和语义。关键字搜索将精确的查询词与索引数据库内容匹配,而语义搜索使用 NLP 和机器学习来理解查询上下文和意图。许多有效的系统结合了这两种方法以获得最佳结果。

初始检索后,重新排序可以进一步提高结果相关性。传统的重新排序依赖于历史用户交互数据,但这种方法难以处理新内容,并且需要大量数据才能有效训练。一种先进的替代方法是使用交叉编码器,它直接比较查询结果对的相似性。

交叉编码器直接比较两段文本并计算相似度得分。与传统的语义搜索方法不同,我们无法预先计算交叉编码器的嵌入并在以后重复使用它们。相反,我们必须对每一对想要比较的文本运行交叉编码器,这使得这种方法在计算上非常昂贵,并且不适用于大规模搜索。但是,它对于重新排序我们数据集的子集非常有效,因为它擅长评估新的、未见过的数据,而无需大量用户交互数据进行微调。

交叉编码器弥补了传统重排序系统在深度文本分析方面的局限性,尤其是针对新颖或高度特定内容。它们不依赖大量用户交互数据集进行训练(尽管此类数据仍然很有用),并且擅长处理新数据和以前从未见过的数据。这使得交叉编码器成为在重排序环境中增强搜索结果相关性的绝佳选择。

实施重新排名

我们将使用 LlamaIndex 和 PostgresML 托管索引实现一个简单的重新排名示例。有关 PostgresML 托管索引的更多信息。查看我们关于 LlamaIndex 的公告:使用 LlamaIndex + PostgresML 简化您的 RAG 应用程序架构 。

安装所需的依赖项以开始使用:

pipinstallllama_indexllama-index-indices-managed-postgresml

我们将使用 Paul Graham 数据集,可以通过 curl 下载:

mkdirdata

curl-odata/paul_graham_essay.txthttps://raw.githubusercontent.com/run-llama/llama_index/main/docs/docs/examples/data/paul_graham/paul_graham_essay.txt

PostgresML 托管索引将处理存储、拆分、嵌入和查询我们的文档。我们需要的只是一个数据库连接字符串。如果您还没有, 请创建您的 PostgresML 帐户 。完成您的个人资料后,您将获得 100 美元的免费积分。

设置 PGML_DATABASE_URL 环境变量:

exportPGML_DATABASE_URL="{YOUR_CONNCECTION_STRING}"

让我们创建索引:

fromllama_index.core.readersimportSimpleDirectoryReader
fromllama_index.indices.managed.postgresmlimportPostgresMLIndex


documents=SimpleDirectoryReader("data").load_data()
index=PostgresMLIndex.from_documents(
documents,collection_name="llama-index-rerank-example"
)

请注意,collection_name 用于唯一标识您正在使用的索引。

这里我们使用 SimpleDirectoryReader 来加载文档,然后从这些文档构造 PostgresMLIndex。

此工作流程不需要文档预处理。相反,文档会直接发送到 PostgresML,并根据管道规范进行存储、拆分和嵌入。这是使用 PostgresML 托管索引的独特品质。

现在让我们搜索一下!我们可以执行语义搜索,并通过从索引中创建检索器来获取前 2 个结果。

retriever=index.as_retriever(limit=2)
docs=retriever.retrieve("Whatdidtheauthordoasachild?")
fordocindocs:
print("---------")
print(f"Id:{doc.id_}")
print(f"Score:{doc.score}")
print(f"Text:{doc.text}")

这样做我们得到:

---------

Id:de01b7e1-95f8-4aa0-b4ec-45ef64816e0e

Score:0.7793415653313153

Text:Wow,Ithought,there'sanaudience.IfIwritesomethingandputitontheweb,anyonecanreadit.Thatmayseemobviousnow,butitwassurprisingthen.Intheprinteratherewasanarrowchanneltoreaders,guardedbyfiercemonstersknownaseditors.Theonlywaytogetanaudienceforanythingyouwrotewastogetitpublishedasabook,orinanewspaperormagazine.Nowanyonecouldpublishanything.



Thishadbeenpossibleinprinciplesince1993,butnotmanypeoplehadrealizedityet.Ihadbeenintimatelyinvolvedwithbuildingtheinfrastructureofthewebformostofthattime,andawriteraswell,andithadtakenme8yearstorealizeit.Eventhenittookmeseveralyearstounderstandtheimplications.Itmeanttherewouldbeawholenewgenerationofessays.[11]



Intheprintera,thechannelforpublishingessayshadbeenvanishinglysmall.ExceptforafewofficiallyanointedthinkerswhowenttotherightpartiesinNewYork,theonlypeopleallowedtopublishessayswerespecialistswritingabouttheirspecialties.Thereweresomanyessaysthathadneverbeenwritten,becausetherehadbeennowaytopublishthem.Nowtheycouldbe,andIwasgoingtowritethem.[12]



I'veworkedonseveraldifferentthings,buttotheextenttherewasaturningpointwhereIfiguredoutwhattoworkon,itwaswhenIstartedpublishingessaysonline.FromthenonIknewthatwhateverelseIdid,I'dalwayswriteessaystoo.



---------

Id:de01b7e1-95f8-4aa0-b4ec-45ef64816e0e

Score:0.7770352826735559

Text:AsterixcomicsbeginbyzoominginonatinycornerofRomanGaulthatturnsoutnottobecontrolledbytheRomans.YoucandosomethingsimilaronamapofNewYorkCity:ifyouzoominontheUpperEastSide,there'satinycornerthat'snotrich,oratleastwasn'tin1993.It'scalledYorkville,andthatwasmynewhome.NowIwasaNewYorkartist—inthestrictlytechnicalsenseofmakingpaintingsandlivinginNewYork.



Iwasnervousaboutmoney,becauseIcouldsensethatInterleafwasonthewaydown.FreelanceLisphackingworkwasveryrare,andIdidn'twanttohavetoprograminanotherlanguage,whichinthosedayswouldhavemeantC++ifIwaslucky.Sowithmyunerringnoseforfinancialopportunity,IdecidedtowriteanotherbookonLisp.Thiswouldbeapopularbook,thesortofbookthatcouldbeusedasatextbook.Iimaginedmyselflivingfrugallyofftheroyaltiesandspendingallmytimepainting.(Thepaintingonthecoverofthisbook,ANSICommonLisp,isonethatIpaintedaroundthistime.)



ThebestthingaboutNewYorkformewasthepresenceofIdelleandJulianWeber.IdelleWeberwasapainter,oneoftheearlyphotorealists,andI'dtakenherpaintingclassatHarvard.I'veneverknownateachermorebelovedbyherstudents.Largenumbersofformerstudentskeptintouchwithher,includingme.AfterImovedtoNewYorkIbecameherdefactostudioassistant.

这些结果还不错,但并不完美。让我们尝试使用交叉编码器进行重新排序。

retriever=index.as_retriever(
limit=2,
rerank={
"model":"mixedbread-ai/mxbai-rerank-base-v1",
"num_documents_to_rerank":100
}
)
docs=retriever.retrieve("Whatdidtheauthordoasachild?")
fordocindocs:
print("---------")
print(f"Id:{doc.id_}")
print(f"Score:{doc.score}")
print(f"Text:{doc.text}")

在这里,我们将检索器配置为返回排名前两个的文档,但这次,我们添加了一个重新排名参数以使用mixedbread-ai/mxbai-rerank-base-v1模型。这意味着我们的初始语义搜索将返回 100 个结果,然后由mixedbread-ai/mxbai-rerank-base-v1模型对这些结果进行重新排名,并且仅显示排名前两个的结果。

运行此输出:

Id:de01b7e1-95f8-4aa0-b4ec-45ef64816e0e
Score:0.17803585529327393
Text:WhatIWorkedOn

February2021

BeforecollegethetwomainthingsIworkedon,outsideofschool,werewritingandprogramming.Ididn'twriteessays.Iwrotewhatbeginningwritersweresupposedtowritethen,andprobablystillare:shortstories.Mystorieswereawful.Theyhadhardlyanyplot,justcharacterswithstrongfeelings,whichIimaginedmadethemdeep.

ThefirstprogramsItriedwritingwereontheIBM1401thatourschooldistrictusedforwhatwasthencalled"dataprocessing."Thiswasin9thgrade,soIwas13or14.Theschooldistrict's1401happenedtobeinthebasementofourjuniorhighschool,andmyfriendRichDravesandIgotpermissiontouseit.ItwaslikeaminiBondvillain'slairdownthere,withallthesealien-lookingmachines—CPU,diskdrives,printer,cardreader—sittinguponaraisedfloorunderbrightfluorescentlights.

ThelanguageweusedwasanearlyversionofFortran.Youhadtotypeprogramsonpunchcards,thenstacktheminthecardreaderandpressabuttontoloadtheprogramintomemoryandrunit.Theresultwouldordinarilybetoprintsomethingonthespectacularlyloudprinter.


---------
Id:de01b7e1-95f8-4aa0-b4ec-45ef64816e0e
Score:0.1057136133313179
Text:Iwantednotjusttobuildthings,buttobuildthingsthatwouldlast.

InthisdissatisfiedstateIwentin1988tovisitRichDravesatCMU,wherehewasingradschool.OnedayIwenttovisittheCarnegieInstitute,whereI'dspentalotoftimeasakid.WhilelookingatapaintingthereIrealizedsomethingthatmightseemobvious,butwasabigsurprisetome.There,rightonthewall,wassomethingyoucouldmakethatwouldlast.Paintingsdidn'tbecomeobsolete.Someofthebestoneswerehundredsofyearsold.

Andmoreoverthiswassomethingyoucouldmakealivingdoing.Notaseasilyasyoucouldbywritingsoftware,ofcourse,butIthoughtifyouwerereallyindustriousandlivedreallycheaply,ithadtobepossibletomakeenoughtosurvive.Andasanartistyoucouldbetrulyindependent.Youwouldn'thaveaboss,orevenneedtogetresearchfunding.

Ihadalwayslikedlookingatpaintings.CouldImakethem?Ihadnoidea.I'dneverimagineditwasevenpossible.Iknewintellectuallythatpeoplemadeart—thatitdidn'tjustappearspontaneously—butitwasasifthepeoplewhomadeitwereadifferentspecies.TheyeitherlivedlongagoorweremysteriousgeniusesdoingstrangethingsinprofilesinLifemagazine.Theideaofactuallybeingabletomakeart,toputthatverbbeforethatnoun,seemedalmostmiraculous.

这些结果好多了!我们可以看到,最上面的文档回答了用户的问题。请注意,我们不必指定用于重新排名的第三方 API。再一次,PostgresML 使用数据库中的交叉编码器来处理重新排名。

我们可以在 RAG 中直接使用重新排序:

query_engine=index.as_query_engine(
streaming=True,
vector_search_limit=2,
vector_search_rerank={
"model":"mixedbread-ai/mxbai-rerank-base-v1",
"num_documents_to_rerank":100,
},
)
results=query_engine.query("Whatdidtheauthordoasachild?")
fortextinresults.response_gen:
print(text,end="",flush=True)

运行此输出:

Basedonthecontextinformation,asachild,theauthorworkedonwriting(writingshortstories)andprogramming(ontheIBM1401usingFortran)outsideofschool.

这正是我们想要的答案!

重新排序可带来更好的结果

搜索可能很复杂。使用交叉编码器进行重新排序可以通过比较文本对并有效处理新数据来改进搜索。使用 LlamaIndex 和 PostgresML 实现重新排序可以改进搜索结果,在检索增强生成应用程序中提供更精确的答案。

要开始使用 PostgresML 和 LlamaIndex,您可以按照 PostgresML 入门 指南 设置您的帐户,并将上述示例与您自己的数据一起使用。

回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

链载AI是专业的生成式人工智能教程平台。提供Stable Diffusion、Midjourney AI绘画教程,Suno AI音乐生成指南,以及Runway、Pika等AI视频制作与动画生成实战案例。从提示词编写到参数调整,手把手助您从入门到精通。
  • 官方手机版

  • 微信公众号

  • 商务合作

  • Powered by Discuz! X3.5 | Copyright © 2025-2025. | 链载Ai
  • 桂ICP备2024021734号 | 营业执照 | |广西笔趣文化传媒有限公司|| QQ