Skip to main content

AI and machine learning · Intermediate · 30 min

Find near-duplicates and group similar text with embeddings

By Padding · Updated 18 Nov 2026
Python 3.15 · sentence-transformers 6.3 · scikit-learn 1.9 · PyTorch 2.15 (CPU)

You will take 500 support tickets, remove the resubmitted ones with a similarity threshold you chose by checking pairs yourself, and sort the rest into named groups with HDBSCAN and k-means, ready for a person to review.

On this page

Support inboxes, survey exports and feedback forms fill up with two kinds of repetition. Some messages are the same message twice: a customer who heard nothing back and sent it again, sometimes with "Hello" on the front. Others are different people describing the same kind of problem. You want to remove the first kind and count the second.

Embeddings help with both. A sentence embedding model turns each message into a vector, and messages that mean nearly the same thing get vectors that point in nearly the same direction. Pairs above a high similarity score are candidate duplicates. Messages that sit in a crowd of similar vectors form a group.

The hard part is not the code. It is deciding where "nearly the same" stops, and remembering that a clustering algorithm will always return groups, whether or not they mean anything. So this tutorial puts a person at two points: you choose the duplicate threshold by checking a sample of pairs by hand, and you name and judge the groups rather than trusting the algorithm's split.

You work on 500 generated support tickets for a mobile payments and shopping app, so every number can be checked against a known answer. The generator plants 40 resubmitted tickets and records each ticket's true topic. Your working scripts never read those answer columns; only the clearly marked check sections do. With your own data there is no answer key, which is why the hand checks matter.

Everything runs on your CPU with the open all-MiniLM-L6-v2 model (Apache 2.0). No API key, no account and no cost per call.

Step 1 · Set up the project and install the libraries

If embeddings and cosine similarity are new to you, work through turn text into embeddings and compare meaning with sentence-transformers first. This tutorial uses the same model and install.

Make a throwaway folder and a virtual environment:

Bash
mkdir -p ~/ticket-groups-demo
cd ~/ticket-groups-demo
python3 -m venv .venv
source .venv/bin/activate

Install the CPU build of PyTorch from PyTorch's own index first, so pip does not fetch the much larger GPU build, then sentence-transformers and scikit-learn:

Bash
pip install --quiet torch==2.15.0 --index-url https://download.pytorch.org/whl/cpu
pip install --quiet sentence-transformers==6.3.0 scikit-learn==1.9.1

The PyTorch download is a few hundred megabytes. On prepaid mobile data, do this step on Wi-Fi; it happens once.

Check it worked

Bash
python -c "import torch, sentence_transformers, sklearn; print(torch.__version__, sentence_transformers.__version__, sklearn.__version__)"

The output is 2.15.0+cpu 6.3.0 1.9.1.

Step 2 · Generate 500 tickets with planted resubmissions

The generator builds tickets about six problems (failed transfers, login, app crashes, refunds, deliveries and data bundles) from sentence templates with alternative wordings, so two customers with the same problem rarely write exactly the same thing. It adds a few tickets that mention two problems at once, then plants 40 resubmissions. A resubmission is an earlier ticket from the same customer, changed the way people change things when they send them again: a greeting, a typo, lower case, or a line about nobody replying.

The seed is fixed, so you get the same 500 tickets every time:

Bash
cat > make_tickets.py <<'PY'
import csv
import random
import re

rng = random.Random(42)

NAMES = ["Ada", "Tunde", "Wanjiru", "Kofi", "Amina", "Thabo", "Chidi", "Fatou",
         "Musa", "Zanele", "Yaw", "Ngozi", "Sipho", "Aisha", "Kwame", "Lerato"]
AMOUNTS = ["500", "1,200", "2,000", "3,500", "5,000", "7,500", "10,000", "15,000"]
DAYS = ["yesterday", "this morning", "on Monday", "last night", "two days ago",
        "on Friday", "an hour ago", "at the weekend"]
DEVICES = ["Tecno Spark", "Samsung A05", "Infinix Hot", "iPhone 12", "Nokia G21",
           "itel A70", "Redmi 12C", "Pixel 6a"]

