Sub topic 5
Finding themes in unlabelled reviews
Earlier chapters defined a label taxonomy and prepared the review text. This chapter covers the case where you have no labels yet and want to know what customers talk about. It assumes you can read basic Python, know what a vector is, and have scikit-learn installed. The output is a set of named themes, each backed by example reviews, which you can later fold into your taxonomy.
Why discover themes instead of assigning them
A fixed taxonomy only finds what you already expect. Real feedback often contains topics nobody planned for, such as a packaging change that customers dislike or a confusing login step. Topic discovery is the exploratory step. It groups similar reviews without labels so that a person can look at each group and name it.
Discovery and classification serve different jobs:
| Approach | Needs labels? | Best for | Main risk |
|---|---|---|---|
| Clustering (this chapter) | No | Finding unknown themes | Groups that are hard to name |
| LLM classification (later chapter) | A taxonomy | Counting known themes reliably | Missing themes outside the taxonomy |
A common workflow is to cluster a sample, name the themes by hand, update the taxonomy, and then classify the full set with an LLM.
The pipeline at a glance
The loop between inspection and clustering matters. You will rarely get good groups on the first run.
Step 1: Turn text into vectors
Clustering algorithms work on numbers, so each review becomes a vector. Two common choices exist.
TF-IDF (term frequency, inverse document frequency) gives each word a weight. The weight is high when a word appears often in one review and rarely across all reviews. Words such as "the" get low weights because they appear everywhere. TF-IDF is fast, needs no model download, and its dimensions are real words, so you can read the result directly.
Embeddings are dense vectors produced by a neural model. Reviews with similar meaning land close together even when they share no words. "The parcel never showed up" and "Still waiting for my order" have no words in common after stop words are removed, but an embedding model places them near each other. The cost is a model to run, and dimensions you cannot read.
| Property | TF-IDF | Embeddings |
|---|---|---|
| Captures synonyms | No | Yes |
| Readable features | Yes | No |
| Setup | One scikit-learn class | A model or API call |
| Cost on large sets | Low | Higher |
| Handles short, vague text | Poorly | Better |
Start with TF-IDF as a baseline. Move to embeddings if the clusters mix topics or split one topic across several groups because customers use different words.
Step 2: Cluster with k-means
K-means is an algorithm that splits vectors into k groups. It picks k centers, assigns each vector to its nearest center, moves each center to the average of its group, and repeats until the assignments stop changing. Each final center summarises its group.
The example below clusters six reviews into two groups and prints the three highest-weighted terms of each cluster center. Those terms are what you read to name a theme.
from sklearn.cluster import KMeans
from sklearn.feature_extraction.text import TfidfVectorizer
reviews = [
"Delivery was late and the box was damaged",
"Package arrived two days late",
"Courier left the parcel damaged and late",
"Great battery life and bright screen",
"The screen is bright and the battery lasts all day",
"Battery easily lasts two days, screen looks great",
]
vectorizer = TfidfVectorizer(stop_words="english")
X = vectorizer.fit_transform(reviews)
kmeans = KMeans(n_clusters=2, n_init=10, random_state=0).fit(X)
terms = vectorizer.get_feature_names_out()
for cluster in range(kmeans.n_clusters):
top = kmeans.cluster_centers_[cluster].argsort()[::-1][:3]
print(cluster, [terms[i] for i in top])You should see one cluster led by words like late and damaged, and another led by battery and screen. The cluster numbers (0 or 1) can swap between environments, so name themes by their content, never by their number.
Some details in the code:
stop_words="english"removes common words. Without it, the top terms of every cluster are filled with "the" and "and".n_init=10runs k-means from ten starting points and keeps the best result. K-means is sensitive to its starting centers, so a single run can give a poor split.random_state=0makes the result repeatable. Keep it fixed while you tune, so changes in the output come from your settings and not from chance.argsort()[::-1]sorts term indexes from the highest weight to the lowest.
Step 3: Choose the number of clusters
K-means requires you to supply k. There is no correct value, only a useful one. Two aids help.
- Silhouette score. This score runs from -1 to 1 and measures how close each review is to its own cluster compared with the nearest other cluster. Higher means cleaner separation. Compute it for several values of k and look for a peak.
- Reading the clusters. Metrics on text are noisy. A k with a slightly lower score but groups you can name is the better choice.
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
def score_k_values(X, k_values):
scores = {}
for k in k_values:
labels = KMeans(n_clusters=k, n_init=10, random_state=0).fit_predict(X)
scores[k] = silhouette_score(X, labels)
return scoresCall it as score_k_values(X, range(2, 6)) on the matrix from the previous example. It needs at least two clusters and fewer clusters than reviews. On real data, try a range such as 5 to 30, and expect the curve to be flat rather than sharply peaked.
Step 4: Name the themes, with evidence
Top terms are a starting point. Before you name a cluster, also read real reviews from it. Look at the reviews closest to the center, since they are the most typical, and a few random ones, since they show how messy the cluster is. A cluster whose top terms read "love, great, product, good" is probably a catch-all for generic praise and carries no theme.
Record for every theme:
- A short name, such as "late or damaged delivery".
- The top terms.
- The size of the cluster as a share of reviews.
- Three to five example reviews, with their IDs.
Keeping IDs lets you trace any later claim back to source text, which a later chapter on summarisation depends on.
Edge cases and common errors
Clusters of different sizes. K-means tends to produce groups of similar spread. One huge theme such as "general satisfaction" can get split in two while a small but important theme, like a safety complaint, gets absorbed into a neighbour. If a rare topic matters to you, search for it directly with keywords or an LLM rather than hoping clustering isolates it.
Mixed reviews. A single review often covers delivery and product quality. K-means assigns it to exactly one cluster, so the other topic is lost. Clustering at sentence level, after splitting each review, reduces this. Aspect-based analysis, covered later, handles it more directly.
Duplicates inflate clusters. If one review was posted fifty times, it becomes a cluster. Deduplicate before clustering, as in the preparation chapter.
Short or empty text. Reviews such as "ok" or "good" produce almost empty vectors and tend to land in random clusters. Filter out texts below a minimum length, or place them in a separate "too short" bucket.
Mixed languages. An English stop word list and an English-only embedding model will cluster other languages by language and not by topic. Detect language first and cluster each language separately, or use a multilingual embedding model.
Domain words that dominate. If the product name appears in most reviews, it will top every cluster. Add it to the stop word list, or set max_df=0.8 in TfidfVectorizer to drop terms that appear in more than 80% of reviews.
Instability. Different random seeds can give different groups. Run with several seeds. If themes change a lot, the structure in the data is weak, and you should report the themes as tentative.
Personal data. Cluster examples show real review text to whoever reads your report. Redact personal data first, as covered earlier.
Using embeddings and an LLM to help
When TF-IDF clusters are muddy, replace the vectors but keep the rest of the pipeline. Any model that returns one vector per review works, and the call is the only change.
import numpy as np
from sklearn.cluster import KMeans
def cluster_embeddings(vectors, k):
X = np.asarray(vectors, dtype=float)
X = X / np.linalg.norm(X, axis=1, keepdims=True)
return KMeans(n_clusters=k, n_init=10, random_state=0).fit_predict(X)Normalising each vector to length 1 makes Euclidean distance behave like cosine similarity, which is the usual measure of closeness for embeddings. Because embedding dimensions have no readable words, you cannot print top terms. Instead, show the reviews nearest each center and name the theme from those.
An LLM can then propose a name from a handful of example reviews per cluster. Treat the name as a suggestion. Check it against the examples yourself, because a model will happily produce a confident label for a cluster that is really a mix of topics.
Deciding what to do next
Use this as a quick guide:
- Groups are clean and nameable: add the themes to your taxonomy and classify the full dataset.
- One group is a catch-all: raise k, or remove generic terms and recluster.
- Same topic split across groups: lower k, or switch to embeddings.
- Many reviews cover several topics: split into sentences before clustering.
- A rare topic matters: search for it directly instead of relying on clusters.
Exercise
You cluster 2,000 reviews with TF-IDF and k-means. One cluster has top terms "love, great, product, good" and holds 40% of the reviews. Another two clusters both have top terms about shipping and courier problems. Give two changes you would try and say why.
Show answer
First, the generic cluster is a catch-all of general praise. Raise k, add generic words such as "love" and "great" to the stop words, or set max_df to drop very common terms, then recluster so specific topics separate out. Second, the two shipping clusters probably split one theme because customers use different words ("courier", "parcel", "delivery"). Lower k, or switch to embeddings so reviews with similar meaning group together. After either change, read example reviews from each cluster before naming it.
Exercise
Why should you name a cluster by its content and not by its number, and what keeps k-means results repeatable while you tune?
Show answer
Cluster numbers are arbitrary labels assigned during fitting, and they can change between runs or environments, so "cluster 0" may mean different themes at different times. Setting randomstate fixes the starting centers so the same data and settings give the same result, and ninit above 1 reduces the chance of a poor starting point.