Skip to content
AI.info

Unsupervised learning

Text and Embedding Clustering

Cluster sparse text vectors and dense embeddings while handling cosine geometry, anisotropy, chunking, generic documents, and topic interpretation.

By the end you can

Example

Text-specific failures hidden by a clean scatter plot

Every failure below has been measured on a named corpus, with a published number. None of them looks wrong on the plot. That is why text clusters have to be read through documents, terms and retrieval behavior instead of pictures.

  • Generic hub: a short policy introduction turns up near many unrelated topics. Broad institutional language makes it a popular nearest neighbour. That is a property of the space, not an accident of one document. Radovanović and two colleagues examined 50 real data sets in 2010 and stated the mechanism: “Through theoretical and empirical analysis involving synthetic and real data sets we show that under commonly used assumptions this distribution becomes considerably skewed as dimensionality increases, causing the emergence of hubs, that is, points with very high k-occurrences which effectively represent "popular" nearest neighbors.” Hubness tracks intrinsic rather than embedding dimensionality. Nielsen and Hansen measured it inside Sentence-BERT in 2024: combining two hubness-reduction methods cut hubness by about 75% and the neighbourhood-classifier error rate by about 9%. Across four pretrained models on 20 Newsgroups the same combination reduced hubness by 69–83% and error rates by 7–9%. A hub is a diagnosable, partly removable defect with a size. It is not an unlucky document.
  • Chunk leakage: adjacent chunks cut from one document fall into several clusters, and each of those groups then looks more coherent than it is. The same author, the same template and the same vocabulary are being counted several times over. The cluster is partly a measurement of your segmentation rule.
  • Template dominance: boilerplate signatures, headers, disclaimers and quoted replies form clusters unrelated to the actual issue content, and they are rarely a small share of the text. Six researchers counted the lines of the 20 Newsgroups corpus in 2024. Over 16.5% of all lines — 126,202 of 762,321 — are quotes rather than original content.
  • Language split: multilingual tickets separate by language even when the intended grouping is problem type. A 2019 study trained a classifier that recovered the language of an mBERT sentence representation with 93.5% accuracy from the best-scoring layers using the [CLS] vector, and 91.9% from mean-pooled states. Accuracy fell to 28.5% only once the language centroid was subtracted. Hierarchical clustering of mBERT's language centroids reproduced genealogical language families at a V-Measure of 82.42, against 62.14 for random grouping. The pull also survives fine-tuning. In the LAReQA benchmark's 'Remove One Target' experiment on XQuAD-R, the English-fine-tuned mBERT (En-En) scored 0.22 mAP when the same-language target answer was removed, against 0.29 when a random cross-language target was removed — a 24% delta. The LAReQA authors put it plainly: “This is illustrated in Figure 1a, where the embeddings cluster primarily by language, and incorrect same-language candidates are preferred over any cross-language candidate.”
  • Semantic collapse: an encoder treats “cancel a subscription” and “subscription cancellation policy” as close, despite the different user intent. The training objective rewarded topical proximity. Nobody asked it to separate a request from a document about requests.

The topic model that really separated document length

Cluster raw term counts over a support inbox and the groups that come back can be short, medium and long tickets. Length is the loudest signal the representation carries, so length is what the algorithm returns. Replace counts with normalized TF–IDF and issue families appear. Hand the same text to a dense encoder and several operationally distinct policies merge into one region. Nothing about the clustering code changed in any of those three runs.

Text clustering is representation-sensitive because words, sequences and semantic embeddings preserve different relations. A modern encoder does not remove that choice. It hides it inside a trained objective. The rest of this lesson prices each layer of the choice with published measurements rather than assurances: the geometry of an encoder's raw output, the share of a canonical corpus that is boilerplate, the language axis inside a multilingual model, the standing of lexical matching against dense retrieval, and the gap between a model's automatic score and what a human reads in its topics.

The embedding objective decides which linguistic differences remain visible.

Visual

Three text representations and their blind spots

The representation determines whether clusters emphasize vocabulary, latent co-occurrence, or learned semantic proximity. A cluster interpretation can never recover information the representation threw away.

Sparse lexical vectors — counts, n-grams, or TF–IDF — preserve explicit vocabulary evidence, so every membership can be traced back to terms a reviewer can read. Linear latent vectors, produced by truncated SVD, compress sparse co-occurrence into dense signed components. That reduces sparsity at the cost of the rare precise term. Neural embeddings map text into learned semantic or task-influenced spaces whose axes were fixed by a training objective you did not choose. Document aggregation sits underneath all three: chunking, pooling and metadata decide how a long text becomes one vector, and therefore decide what is being clustered at all.