# [a|b|c] is a choice of wording; {slot} is filled from the lists above.
TOPICS = {
    "transfer": [
        "I [sent|transferred|tried to send] {amount} to {name} {day} [but the money never arrived|and it has not reached them|and {name} still has nothing].",
        "My [transfer|payment] of {amount} to {name} [failed|did not go through] {day} [and I was still charged|but my balance went down|and the fee was taken anyway].",
        "[{name} says|{name} tells me] the {amount} I sent {day} [has not arrived|is not in their wallet|never came].",
        "A [payment|transfer] of {amount} to {name} has been [pending|stuck on processing] ever since I sent it {day}.",
        "[The app|Your app] took {amount} from my wallet {day} [but {name} got nothing|and the transfer shows failed].",
    ],
    "login": [
        "I [could not|was unable to] [log in|sign in|open my account] {day} because the app said my [PIN|password] was wrong.",
        "My account was [locked|blocked] after I [typed|entered] the wrong [password|PIN] {day}.",
        "The [one-time code|OTP|verification code] never [arrives|comes] by SMS, so I [cannot|can't] sign in on my {device}.",
        "I [reset|changed] my password {day} and the new one [still does not work|is rejected].",
        "After [changing|replacing] my SIM {day} I [can no longer get into|am locked out of] my account.",
    ],
    "crash": [
        "The app [closes by itself|shuts down|keeps crashing] every time I open it on my {device}.",
        "[Since|After] the update {day} the app [freezes|hangs] on the [home screen|loading screen] of my {device}.",
        "The app [crashes|closes] when I [tap|open] the [history|statements|settings] page on my {device}.",
        "My {device} shows a [blank|white|black] screen when the app [starts|opens].",
        "Every time I [scan a QR code|try to pay a merchant] the app [stops responding|shuts down] on my {device}.",
    ],
    "refund": [
        "I [want|would like|need] a refund for the order I [cancelled|returned] {day}.",
        "[Please refund|Kindly return] the {amount} for the subscription I did not renew.",
        "I [returned|sent back] the item {day} and I am still waiting for my {amount}.",
        "I was charged {amount} twice {day}, please [give back|reverse|refund] one of the payments.",
        "[You promised|I was told] my {amount} refund would take five days and it has not [come|arrived].",
    ],
    "delivery": [
        "My [parcel|order|package] was [due|meant to arrive] {day} and it [still has not been delivered|has not come].",
        "The [courier|rider|driver] marked my order as delivered {day} but [nothing came|I received nothing].",
        "The tracking [page|status] for my [order|parcel] stopped [changing|updating] {day}.",
        "My [package|parcel] arrived {day} with the box [torn|damaged] and [an item|one item|a phone case] missing.",
        "I [received|got] [someone else's order|the wrong parcel] {day} instead of mine.",
    ],
    "data": [
        "I bought a {amount} data bundle {day} and it [finished|was used up] in a few hours.",
        "My data bundle was not [added|activated] after I paid {amount} {day}.",
        "The [bundle|data plan] I bought {day} [expired|ran out] before the date you promised.",
        "Airtime of {amount} was [deducted|taken] {day} but no bundle was [activated|added].",
        "I keep getting charged for a [daily|weekly] data plan I never [subscribed to|asked for].",
    ],
}

MIXED = [
    "The app crashed on my {device} halfway through sending {amount} to {name}, and now the money is missing.",
    "I paid {amount} for a data bundle {day} and then the app would not let me log in.",
    "My parcel never arrived, so I want a refund of the {amount} I paid {day}.",
    "After the update {day} I cannot log in, and my transfer to {name} is stuck.",
    "The app froze while I was paying for delivery and I was charged {amount} twice.",
    "My data ran out while tracking my order, so I missed the rider's call {day}.",
    "I was locked out {day} and while I waited my refund of {amount} went to an old account.",
    "The app crashes on the refunds page on my {device}, so I cannot ask for my {amount} back.",
    "Sending {amount} to {name} {day} used up my whole data bundle and still failed.",
    "The rider wanted cash because the app crashed when I tried to pay {amount}.",
]

OPENERS = ["", "", "", "Good morning. ", "Dear support, ", "Please help me. ", "Hello team. "]
CLOSINGS = ["", "", " I have tried twice already.", " This is urgent.", " My number ends in {digits}.",
            " Order reference {ref}.", " I contacted you before and got no reply.",
            " I am on the latest version.", " Kindly look into it.", " This has happened before.",
            " I need this sorted today.", " What should I do?"]


