Sub topic 10
Sentence embeddings as document representations
This chapter covers how a sentence embedding model turns a document into a vector, and why that vector suits topic modelling. It assumes you have read the earlier chapters on bag-of-words counts. It also assumes you can run Python with pip, and that you know a vector embedding is a list of numbers where similar meanings sit close together.
Why BERTopic needs a different representation
LDA works on bag-of-words counts. Each document is a long, sparse vector with one slot per vocabulary word. Two documents only look similar if they share words. "The striker scored late" and "the forward netted in injury time" have almost no words in common, so their count vectors are nearly orthogonal.
A sentence embedding model maps each text to a dense vector, typically 384 to 1024 numbers. The model is trained so that texts with similar meaning land near each other, even when they use different words. BERTopic clusters these vectors, so the quality of the embeddings sets the ceiling on the quality of the topics.
| Property | Bag-of-words | Sentence embedding |
|---|---|---|
| Dimensions | Vocabulary size (10,000s) | Fixed (for example 384) |
| Sparsity | Mostly zeros | Dense |
| Synonyms | Treated as unrelated | Usually close together |
| Word order and context | Ignored | Partly captured |
| Interpretable axes | Yes, one word per axis | No |
The last row matters. You cannot read a topic off an embedding axis. That is why BERTopic adds a separate step (c-TF-IDF, covered later) to produce topic words.
How an embedding is produced
A sentence embedding model is a transformer encoder. It splits text into word pieces, runs them through the network, and gets one output vector per piece. A pooling step then collapses these into one vector for the whole text. Mean pooling, which averages the piece vectors, is the most common choice.
The model is trained on pairs of related texts, such as questions and answers or paraphrases. Training pulls related pairs together and pushes unrelated texts apart. This is why a general-purpose model like all-MiniLM-L6-v2 works well for topic discovery without any training on your corpus.
Computing embeddings
Install the library with pip install sentence-transformers. The first call downloads the model weights.
from sentence_transformers import SentenceTransformer, util
model = SentenceTransformer("all-MiniLM-L6-v2")
docs = [
"The striker scored a late goal to win the match.",
"The forward netted in injury time to decide the game.",
"Parliament voted on the new tax policy yesterday.",
"The government passed the budget after a long debate.",
]
embeddings = model.encode(
docs,
batch_size=32,
normalize_embeddings=True,
show_progress_bar=False,
)
print(embeddings.shape) # (4, 384)
sims = util.cos_sim(embeddings, embeddings)
print(sims)The shape is (4, 384): one 384-number row per document. In the similarity matrix, the two football sentences should score clearly higher with each other than with the politics sentences. They share almost no words, so a count-based method would not see the link.
Cosine similarity and normalisation
Cosine similarity compares the angle between two vectors and ignores their length. With normalize_embeddings=True, every vector has length 1. Cosine similarity then equals the dot product, and Euclidean distance becomes a monotonic function of cosine similarity. That matters because HDBSCAN is often run with Euclidean distance, while UMAP can use cosine. Normalised vectors keep the two choices consistent.
Choosing a model
all-MiniLM-L6-v2: 384 dimensions, small and fast, a good default. It is trained mainly on English.- Larger models such as
all-mpnet-base-v2: 768 dimensions, slower, usually a little better at separating close topics. - Multilingual models such as
paraphrase-multilingual-MiniLM-L12-v2: needed when the corpus mixes languages. Documents in different languages then share one space. - Domain models: for legal, biomedical, or code text, a model trained on that domain often beats a general one.
Judge a model on your own data. Embed a sample, pick a few documents, and inspect their nearest neighbours. If the neighbours are on the wrong subject, a different model will help more than any tuning of UMAP or HDBSCAN.
Edge cases and common errors
Truncation of long documents
Every model has a maximum input length, exposed as model.max_seq_length. For all-MiniLM-L6-v2 it is 256 word pieces, roughly 200 words. Anything beyond that is silently dropped. A 2,000-word article is therefore represented by its opening only.
Two fixes work well. If your documents are long, split them into paragraphs or sentences and treat each as its own document. Alternatively, embed chunks and average them:
import numpy as np
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("all-MiniLM-L6-v2")
def embed_long(text, model, chunk_words=150):
words = text.split()
chunks = [
" ".join(words[i : i + chunk_words])
for i in range(0, len(words), chunk_words)
] or [""]
vectors = model.encode(
chunks, normalize_embeddings=True, show_progress_bar=False
)
mean = vectors.mean(axis=0)
return mean / np.linalg.norm(mean)
vec = embed_long("word " * 1000, model)
print(vec.shape) # (384,)Averaging blurs documents that cover several subjects. Splitting into smaller documents keeps topics sharper, but you then get topics per chunk rather than per document.
Preprocessing differs from LDA
For LDA you lower-case, remove stop words, and often lemmatise. Do not do this before embedding. The model was trained on natural sentences, and stop words and word order carry meaning for it. Stripping them gives vectors from text the model never saw. Feed it the raw text, with only light cleaning such as removing markup, URLs, and boilerplate. Stop-word removal belongs later, in the vectoriser that builds c-TF-IDF.
Other pitfalls
- Very short texts. Tweets and titles give noisy vectors, and many become outliers during clustering.
- Duplicates and boilerplate. Repeated email footers or templates form their own tight cluster. Remove them first.
- Mixed model and metric. Some models are trained for dot product, others for cosine. Check the model card before choosing a metric.
- Recomputing every run. Encoding is the slowest step on large corpora. Compute once, save with
np.save, and reuse. - Changing models between runs. Vectors from different models live in different spaces. Never mix them or compare them directly.
Reusing embeddings with BERTopic
BERTopic accepts precomputed embeddings, so you can tune the later stages without re-encoding. This is the main practical benefit of treating embedding as its own step.
import numpy as np
from bertopic import BERTopic
from sentence_transformers import SentenceTransformer
# Replace this placeholder with your real corpus. BERTopic needs far more
# than a few documents for its clustering step to find topics.
docs = ["your document text here"] * 500
model = SentenceTransformer("all-MiniLM-L6-v2")
embeddings = model.encode(docs, normalize_embeddings=True, show_progress_bar=True)
np.save("embeddings.npy", embeddings)
embeddings = np.load("embeddings.npy")
topic_model = BERTopic(embedding_model=model, min_topic_size=15)
topics, probs = topic_model.fit_transform(docs, embeddings=embeddings)Passing embedding_model=model as well lets BERTopic embed new documents later, for example in transform. It uses the precomputed embeddings for the fit itself.
Exercise
You embed 5,000 news articles averaging 1,200 words with all-MiniLM-L6-v2 and cluster the vectors. The topics seem to depend only on the article introductions. Why does this happen, and what are two ways to fix it?
Show answer
The model's maxseqlength is 256 word pieces, so it silently drops everything after roughly the first 200 words, and each vector represents only the introduction. Fix it by splitting articles into paragraphs and treating each as its own document, or by embedding chunks and averaging the normalised chunk vectors. A model with a longer input limit is a third option.
Exercise
Why should you not remove stop words and lemmatise your text before passing it to a sentence embedding model, even though you would do so for LDA?
Show answer
The embedding model was trained on natural sentences, where stop words and word order carry meaning. Stripped or lemmatised text is input it never saw in training, so the vectors get worse. Do stop-word removal later, in the vectoriser that builds the topic words.