链载Ai

标题: RAG15种分块策略进行汇总介绍。 [打印本页]

作者: 链载Ai    时间: 昨天 13:20
标题: RAG15种分块策略进行汇总介绍。

上一篇我们介绍了5种常见的分块策略,那这一篇我们来介绍下15种分块策略进行汇总介绍。




固定大小分块

01


固定大小的分块将文档拆分为预定义大小的块,通常按字数、标记数或字符数。


当您需要一种简单明了的方法并且文档结构并不重要时。它在处理较小、不太复杂的文档时效果很好。


优势:

弊:




基于句子分块

02


此方法根据自然句子边界对文本进行分块。每个块都包含一定数量的句子,保留语义单元。保持连贯的思想是至关重要的,在句子中间拆分会导致失去意义。


优势:

弊:

importspacynlp=spacy.load("en_core_web_sm")defsentence_chunk(text):doc=nlp(text)return[sent.textforsentindoc.sents]#ApplyingSentence-BasedChunkingsentence_chunks=sentence_chunk(sample_text)forchunkinsentence_chunks:print(chunk,'\n---\n')



基于段落分块

03


此策略根据段落边界拆分文本,将每个段落视为一个块。最适合结构化文档,如报告或论文,其中每个段落都包含一个完整的想法或论点。


优势:

弊:


defparagraph_chunk(text):paragraphs=text.split('\n\n')returnparagraphs#ApplyingParagraph-BasedChunkingparagraph_chunks=paragraph_chunk(sample_text)forchunkinparagraph_chunks:print(chunk,'\n---\n')




基于语义的分块

04


此方法使用机器学习模型(如 transformers)根据语义含义将文本拆分为块。当保留最高级别的上下文至关重要时,例如在复杂的技术文档中。


优势:

弊:


defsemantic_chunk(text,max_len=200):doc=nlp(text)chunks=[]current_chunk=[]forsentindoc.sents:current_chunk.append(sent.text)iflen(''.join(current_chunk))>max_len:chunks.append(''.join(current_chunk))current_chunk=[]ifcurrent_chunk:chunks.append(''.join(current_chunk))returnchunks#ApplyingSemantic-BasedChunkingsemantic_chunks=semantic_chunk(sample_text)forchunkinsemantic_chunks:print(chunk,'\n---\n')



基于多模态的分块

05


此策略分别处理不同的内容类型(文本、图像、表格)。每种模态都根据其特征独立分块。适用于包含各种内容类型的文档,如 PDF 或具有混合媒体的技术手册。


优势:

弊:


defmodality_chunk(text,images=None,tables=None):#Thisfunctionassumesyouhavepre-processedtext,images,andtablestext_chunks=paragraph_chunk(text)return{'text_chunks':text_chunks,'images':images,'tables':tables}#ApplyingModality-SpecificChunkingmodality_chunks=modality_chunk(sample_text,images=['img1.png'],tables=['table1'])print(modality_chunks)




滑动窗口分块

06


滑动窗口分块会创建重叠的数据块,从而允许每个数据块与下一个数据块共享其部分内容。当您需要确保块之间上下文的连续性时,例如在法律或学术文档中。


优势:

弊:


defsliding_window_chunk(text,chunk_size=100,overlap=20):tokens=text.split()chunks=[]foriinrange(0,len(tokens),chunk_size-overlap):chunk=''.join(tokens[i:i+chunk_size])chunks.append(chunk)returnchunks#ApplyingSlidingWindowChunkingsliding_chunks=sliding_window_chunk(sample_text)forchunkinsliding_chunks:print(chunk,'\n---\n')




分层分块

07


分层分块在多个级别划分文档,例如部分、小节和段落。对于高度结构化的文档,如学术论文或法律文本,维护层次结构是必不可少的。


优势:

弊:


defhierarchical_chunk(text,section_keywords):sections=[]current_section=[]forlineintext.splitlines():ifany(keywordinlineforkeywordinsection_keywords):ifcurrent_section:sections.append("\n".join(current_section))current_section=[line]else:current_section.append(line)ifcurrent_section:sections.append("\n".join(current_section))returnsections#ApplyingHierarchicalChunkingsection_keywords=["Introduction","Overview","Methods","Conclusion"]hierarchical_chunks=hierarchical_chunk(sample_text,section_keywords)forchunkinhierarchical_chunks:print(chunk,'\n---\n')




内容感知分块

08


此方法根据内容特征(例如,在段落级别对文本进行分块,将表格作为单独的实体)进行调整。对于内容异构的文档,例如电子书或技术手册,分块必须根据内容类型而变化。


优势:

弊:


defcontent_aware_chunk(text):chunks=[]current_chunk=[]forlineintext.splitlines():ifline.startswith(('##','###','Introduction','Conclusion')):ifcurrent_chunk:chunks.append('\n'.join(current_chunk))current_chunk=[line]else:current_chunk.append(line)ifcurrent_chunk:chunks.append('\n'.join(current_chunk))returnchunks#ApplyingContent-AwareChunkingcontent_chunks=content_aware_chunk(sample_text)forchunkincontent_chunks:print(chunk,'\n---\n')