def fill(template):
    choices = []

    def pick(match):
        options = match.group(1).split("|")
        n = rng.randrange(len(options))
        choices.append(n)
        return options[n]

    text = re.sub(r"\[([^\]]+)\]", pick, template)
    text = text.format(amount=rng.choice(AMOUNTS), name=rng.choice(NAMES),
                       day=rng.choice(DAYS), device=rng.choice(DEVICES))
    return text, tuple(choices)


def resubmit(text):
    style = rng.randrange(5)
    if style == 0:
        return "Hello, " + text[0].lower() + text[1:]
    if style == 1:
        return text.lower()
    if style == 2:
        return text + " Sending this again because nobody replied."
    if style == 3:
        words = text.split(" ")
        k = max(range(len(words)), key=lambda n: len(words[n]))
        w = words[k]
        words[k] = w[0] + w[2] + w[1] + w[3:]
        return " ".join(words)
    return "Hi, " + text + " Thanks."


def customer():
    return f"C{rng.randint(1000, 9999)}"


tickets, shapes = [], set()
topics = list(TOPICS)
while len(tickets) < 450:
    topic = topics[len(tickets) % len(topics)]
    frame = rng.randrange(len(TOPICS[topic]))
    body, choices = fill(TOPICS[topic][frame])
    opener, closing = rng.randrange(len(OPENERS)), rng.randrange(len(CLOSINGS))
    shape = (topic, frame, choices, closing)
    if shape in shapes:
        continue
    shapes.add(shape)
    text = OPENERS[opener] + body + CLOSINGS[closing].format(
        digits=rng.randint(1000, 9999), ref=rng.randint(100000, 999999))
    tickets.append({"text": text, "topic": topic, "customer": customer(), "dup_of": None})
for template in MIXED:
    tickets.append({"text": fill(template)[0], "topic": "mixed", "customer": customer(), "dup_of": None})
rng.shuffle(tickets)

for original in rng.sample([t for t in tickets if t["topic"] != "mixed"], 40):
    copy = {"text": resubmit(original["text"]), "topic": original["topic"],
            "customer": original["customer"], "dup_of": original}
    position = next(n for n, t in enumerate(tickets) if t is original)
    tickets.insert(rng.randint(position + 1, len(tickets)), copy)

for n, t in enumerate(tickets, 1):
    t["id"] = f"T{n:04d}"

with open("tickets.csv", "w", newline="", encoding="utf-8") as f:
    writer = csv.writer(f)
    writer.writerow(["id", "customer", "text", "topic", "dup_of"])
    for t in tickets:
        writer.writerow([t["id"], t["customer"], t["text"], t["topic"],
                         t["dup_of"]["id"] if t["dup_of"] else ""])
print("wrote", len(tickets), "tickets")
PY
python make_tickets.py

topic and dup_of are the answer key. Treat them as hidden: they exist only so you can see how well each method did.

Check it worked

Bash
head -4 tickets.csv
python -c "import csv; rows = list(csv.DictReader(open('tickets.csv', encoding='utf-8'))); print(len(rows), 'tickets,', sum(1 for r in rows if r['dup_of']), 'planted resubmissions'); assert len(rows) == 500"

The last line is 500 tickets, 40 planted resubmissions. The first rows are ordinary tickets with an id, a customer code, the text, a topic and, for most rows, an empty dup_of.

Step 3 · Embed the tickets and list the closest pairs

Put the model in one shared file. The revision pins the model files so your scores do not move if the model page changes:

Bash
cat > common.py <<'PY'
import csv

from sentence_transformers import SentenceTransformer

MODEL_ID = "sentence-transformers/all-MiniLM-L6-v2"
REVISION = "1110a243fdf4706b3f48f1d95db1a4f5529b4d41"


def load_model():
    return SentenceTransformer(MODEL_ID, revision=REVISION, device="cpu")


def read_csv(path):
    with open(path, newline="", encoding="utf-8") as f:
        return list(csv.DictReader(f))


def write_csv(path, rows):
    with open(path, "w", newline="", encoding="utf-8") as f:
        writer = csv.DictWriter(f, fieldnames=list(rows[0]))
        writer.writeheader()
        writer.writerows(rows)
PY

Embed every ticket once and save the vectors, so later steps do not recompute them. normalize_embeddings=True makes every vector length 1, so a plain dot product is the cosine similarity:

Bash
cat > embed.py <<'PY'
import numpy as np

from common import load_model, read_csv

