This model borrows from Greg Kamradt’s work here: https://github.com/FullStackRetrieval-com/RetrievalTutorials/blob/main/5_Levels_Of_Text_Splitting.ipynb. The idea is to segment text into semantically coherent chunks. The primary goal of this work is to use sentence transformers embeddings to represent the meaning of sentences and detect shifts in meaning to identify potential breakpoints between chunks.
Model Description
This model aims to segment a text into semantically coherent chunks. It uses sentence-transformers embeddings to represent the meaning of sentences and detect shifts in the meaning to identify potential breakpoints between chunks. There are two primary changes in function from Greg Kamradt excellent original work: 1) Introduce the use of sentence-transformer embeddings rather than OpenAI to provide an entirely open source implementation of semantic chunking, and 2) add functionality to merge smaller chunks with their most semantically similar neighbors to better normalize chunk size. The goal is to use semantic Understanding to enable a model to consider the meaning of text segments rather than purely relying on punctuation or syntax, and to provide flexiblity so that the breakpoint_percentile_threshold and min_chunk_size can be adjusted to influence the granularity of the chunks.
General Outline:
Preprocessing
- Loading Text: Reads the text from the specified path.
- Sentence Tokenization: Splits the text into a list of individual sentences using nltk's sentence tokenizer.
Semantic Embeddings
- Model Loading: Loads a pre-trained Sentence Transformer model ( in this case: 'sentence-transformers/all-mpnet-base-v1').
- Embedding Generation: Converts each sentence into an embedding to represent its meaning.
Sentence Combination:
- Combines each sentence with its neighbors to form slightly larger units, helping the model understand the context in which changes of topic are likely to occur.
Breakpoint Identification
Cosine Distance: Calculates cosine distances between embeddings of the combined sentences. These distances represent the degree of semantic dissimilarity.
Percentile-Based Threshold: Determines a threshold based on a percentile of the distances (e.g., 95th percentile), where higher values indicate more significant semantic shifts.
Locating Breaks: Identifies the indices of distances above the threshold, which mark potential breakpoints between chunks. Chunk Creation:
Splitting at Breakpoints: Divides the original sentences into chunks based on the identified breakpoints.
Chunk Merging:
- Minimum Chunk Size: Defines a minimum number of sentences to consider a chunk valid.
- Similarity-Based Merging: Merges smaller chunks with their most semantically similar neighbor based on cosine similarity between chunk embeddings.
Output:
- The model ultimately produces a list of text chunks (chunks), each representing a somewhat self-contained, semantically cohesive segment of the original text.
Usage
Using this chunker is easy when you have sentence-transformers installed:
pip install -U sentence-transformers
Then you can implement like this:
---
license: mit
---
import nltk
from nltk.tokenize import sent_tokenize
from sentence_transformers import SentenceTransformer
from sklearn.metrics.pairwise import cosine_similarity
import numpy as np
import matplotlib.pyplot as plt
# Load and tokenize the text
def load_and_tokenize(file_path):
with open(file_path, 'r') as f:
text = f.read()
return sent_tokenize(text)
# Combine sentences with their neighbors
def combine_sentences(sentences, buffer=1):
combined = []
for i in range(len(sentences)):
start = max(0, i - buffer)
end = min(len(sentences), i + buffer + 1)
combined.append(' '.join(sentences[start:end]))
return combined
# Calculate cosine distances between embeddings
def calc_cosine_distances(embeddings):
distances = []
for i in range(len(embeddings) - 1):
sim = cosine_similarity([embeddings[i]], [embeddings[i + 1]])[0][0]
distances.append(1 - sim)
return distances
# Find breakpoints based on distance threshold
def find_breakpoints(distances, percentile=95):
threshold = np.percentile(distances, percentile)
return [i for i, d in enumerate(distances) if d > threshold]
# Create chunks based on breakpoints
def create_chunks(sentences, breakpoints):
chunks = []
start = 0
for bp in breakpoints:
chunks.append(' '.join(sentences[start:bp + 1]))
start = bp + 1
chunks.append(' '.join(sentences[start:]))
return chunks
# Merge small chunks with their most similar neighbor
def merge_small_chunks(chunks, embeddings, min_size=3):
merged = [chunks[0]]
merged_emb = [embeddings[0]]
for i in range(1, len(chunks) - 1):
if len(chunks[i].split('. ')) < min_size:
prev_sim = cosine_similarity([embeddings[i]], [merged_emb[-1]])[0][0]
next_sim = cosine_similarity([embeddings[i]], [embeddings[i + 1]])[0][0]
if prev_sim > next_sim:
merged[-1] += ' ' + chunks[i]
merged_emb[-1] = (merged_emb[-1] + embeddings[i]) / 2
else:
chunks[i + 1] = chunks[i] + ' ' + chunks[i + 1]
embeddings[i + 1] = (embeddings[i] + embeddings[i + 1]) / 2
else:
merged.append(chunks[i])
merged_emb.append(embeddings[i])
merged.append(chunks[-1])
merged_emb.append(embeddings[-1])
return merged, merged_emb
# Main process
def chunk_text(file_path):
# Load the model
model = SentenceTransformer('sentence-transformers/all-mpnet-base-v1')
# Process the text
sentences = load_and_tokenize(file_path)
combined = combine_sentences(sentences)
embeddings = model.encode(combined)
# Find breakpoints and create initial chunks
distances = calc_cosine_distances(embeddings)
breakpoints = find_breakpoints(distances)
chunks = create_chunks(sentences, breakpoints)
# Merge small chunks
chunk_embeddings = model.encode(chunks)
final_chunks, _ = merge_small_chunks(chunks, chunk_embeddings)
return final_chunks
if __name__ == "__main__":
file_path = "/path/to/your/text/file.txt"
result = chunk_text(file_path)
print(f"Number of chunks: {len(result)}")
print("First chunk:", result[0][:100] + "...")
Evaluation Results
Testing on various buffer sizes and breakpoints using the King James Version of the book of Romans (Available here: https://quod.lib.umich.edu/cgi/k/kjv/kjv-idx?type=DIV1&byte=5015363).
Intra-chunk similarity (how similar the sentences in a given chunk are to each other. Higher = More Semantically Similar):
Inter-chunk similarity (how similar the respective chunks are to each other. Lower = Less Semantically Similar):
Citing and Authors
If you find this model helpful, please enjoy and give all credit to Greg Kamradt for the idea.