FigureHierarchy · 4 levels
  • Sparse lexical vectors

    Counts, n-grams, or TF–IDF preserve explicit vocabulary evidence.

    • Linear latent vectors

      Truncated SVD compresses sparse co-occurrence into dense components.

      • Neural embeddings

        Encoders map text into learned semantic or task-influenced spaces.

        • Document aggregation

          Chunking, pooling, and metadata determine how long text becomes one vector.

A cluster interpretation cannot exceed the information preserved by its representation.

Key idea

Do not cluster a two-dimensional text visualization

t-SNE and UMAP can exaggerate gaps or compress distances to support visualization. Running a second clustering algorithm on the plotted coordinates turns visualization artifacts into labels.

Cluster in a validated sparse or higher-dimensional embedding space. Use two-dimensional projections to inspect examples, not as automatic evidence of topic boundaries. Chari and Pachter measured what the picture costs the analysis. Writing in PLOS Computational Biology in 2023, they state that “extreme dimension reduction, from hundreds or thousands of dimensions to 2, inevitably induces significant distortion of high-dimensional datasets”, and conclude that “extensive distortions and inconsistent practices make such embeddings counter-productive for exploratory, biological analyses”. That verdict comes from single-cell genomics. The geometry behind it does not care about the field. A text embedding squeezed to two axes has been distorted by the same arithmetic.

Visualization coordinates are not a neutral replacement for the original representation.

Steps

Build an auditable text-clustering pipeline

Representation, chunking, clustering and naming should be evaluated separately, because each one can produce the whole result on its own.

1. Define the text unit. Choose message, paragraph, document, conversation, or fixed window according to the action the clusters will drive.

2. Remove structural noise. Handle boilerplate, signatures, markup, duplicates and language metadata explicitly, and treat this as a measurable step rather than hygiene. The scikit-learn User Guide sizes the effect on the canonical text benchmark. On its four-newsgroup example from 20 Newsgroups (alt.atheism, talk.religion.misc, comp.graphics, sci.space), the same multinomial Naive Bayes model scores a macro F1 of 0.88213 on the raw text, 0.77310 once headers, footers and quoted blocks are stripped from the test set, and 0.76995 when they are stripped from training too. The guide's own reading of the raw score is blunt: “With such an abundance of clues that distinguish newsgroups, the classifiers barely have to identify topics from text at all, and they all perform at the same high level.” The documented remedy is the loader argument remove=('headers','footers','quotes'). Eleven points of F1 were never topic structure.

3. Compare representations. Benchmark lexical, latent and neural spaces against domain contrast pairs you wrote down before looking at the clusters.

4. Fit several cluster models. Use cosine-compatible centroid, density, or hierarchical approaches where appropriate, and keep the disagreements rather than the prettiest run.

5. Name from evidence. Review exemplars, discriminative terms, boundary cases and contradictions before assigning labels. Do not delegate the judgement to an automatic coherence score: Doogan and Buntine re-tested those measures against human open-labelling in applied settings in 2021, and reported against them.

6. Test downstream use. Measure routing, retrieval, taxonomy coverage, or analyst discovery rather than plot beauty.

FigureProcess · 6 steps
  1. 1. Define text unit

    Choose message, paragraph, document, conversation, or fixed window according to the action.

  2. 2. Remove structural noise

    Handle boilerplate, signatures, markup, duplicates, and language metadata explicitly.

  3. 3. Compare representations

    Benchmark lexical, latent, and neural spaces with domain contrast pairs.

  4. 4. Fit several cluster models

    Use cosine-compatible centroid, density, or hierarchical approaches where appropriate.

  5. 5. Name from evidence

    Review exemplars, discriminative terms, boundary cases, and contradictions before assigning labels.

  6. 6. Test downstream use

    Measure routing, retrieval, taxonomy coverage, or analyst discovery rather than plot beauty.

Comparison

Lexical and semantic clustering solve different problems

Pipelines compare both instead of treating one as universally superior, and the benchmark record supports that caution.

TF–IDF plus cosine groups documents through weighted term overlap: transparent vocabulary evidence, strong on domain-specific terminology, weak on paraphrase, sensitive to tokenization and rare terms. LSA plus clustering uses truncated SVD to compress term-document structure. It reduces sparsity and captures broad co-occurrence, but produces signed latent components and can blur the rare precise term. Dense sentence embeddings group learned semantic representations: many paraphrases are recognized, generic hubs appear, training-domain bias is inherited, and language and domain evaluation is required.