tickets = read_csv("tickets.csv")
model = load_model()
vectors = model.encode([t["text"] for t in tickets], batch_size=64,
                       normalize_embeddings=True, show_progress_bar=False)
np.save("embeddings.npy", vectors)
print("saved", vectors.shape)
PY
python embed.py

Now score every pair. 500 tickets make 124,750 pairs, which NumPy handles in a fraction of a second. Keep only the pairs scoring 0.85 or more and write them to a file, closest first:

Bash
cat > pairs.py <<'PY'
import numpy as np

from common import read_csv, write_csv

tickets = read_csv("tickets.csv")
vectors = np.load("embeddings.npy")
scores = vectors @ vectors.T
i, j = np.triu_indices(len(tickets), k=1)
pair_scores = scores[i, j]
keep = np.argsort(-pair_scores)
keep = keep[pair_scores[keep] >= 0.85]

rows = []
for n in keep:
    a, b = tickets[i[n]], tickets[j[n]]
    rows.append({"score": f"{pair_scores[n]:.3f}", "a": a["id"], "b": b["id"],
                 "customer_a": a["customer"], "customer_b": b["customer"],
                 "text_a": a["text"], "text_b": b["text"]})
write_csv("pairs.csv", rows)

BANDS = [(0.99, 1.01), (0.97, 0.99), (0.95, 0.97), (0.92, 0.95), (0.85, 0.92)]
for low, high in BANDS:
    count = sum(1 for r in rows if low <= float(r["score"]) < high)
    print(f"{low:.2f} to {min(high, 1.0):.2f}: {count} pairs")
same_customer = [r for r in rows if r["customer_a"] == r["customer_b"]]
print(f"pairs from the same customer: {len(same_customer)}")
print("\nclosest five:")
for r in rows[:5]:
    print(r["score"], "|", r["text_a"][:60], "|", r["text_b"][:60])
assert len(rows) > 40
PY
python pairs.py

Check it worked