表感知分块

09


此策略通过将文档表提取为独立的块并将其转换为 markdown 或 JSON 等格式以便于处理来专门处理文档表。对于包含表格数据的文档,例如财务报告或技术文档,其中的表格包含重要信息。


优势:

弊:


importpandasaspddeftable_aware_chunk(table):returntable.to_markdown()#Sampletabledatatable=pd.DataFrame({"Name":["John","Alice","Bob"],"Age":[25,30,22],"Occupation":["Engineer","Doctor","Artist"]})#ApplyingTable-AwareChunkingtable_markdown=table_aware_chunk(table)print(table_markdown)




基于令牌分块

10


基于标记的分块根据固定数量的标记而不是单词或句子来拆分文本。它使用来自 NLP 模型的分词器。对于对 Token 进行作的模型,例如具有 Token 限制的基于 transformer 的模型(例如 GPT-3 或 GPT-4)。


优势:

弊:


fromtransformersimportGPT2Tokenizertokenizer=GPT2Tokenizer.from_pretrained("gpt2")deftoken_based_chunk(text,max_tokens=200):tokens=tokenizer(text)["input_ids"]chunks=[tokens[i:i+max_tokens]foriinrange(0,len(tokens),max_tokens)]return[tokenizer.decode(chunk)forchunkinchunks]#ApplyingToken-BasedChunkingtoken_chunks=token_based_chunk(sample_text)forchunkintoken_chunks:print(chunk,'\n---\n')




基于实体分块

11


基于实体的分块利用命名实体识别 (NER) 根据识别的实体(如人员、组织或位置)将文本分成多个块。对于特定实体必须作为上下文单元进行维护的文档,例如简历、合同或法律文档。


优势:

弊:


defentity_based_chunk(text):doc=nlp(text)entities=[ent.textforentindoc.ents]returnentities#ApplyingEntity-BasedChunkingentity_chunks=entity_based_chunk(sample_text)print(entity_chunks)




基于主题分块

12


用于涵盖多个主题的文档,例如新闻文章、研究论文或具有不同主题的报告。


优势:

弊:




基于页面分块

13


根据页面边界拆分文档,页面边界通常用于 PDF 或格式化文档,其中每个页面都被视为一个块。对于页面边界具有语义重要性的页面文档,如 PDF 或可打印报表。


优势:

弊:


defpage_based_chunk(pages):#Splitbasedonpre-processedpagelist(simulatingPDFpagetext)returnpages#Samplepagespages=["age1content","age2content","age3content"]#ApplyingPage-BasedChunkingpage_chunks=page_based_chunk(pages)forchunkinpage_chunks:print(chunk,'\n---\n')




基于关键字分块

14


此方法根据表示主题转移的预定义关键字或短语(例如,“Introduction”、“Conclusion”)对文档进行分块。适合遵循清晰结构的文档,例如科学论文或技术规范。


优势:

弊:


defkeyword_based_chunk(text,keywords):chunks=[]current_chunk=[]forlineintext.splitlines():ifany(keywordinlineforkeywordinkeywords):ifcurrent_chunk:chunks.append('\n'.join(current_chunk))current_chunk=[line]else:current_chunk.append(line)ifcurrent_chunk:chunks.append('\n'.join(current_chunk))returnchunks#ApplyingKeyword-BasedChunkingkeywords=["Introduction","Overview","Conclusion","Methods","Challenges"]keyword_chunks=keyword_based_chunk(sample_text,keywords)forchunkinkeyword_chunks:print(chunk,'\n---\n')




混合分块

15


根据内容类型和文档结构组合了多个分块策略。例如,文本可以按句子分块,而表格和图像是分开处理的。用于包含各种内容类型的复杂文档,如技术报告、业务文档或产品手册。


优势:

弊:


defhybrid_chunk(text):paragraphs=paragraph_chunk(text)hybrid_chunks=[]forparagraphinparagraphs:hybrid_chunks+=sentence_chunk(paragraph)returnhybrid_chunks#ApplyingHybridChunkinghybrid_chunks=hybrid_chunk(sample_text)forchunkinhybrid_chunks:print(chunk,'\n---\n')



在构建检索增强生成 (RAG) 时,针对特定用例和文档类型优化分块至关重要。不同的场景根据文档大小、内容多样性和检索速度有不同的要求。让我们根据这些因素探讨一些优化策略。


选择正确的分块策略取决于多个因素,包括文档类型、上下文保留的需求以及检索速度和准确性之间的平衡。无论您是处理学术论文、法律文档还是混合内容文件,选择合适的方法都可以显著提高 RAG 的有效性。通过迭代和优化分块方法,您可以适应不断变化的文档类型和用户需求,确保您的检索系统保持稳健和高效。






欢迎光临 链载Ai (https://www.lianzai.com/) Powered by Discuz! X3.5