Back to Tutorials
LLM Application Development
Advanced

Discover Topics with Embeddings and Clustering

Cluster 120 support tickets by meaning, live, read each cluster’s words and typical tickets, and find a problem that the ticket categories split four ways.

9 minInteractive: drag, click and try things as you read


You have a pile of text, support tickets or survey answers or reviews, and no time to read it all. Turn each piece into an embedding, group the embeddings that sit close together, and read a few from each group: the themes appear on their own, including ones nobody thought to look for. Clustering finds the groups; you still have to read them to know what they mean. Here you’ll cluster 120 real-looking tickets live, and hunt for a problem that the ticket categories hide.

Three steps#

  1. Embed each ticket with a sentence embedding model, so tickets that mean similar things get similar lists of numbers (here MiniLM, 384 numbers each).
  2. Cluster the vectors. k-means is the usual first try: you choose k, the number of groups; it places k centres, gives every ticket to its nearest centre, moves each centre to the middle of its tickets, and repeats until nothing changes.
  3. Describe each cluster: the words that are common in it but rare elsewhere, and the tickets nearest its centre, the most typical ones.

The tickets come from Hearth, a made-up smart-home company: 100 everyday ones (billing, bugs, feature requests, delivery, accounts) and 20 about something new. Since version 5.2 of the app, people keep getting signed out, and the home-screen widget stops updating. Nobody has made a category for that yet, so the people filing those tickets picked whatever seemed closest.

Predict first

The 20 tickets about the 5.2 update were each filed under one of five categories by the person who wrote it. How many different categories did they end up in?

Try it
The tickets are made up. Their embeddings are real (all-MiniLM-L6-v2, computed offline); k-means runs live in your browser on all 384 numbers, keeping the best of five random starts. The 2D map was made offline with UMAP and is only for drawing: dots close on the map are usually close in meaning.

At k = 6, five of the clusters are what you’d expect from a smart-home help desk: deliveries, charges, account access, the thermostat, and the doorbell and alarms. The biggest one is different. Its top words are “app, out, version, update”, its most typical ticket is “Updated the app yesterday and now it logs me out…”, and it holds 14 of the 20 update tickets, which people had filed as bugs, account problems and feature requests. A cluster that cuts across your categories is often the most interesting one.

Now press “Start from a different random guess” a few times. k-means only finds a good arrangement near where it starts, so the clusters shift: at k = 6, over the first 30 starts, the update cluster holds anywhere from 10 to 18 of the 20. The theme survives; the exact borders don’t. That’s normal, and it’s why you read clusters rather than treat them as facts.

How many topics are there?#

There’s no right answer for k. The usual score is the silhouette: for each ticket, how much closer it is to its own cluster than to the next nearest one, from −1 to 1. Near 1 means tight, well-separated groups; near 0 means the groups blur into each other.

Predict first

These tickets fall into fairly clear themes. What do you expect the best silhouette score to be?

Try it
The same tickets and the same live k-means (first start) for every k from 2 to 10. The silhouette score uses cosine distance between the full embeddings.

The score barely moves, so use it as a hint, not a verdict. What matters is whether the clusters are useful. At k = 2 the update tickets share a cluster of 64 that tells you nothing; at k = 9, 17 of the 20 sit together in a cluster of 20, clean enough to hand to an engineer. A common approach is to start with more clusters than you think you need, read them, and merge the ones that turn out to be the same thing.

In code#

The whole pipeline in a few lines, free and local (pip install sentence-transformers scikit-learn), on 12 of the tickets:

from collections import Counter
from sentence_transformers import SentenceTransformer
from sklearn.cluster import KMeans

tickets = [
    "My order hasn't arrived and it's been a week.", "The parcel was sent to my old address.",
    "Can you deliver on a Saturday?", "I only received two of the three bulbs I ordered.",
    "I was charged twice for Hearth Plus this month.", "Why did my subscription go up?",
    "Can I get a refund for the thermostat I returned?", "Do you take PayPal?",
    "Since the 5.2 update the app signs me out every morning.", "The new app version keeps asking for my password.",
    "My widget stopped refreshing after the app update.", "Version 5.2 forgets my login overnight.",
]
model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
vectors = model.encode(tickets, normalize_embeddings=True)
clusters = KMeans(n_clusters=3, n_init=10, random_state=0).fit_predict(vectors)

stop = {"the", "my", "i", "a", "and", "for", "it", "to", "on", "of", "was", "but", "can", "you", "me", "is", "this", "do", "why", "did", "has", "been", "its", "it's", "after", "every", "keeps", "only"}
for c in range(3):
    members = [t for t, k in zip(tickets, clusters) if k == c]
    words = Counter(w.strip("?.,'").lower() for t in members for w in t.split())
    top = [w for w, _ in words.most_common() if w not in stop][:4]
    print(f"cluster {c} ({len(members)} tickets): {', '.join(top)}  e.g. {members[0]!r}")
# cluster 0 (4 tickets): app, 5.2, update, version  e.g. 'Since the 5.2 update the app signs me out every morning.'
# cluster 1 (5 tickets): order, hasn't, arrived, week  e.g. "My order hasn't arrived and it's been a week."
# cluster 2 (3 tickets): charged, twice, hearth, plus  e.g. 'I was charged twice for Hearth Plus this month.'

Three clean themes, and one surprise: “Do you take PayPal?” landed with the deliveries, not the billing questions. On twelve tickets you can spot that at a glance; on twelve thousand, read a sample from every cluster.

What to remember

  • Embed, cluster, describe: embeddings put similar texts close together, k-means groups them, and top words plus typical examples tell you what each group is about.
  • Clusters can cut across your existing categories; here most of 20 tickets about one app update, filed under four categories, came together in one cluster.
  • There’s no correct k and the silhouette score is often low for text; try a few values and different starts, and judge clusters by reading them.

Keep going

Sign in to save your place and keep a learning streak. Free, with Google.