embed.py prints saved (500, 384): one row of 384 numbers per ticket. pairs.py prints a count for each score band, then the five closest pairs. Expect the top pairs to score 1.000 or close to it and to be obvious resubmissions: one is the other in lower case (this model's tokenizer ignores case, so those score exactly 1.000), or with "Hello," in front.

Look at the band counts. The lower bands hold far more pairs than there are planted resubmissions, so most of them must be something else. Note the count of pairs from the same customer too; you will use it in the dedupe step.

Step 4 · Choose the threshold by checking pairs yourself

A score of 0.88 does not tell you whether two tickets are the same ticket. Look at some. This script takes up to eight random pairs from each band and writes them to review.csv with an empty same column:

Bash
cat > sample_review.py <<'PY'
import random

from common import read_csv, write_csv

rng = random.Random(7)
pairs = read_csv("pairs.csv")
BANDS = [("0.99+", 0.99, 1.01), ("0.97-0.99", 0.97, 0.99), ("0.95-0.97", 0.95, 0.97),
         ("0.92-0.95", 0.92, 0.95), ("0.85-0.92", 0.85, 0.92)]
review = []
for name, low, high in BANDS:
    in_band = [p for p in pairs if low <= float(p["score"]) < high]
    for p in rng.sample(in_band, min(8, len(in_band))):
        review.append({"band": name, **p, "same": ""})
write_csv("review.csv", review)
print("wrote", len(review), "pairs to review.csv")
PY
python sample_review.py

Open review.csv in a spreadsheet or text editor. For each row, read both texts and the two customer codes, and type y in the same column if it is the same ticket sent again, or n if it is a different ticket. Use one rule and write it down. Here the rule is: same customer and same problem is y; two customers with the same kind of problem is n, because both people need an answer. Save the file as CSV.

Now read your labels back. The script works from the top band down and keeps lowering the threshold while at least 90% of the pairs you checked in a band are real duplicates. It stops at the first band that fails:

Bash
cat > choose_threshold.py <<'PY'
from common import read_csv

ORDER = [("0.99+", 0.99), ("0.97-0.99", 0.97), ("0.95-0.97", 0.95),
         ("0.92-0.95", 0.92), ("0.85-0.92", 0.85)]
rows = read_csv("review.csv")
threshold = None
for name, low in ORDER:
    labelled = [r for r in rows if r["band"] == name and r["same"].strip().lower() in ("y", "n")]
    if not labelled:
        print(f"{name}: nothing labelled, stopping")
        break
    yes = sum(1 for r in labelled if r["same"].strip().lower() == "y")
    share = yes / len(labelled)
    print(f"{name}: {yes} of {len(labelled)} are the same ticket ({share:.0%})")
    if share < 0.9:
        break
    threshold = low

if threshold is None:
    print("Even the top band has false matches. Label more pairs before removing anything.")
    threshold = 1.01
else:
    print("threshold:", threshold)
with open("threshold.txt", "w") as f:
    f.write(str(threshold))
PY
python choose_threshold.py

Check it worked

The script prints one line per band with how many of your checked pairs were real duplicates, then a threshold, and threshold.txt now holds it. Expect the top band (0.99 and above) to be all or nearly all y: copies that differ only in case or a single letter. Somewhere in the lower bands, pairs from two different customers start to appear, typically the same template sentence with a different device, amount or closing line. Same kind of problem, different ticket: those are exactly the pairs you must not delete. The threshold you get depends on where that starts: 0.99 if the 0.97 to 0.99 band already has false matches, lower if it does not. Open review.csv and check that the line the script drew matches what you saw.

Eight pairs per band is a small sample. On real data, check more pairs around the band where the share drops, and repeat the check when the kind of text changes. Short messages tend to score higher with each other than long ones, so a threshold chosen on emails may be wrong for chat messages.

Step 5 · Remove the duplicates

Use two rules. Any pair at or above your threshold is a duplicate, whoever sent it. A pair from the same customer is a duplicate at a lower score, 0.85 here, because one person rarely sends two different tickets that read almost alike. Look at the same-customer pairs in pairs.csv before you trust that lower bar on your own data; when your tickets carry a sender, an email address or a phone number, use it.

Join every duplicate pair into a group and keep the earliest ticket in each group. Grouping matters: if B repeats A and C repeats B, all three collapse to A, even if A and C score below the line.

Bash
cat > dedupe.py <<'PY'
import numpy as np

from common import read_csv, write_csv

SAME_CUSTOMER = 0.85

tickets = read_csv("tickets.csv")
vectors = np.load("embeddings.npy")
threshold = float(open("threshold.txt").read())

parent = list(range(len(tickets)))


def root(n):
    while parent[n] != n:
        parent[n] = parent[parent[n]]
        n = parent[n]
    return n


def join(a, b):
    ra, rb = root(a), root(b)
    parent[max(ra, rb)] = min(ra, rb)


scores = np.triu(vectors @ vectors.T, k=1)
by_text = by_customer = 0
for a, b in np.argwhere(scores >= SAME_CUSTOMER):
    if scores[a, b] >= threshold:
        by_text += 1
    elif tickets[a]["customer"] == tickets[b]["customer"]:
        by_customer += 1
    else:
        continue
    join(a, b)

keep = [n for n in range(len(tickets)) if root(n) == n]
removed = [n for n in range(len(tickets)) if root(n) != n]
write_csv("unique.csv", [{"id": tickets[n]["id"], "customer": tickets[n]["customer"],
                          "text": tickets[n]["text"]} for n in keep])
np.save("unique.npy", vectors[keep])
print(f"pairs joined: {by_text} by text alone (>= {threshold}), "
      f"{by_customer} more from the same customer (>= {SAME_CUSTOMER})")
print(f"kept {len(keep)}, removed {len(removed)}")

# Answer key check (generated data only)
caught = sum(1 for n in removed if tickets[n]["dup_of"])
wrong = len(removed) - caught
print(f"answer key: {caught} of 40 planted resubmissions removed, {wrong} other tickets removed")
assert caught >= 30
assert wrong <= 3
PY
python dedupe.py

Check it worked

The first line splits the joined pairs between the two rules, the second shows how many tickets were kept and removed, and the answer-key line shows how many of the 40 planted resubmissions went and how many other tickets were removed by mistake. Expect nearly all of the planted resubmissions gone and few or no mistakes, with a large share of the catches coming from the same-customer rule.

That split is the lesson of the last two steps. Text similarity alone can safely remove only near-exact copies, because two people with the same problem can write almost the same sentence. The resubmissions with a line added ("Sending this again because nobody replied.") can score lower than some pairs of different tickets; sort pairs.csv by customer to see where yours landed. In that case only the sender tells them apart.

Step 6 · Group the tickets with HDBSCAN

HDBSCAN looks for dense regions of vectors and leaves points in sparse regions unassigned, as noise with the label -1. You do not tell it how many groups to find; you tell it the smallest group worth calling a group (min_cluster_size) and how cautious to be (min_samples, where higher means more noise).

First write a helper that both clustering steps use. It names each group from its most central tickets: the ones closest to the group's average vector. Reading three central tickets tells you more about a group than its number does:

Bash
cat > describe.py <<'PY'
from collections import Counter

import numpy as np

from common import read_csv


def describe(labels, vectors, rows, examples=3):
    for group in sorted(set(labels) - {-1}):
        members = np.where(labels == group)[0]
        centre = vectors[members].mean(axis=0)
        closest = members[np.argsort(-(vectors[members] @ centre))[:examples]]
        print(f"\ngroup {group}: {len(members)} tickets")
        for n in closest:
            print("   ", rows[n]["text"][:90])
    noise = int((labels == -1).sum())
    if noise:
        print(f"\nnoise (-1): {noise} tickets")


def answer_key_purity(labels, rows):
    """Generated data only: how much of each group shares one true topic."""
    topic = {t["id"]: t["topic"] for t in read_csv("tickets.csv")}
    agree = total = 0
    for group in sorted(set(labels) - {-1}):
        counts = Counter(topic[rows[n]["id"]] for n in np.where(labels == group)[0])
        name, top = counts.most_common(1)[0]
        print(f"group {group}: {top}/{sum(counts.values())} are '{name}'")
        agree += top
        total += sum(counts.values())
    return agree / total
PY

Now cluster the deduplicated tickets:

Bash
cat > group_hdbscan.py <<'PY'
import numpy as np
from sklearn.cluster import HDBSCAN

from common import read_csv
from describe import answer_key_purity, describe

rows = read_csv("unique.csv")
vectors = np.load("unique.npy")
labels = HDBSCAN(min_cluster_size=15, min_samples=5, copy=True).fit_predict(vectors)
np.save("labels_hdbscan.npy", labels)

groups = len(set(labels) - {-1})
print(f"HDBSCAN found {groups} groups and {(labels == -1).sum()} noise tickets")
describe(labels, vectors, rows)

print("\nAnswer key (generated data only):")
purity = answer_key_purity(labels, rows)
print(f"purity: {purity:.0%}")
assert groups >= 3
PY
python group_hdbscan.py

On unit-length vectors, the Euclidean distance HDBSCAN uses by default ranks pairs in the same order as cosine similarity, so there is no need to change the metric.

Check it worked

The first line gives the number of groups and how many tickets were left as noise. Under each group you see its size and three central tickets; read them and you can name the group in a few words ("money sent but not received", "app crashes on start"). The purity line shows how much of each group shares one true topic.

The exact counts depend on the data and settings; expect several groups and a noticeable share of noise, and two things that are not bugs. Some topics come out as two or three groups, because tickets built from one template sit very close to each other: data bundles, for example, may split into "bundle used up or not added", "airtime taken, no bundle" and "charged for a plan I never asked for". A person would probably keep those apart too. And a good share of the tickets can land in noise, often including tickets that mention two problems. HDBSCAN is telling you it is not sure, which is useful information. Raise min_cluster_size for fewer, broader groups; lower min_samples for less noise.

Step 7 · Group the same tickets with k-means

k-means needs the number of groups up front and puts every ticket in exactly one, with no noise. A common way to pick the number is to try several and compare silhouette scores, which run from -1 to 1 and measure how much closer each ticket is to its own group than to the next one:

Bash
cat > group_kmeans.py <<'PY'
import numpy as np
from sklearn.cluster import KMeans
from sklearn.metrics import adjusted_rand_score, silhouette_score

from common import read_csv
from describe import answer_key_purity, describe

rows = read_csv("unique.csv")
vectors = np.load("unique.npy")

results = {}
for k in range(3, 11):
    labels = KMeans(n_clusters=k, n_init=10, random_state=0).fit_predict(vectors)
    results[k] = (silhouette_score(vectors, labels, metric="cosine"), labels)
    print(f"k={k}: silhouette {results[k][0]:.3f}")

best = max(results, key=lambda k: results[k][0])
labels = results[best][1]
np.save("labels_kmeans.npy", labels)
print(f"\nbest k by silhouette: {best}")
describe(labels, vectors, rows)

hdb = np.load("labels_hdbscan.npy")
clustered = hdb != -1
print(f"\nagreement with HDBSCAN on its non-noise tickets (adjusted Rand): "
      f"{adjusted_rand_score(hdb[clustered], labels[clustered]):.2f}")

print("\nAnswer key (generated data only):")
purity = answer_key_purity(labels, rows)
print(f"purity: {purity:.0%}")
assert purity >= 0.6
PY
python group_kmeans.py

Check it worked

You see eight silhouette scores, the best k, and the central tickets of each k-means group. The scores are likely to be low and close together. That is common for sentence embeddings, and it means the "best" k is a weak preference, not a fact about your data. The best k may well differ from the six true topics; if it is higher, read the central tickets to see which topic was split into more than one group. Change range(3, 11) to range(5, 8) and look at how the groups merge and split as k changes.

The adjusted Rand score compares the two methods on the tickets both of them grouped: 1 means identical groupings, 0 means no better than chance. The score can come out high or quite low: when HDBSCAN splits one topic into several template groups and k-means splits it differently, the methods disagree even though both groupings make sense. Read the central tickets of both before deciding which split is more useful. The comparison leaves out the tickets HDBSCAN called noise, where k-means had to choose.

Step 8 · Hand the groups to a person

Neither result is an answer. Each is a list of suggestions for someone who knows the product. Before you hand them over, look at the tickets the methods are least sure about. The ten tickets that mention two problems are a good place to start:

Bash
cat > for_review.py <<'PY'
import numpy as np

from common import read_csv, write_csv

rows = read_csv("unique.csv")
vectors = np.load("unique.npy")
hdb = np.load("labels_hdbscan.npy")
km = np.load("labels_kmeans.npy")

# Answer key (generated data only): find the tickets that mention two problems
topic = {t["id"]: t["topic"] for t in read_csv("tickets.csv")}
print("tickets that mention two problems:")
for n, r in enumerate(rows):
    if topic[r["id"]] == "mixed":
        print(f"  hdbscan {hdb[n]:>2}  kmeans {km[n]:>2}  {r['text'][:70]}")

sheet = []
for group in sorted(set(km)):
    members = np.where(km == group)[0]
    centre = vectors[members].mean(axis=0)
    closest = members[np.argsort(-(vectors[members] @ centre))[:3]]
    sheet.append({"group": int(group), "tickets": len(members),
                  "example_1": rows[closest[0]]["text"],
                  "example_2": rows[closest[1]]["text"],
                  "example_3": rows[closest[2]]["text"],
                  "name": "", "keep_merge_or_split": "", "notes": ""})
write_csv("groups_for_review.csv", sheet)
print(f"\nwrote {len(sheet)} groups to groups_for_review.csv")
assert len(sheet) >= 3
PY
python for_review.py

Check it worked

The script lists the ten two-problem tickets with the group each method gave them. HDBSCAN is likely to mark several of them -1; k-means puts every one in some group, which looks tidier and is less honest: a ticket about a crash during a transfer now counts as only one of those problems. Then groups_for_review.csv holds one row per k-means group, with three example tickets and empty name, keep_merge_or_split and notes columns for the reviewer.

That empty sheet is the deliverable. A person names each group, merges groups that are the same problem for the business, splits ones that hide two, and reads the noise tickets, which is where new problems tend to appear first. Then count tickets per named group, not per cluster number. If you need consistent labels across months, move from clustering to a classifier trained on the groups your reviewer settled on: see classify text cheaply with embeddings and logistic regression.

A note on language: this model was trained on English. If your tickets mix English with Pidgin, Swahili, Yoruba, Hausa or French, vectors for those messages are much less reliable, and they may drift into noise or the wrong group. Try sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2 (also Apache 2.0) and repeat the hand check on pairs in each language before you trust its threshold.

Step 9 · Clean up

Remove the project folder and the cached model. Keep the cache if you are going on to another embeddings tutorial, to save the download:

Bash
deactivate
cd ~
rm -rf ~/ticket-groups-demo ~/.cache/huggingface/hub/models--sentence-transformers--all-MiniLM-L6-v2
ls ~/ticket-groups-demo 2>/dev/null || echo "removed"

Check it worked

The last command prints removed.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

AI-Integrated Solutions

Get new tutorials

New tutorials, about twice a month.