The trade-off has been measured rather than argued. The BEIR benchmark, published in 2021, evaluated 10 retrieval systems across 18 datasets. Its abstract reports that “Our results show BM25 is a robust baseline and re-ranking and late-interaction-based models on average achieve the best zero-shot performances, however, at high computational costs.” Four researchers pushed on the same seam later that year. Building EntityQuestions out of Wikidata facts, they measured DPR at 49.7% top-20 accuracy against BM25's 71.2% on average, with the gap on some question patterns reaching 60% absolute. Lexical evidence is not a legacy baseline you have outgrown.

The dense column carries a second, quieter problem. Cosine over an encoder's raw output is not a neutral distance. Kawin Ethayarajh measured the geometry of contextual embeddings in 2019 and found no layer isotropic: for GPT-2 the average cosine similarity between uniformly randomly sampled words is roughly 0.6 in layers 2 through 8, and rises to almost 1.0 in the last layer. His first finding says it outright: “The anisotropy in GPT-2’s last layer is so extreme that two random words will on average have almost perfect cosine similarity!” Timkey and van Schijndel traced the distortion in 2021, independently, to just 1–3 'rogue' dimensions that dominate cosine similarity until the dimensions are standardised. A high cosine similarity means nothing until you know what two unrelated documents score in the same space.

FigureComparison · 3 columns

TF–IDF plus cosine

Groups documents through weighted term overlap.

  • Transparent vocabulary evidence
  • Strong for domain-specific terminology
  • Weak on paraphrase
  • Sensitive to tokenization and rare terms

LSA plus clustering

Uses truncated SVD to compress term-document structure.

  • Reduces sparsity
  • Captures broad co-occurrence
  • Produces signed latent components
  • Can blur rare precise terms

Dense sentence embeddings

Groups learned semantic representations.

  • Recognizes many paraphrases
  • Can create generic hubs
  • Inherits training-domain bias
  • Needs language and domain evaluation

Analogy

Organizing a library by words, themes, or reader behavior

Books can be shelved by shared vocabulary, by inferred themes, or by patterns learned from what readers borrow together. Each system creates a different neighborhood, and each is defensible on its own terms.

Catalog rules are explicit. A reader who disagrees with a shelf can read the rule and argue with it. Text embeddings combine many learned signals that may not be visible to reviewers at all, including signals nobody intended to encode — the language a sentence is written in, or the boilerplate wrapped around it. No shelf label explains why two documents ended up adjacent.

A semantic vector is a learned shelving policy, not meaning itself.

Text clusters are editorial hypotheses backed by a representation

A topic name like “billing problem” should come from sampled documents, distinguishing terms and domain review. The algorithm supplies memberships, not the title and not the explanation. The automatic score you would rather trust instead has been tested against human readers, and it lost. Five researchers ran word-intrusion and topic-intrusion studies on Amazon Mechanical Turk in 2009, over 8,447 New York Times articles from 1987–2007 with an 8,269-type vocabulary, and over 10,000 Wikipedia articles. The model with the better held-out likelihood, CTM, produced the topics people read worst. Their abstract records it as a surprise: “Surprisingly, topic models which perform better on held-out likelihood may infer less semantically meaningful topics.” Twelve years later Doogan and Buntine reached the same verdict against automated coherence measures on specialised collections.

Version tokenizer, encoder, chunking, preprocessing and model together. A representation update can rewrite the topic map even when the clustering code is unchanged. A lineage record that names only the algorithm will not tell you which of the two happened.

Text-cluster lineage starts before the clustering algorithm.

Case

Sixty-five hours of BERT, or five seconds

Brute-force similarity search was priced in 2019. Reimers and Gurevych, introducing Sentence-BERT, state in their abstract that “Finding the most similar pair in a collection of 10,000 sentences requires about 50 million inference computations (~65 hours) with BERT”. That cost, they write, “makes it unsuitable for semantic similarity search as well as for unsupervised tasks like clustering”. Their own architecture “reduces the effort for finding the most similar pair from 65 hours with BERT / RoBERTa to about 5 seconds with SBERT, while maintaining the accuracy from BERT”.

The difference is structural, not an optimization. A cross-encoder must run the model once per pair, so its cost grows with the square of the collection. A bi-encoder embeds each sentence once and compares vectors afterwards, which is what makes clustering possible at all. How an encoder was trained decides whether clustering its output is affordable, before any question of whether the clusters are good.

Figure

Why an all-pairs task decides which encoder you can use: the same 10,000-sentence search priced two ways.

Key takeaways