Sub topic 6
Grouping Similar Questions into Topic Clusters
This chapter assumes you have already scrubbed personal data, normalised the text and removed duplicates, as covered in the earlier chapters. You should be able to read short Python scripts and have scikit-learn installed. By the end you will be able to group cleaned questions into named topic clusters, check that the groups make sense, and store the cluster on each prompt record.
Why cluster at all
After deduplication you may still have thousands of distinct questions. Many of them ask about the same thing in different words. "How do I change the email on my account?" and "Can I move my subscription to a different email address?" are one topic. If you treat them as separate items, popular topics get over-counted in some places and rare topics are lost in the noise.
A topic cluster is a group of questions about the same subject. Clusters do three jobs later in the pipeline:
- They let you sample in proportion to real demand, so a topic that makes up 20% of questions gets about 20% of the prompts.
- They let you guarantee a minimum for small clusters, so rare but important topics are not dropped.
- They give you a unit for reporting. "Answers about account management are weak" is more useful than a list of 400 unrelated failures.
Topic is a different axis from intent. Intent describes what the person wants to do (learn how, compare, buy, fix). Topic describes what the question is about (billing, delivery, account settings). A question has both. Cluster by topic, and keep the intent label from the previous chapter as a separate field.
The clustering workflow
The loop between inspection and re-clustering is the real work. The algorithm gives you a first draft, and a person decides whether it is usable.
Step 1: Turn questions into vectors
Clustering algorithms work on numbers, so each question becomes a vector. There are two common choices.
| Approach | How it works | Strengths | Weaknesses |
|---|---|---|---|
| TF-IDF | Weights words by how often they appear in a question versus across all questions | Fast, no model download, easy to explain, top terms are readable | Matches shared words only, so "refund" and "money back" look unrelated |
| Sentence embeddings | A language model maps each question to a vector where similar meanings are close | Handles paraphrase and synonyms | Needs a model, slower, harder to explain why two questions were grouped |
For a first pass on a few thousand short questions, TF-IDF is a reasonable start because you can see why a cluster formed. If you find that obvious paraphrases land in different clusters, switch to embeddings. The rest of the workflow stays the same, because both produce a matrix with one row per question.
Step 2: Cluster and inspect
The script below clusters a small example set with k-means, then prints for each cluster its share of real demand, its top terms and the question closest to the centre. The count field is how often each question appeared before deduplication. We use it to weight the share, so a cluster's size reflects demand and not just the number of distinct wordings.
import numpy as np
from sklearn.cluster import KMeans
from sklearn.feature_extraction.text import TfidfVectorizer
rows = [
{"id": "q-01", "text": "Can I move my subscription to a different email address?", "count": 37},
{"id": "q-02", "text": "How do I change the email on my account?", "count": 52},
{"id": "q-03", "text": "How do I update my login email?", "count": 18},
{"id": "q-04", "text": "Can I change my account email without losing history?", "count": 9},
{"id": "q-05", "text": "Why was I charged twice this month?", "count": 44},
{"id": "q-06", "text": "How do I get a refund for a duplicate charge?", "count": 31},
{"id": "q-07", "text": "Where can I download my invoice?", "count": 26},
{"id": "q-08", "text": "Why is my invoice higher than last month?", "count": 15},
{"id": "q-09", "text": "How long does delivery take to Canada?", "count": 22},
{"id": "q-10", "text": "Can I track my order?", "count": 40},
{"id": "q-11", "text": "Does delivery to Canada cost extra?", "count": 12},
{"id": "q-12", "text": "My parcel has not arrived, what should I do?", "count": 19},
]
K = 3
vectorizer = TfidfVectorizer(stop_words="english", ngram_range=(1, 2))
X = vectorizer.fit_transform([r["text"] for r in rows])
model = KMeans(n_clusters=K, n_init=10, random_state=7)
labels = model.fit_predict(X)
terms = vectorizer.get_feature_names_out()
total_demand = sum(r["count"] for r in rows)
for cid in range(K):
members = np.where(labels == cid)[0]
centroid = model.cluster_centers_[cid]
top_terms = terms[centroid.argsort()[::-1][:3]]
closest = members[np.argmax(X[members] @ centroid)]
demand = sum(rows[i]["count"] for i in members)
print(f"cluster {cid}: {len(members)} questions, "
f"{demand / total_demand:.0%} of demand")
print(" top terms:", ", ".join(top_terms))
print(" closest question:", rows[closest]["text"])Three details matter here:
random_state=7makes the run repeatable, in the same way the sampling code later in this tutorial uses a fixed seed. Without it, two runs can give different groupings.n_init=10runs the algorithm from ten starting points and keeps the best result, which reduces the chance of a poor grouping caused by an unlucky start.- The closest question to the centroid is the most typical member. Reading it, plus a few random members, tells you more than the top terms alone.
The cluster numbers are arbitrary and can change between runs or data versions. Do not store 0, 1, 2 as the cluster. Give each cluster a stable name by hand.
Step 3: Choose the number of clusters
K-means needs you to pick k in advance. There is no single correct value. Use these checks together:
- Start with a rough guess based on how many product areas or help-centre categories you have.
- Try several values, such as 8, 12 and 16 on a real dataset, and read the clusters for each.
- Optionally compute a silhouette score with
sklearn.metrics.silhouette_score. It measures how well separated the clusters are. Treat it as a hint. Short questions often score low even when the clusters are useful.
Look for two failure patterns:
- Too few clusters: a cluster mixes unrelated subjects, for example "billing" and "cancellation" together. Its top terms are generic and its sample questions do not feel like one topic.
- Too many clusters: two clusters have nearly the same top terms and sample questions. Merge them.
A practical target is clusters you can describe in a short phrase, each large enough to supply at least a handful of prompts. For most product or service sets that lands between roughly 8 and 30 clusters.
Step 4: Name the clusters and store them
Read each cluster and give it a short, stable, lowercase name, such as account_management, billing_charges or delivery_tracking. Keep a small mapping from your chosen names to a one-line description. Then write the name to each record, along with the original count. This matches the record format used throughout the tutorial:
{"id":"q-0042","text":"Can I move my subscription to a different email address?","source":"support_tickets","intent":"how_to","cluster":"account_management","count":37}The sampling step reads the cluster field and the count field directly, so get these right before moving on.
Edge cases and common errors
Questions that span two topics. "Why was I charged twice for my delivery?" is about billing and delivery. K-means assigns it to exactly one cluster. This is acceptable for sampling, because each question is counted once. Do not try to fix it by duplicating the record into both clusters, since that inflates demand. If a large share of questions are mixed, consider a separate secondary_cluster field and leave the sampler using only the primary one.
Singletons and outliers. Some questions fit nowhere, such as a one-off complaint or an off-topic message. Forcing them into a cluster pollutes it. Put them in an explicit other cluster, and review it. A large other cluster means your k is too low or your vectors are too weak, and a small one is normal. Do not silently drop these questions, because rare topics are exactly what the minimum-per-cluster rule is meant to protect.
Clusters shaped by phrasing, not subject. TF-IDF clusters can form around question openers like "how do I" or "why is". Stop-word removal helps, but if clusters track the opener, you are partly rediscovering intent. Check this by reading members from several clusters. If you see it, remove common openers from the vocabulary or move to embeddings.
Count-weighted versus distinct-question clusters. A cluster with 3 distinct questions that appeared 500 times is a big topic. Report both numbers. Use weighted demand to decide how many prompts the cluster deserves, and use distinct questions to judge whether you have enough variety to sample from.
Clusters that drift between versions. If you re-cluster from scratch when you refresh the set, last quarter's billing_charges may split or merge. Version-to-version comparisons then become unreliable. When refreshing, assign new questions to the existing clusters first (for example with model.predict on vectors made by the same fitted vectorizer) and only re-cluster when the review shows poor fit.
Over-trusting the algorithm. A cluster can look tidy statistically and still be useless. Always read it. Ten minutes of review per version is cheap compared with building a prompt set on a broken grouping.
A quick review checklist
Before you freeze the clusters, confirm each of these:
- Every cluster has a name you can explain in a short phrase.
- Each cluster's sampled questions read as one topic.
- No two clusters are near-duplicates of each other.
- The
othercluster is small, and you have read it. - Weighted demand per cluster is recorded, and the shares add up to 100%.
- Names, not numeric labels, are stored on the records.
Exercise
Your clustering run produces one cluster whose top terms are "order", "account" and "help", and whose sample questions mix cancellations, password resets and delivery delays. It holds 35% of demand. What is wrong, and what do you do next?
Show answer
The cluster is too broad. Its generic top terms and mixed sample questions show that k is too low or the vectors are too weak to separate the subjects. Re-run with a higher k (or with embeddings if paraphrases are being missed), then read the new clusters again. If cancellations, password resets and delivery delays now form separate, nameable clusters, name them and store the names on the records. Because the broad cluster held 35% of demand, leaving it as one group would have let it dominate sampling and hidden problems in the specific topics.
Exercise
Why should you store a name such as billing_charges on each record instead of the numeric label that k-means returns?
Show answer
Numeric labels are arbitrary. They can change between runs, library versions or data refreshes, so cluster 2 today may not match cluster 2 next quarter. A hand-chosen, stable name keeps the sampling step, the reports and later versions of the prompt set comparable.