Velamuvi AIAcademy
Embeddings

Lesson 6 of 8 · Using Embeddings

Clustering and Classification

Group texts by topic with k-means on embeddings, and label new texts from a few examples with nearest centroid and k-NN. Working Python, and when to use an LLM.

  • 6 min read
  • Intermediate
  • Reviewed
In this lesson you will learn
  • How clustering finds groups in unlabelled texts
  • How k-means works on embeddings
  • How to classify new texts from a few labelled examples
  • When embedding-based classification beats asking an LLM

Two jobs, one idea

Because similar texts have nearby vectors, embeddings make two classic jobs easy:

  • Clustering: you have thousands of texts and no labels. Find natural groups, such as the main topics in a pile of reviews.
  • Classification: you have a few labelled examples. Put each new text into the right category.

Clustering with k-means

Here are nine customer reviews placed by (toy) two-number embeddings:

slow deliveryarrived latecourier lost itgreat tastedelicioustoo saltyapp crashedcan't log inpayment froze
Three topics form three clouds: delivery, food and the app. k-means finds them without being told.
Try it yourselfPython
import math

# 2-number embeddings of 9 customer reviews (real ones would have hundreds of numbers)
reviews = {
    "slow delivery": [-2.0, 1.6], "arrived late": [-2.4, 2.4], "courier lost it": [-1.4, 2.9],
    "great taste": [1.5, 2.6], "delicious": [1.7, 1.8], "too salty": [1.3, 1.0],
    "app crashed": [-0.6, -1.6], "can't log in": [-1.2, -2.6], "payment froze": [0.5, -2.1],
}
names = list(reviews)

def distance(a, b):
    return math.sqrt((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2)

# k-means with k = 3: start with three reviews as the centres
centres = [reviews["slow delivery"], reviews["great taste"], reviews["app crashed"]]
for step in range(5):
    groups = [[], [], []]
    for name in names:                        # 1. assign each review to its nearest centre
        d = [distance(reviews[name], c) for c in centres]
        groups[d.index(min(d))].append(name)
    for g in range(3):                        # 2. move each centre to the middle of its group
        xs = [reviews[name][0] for name in groups[g]]
        ys = [reviews[name][1] for name in groups[g]]
        centres[g] = [sum(xs) / len(xs), sum(ys) / len(ys)]

for g in range(3):
    print(f"Group {g + 1}: {', '.join(groups[g])}")

k-means found the three topics: delivery problems, food, and app problems. With real embeddings you would cluster thousands of reviews into, say, 10 groups, then read a few from each group (or ask an LLM to name each group) to understand what customers are talking about.

Classification from a few examples

Label a handful of examples per category, average each category's vectors into a centroid, and give every new text the label of the nearest centroid.

Try it yourselfPython
import math

# A tiny, hand-made "embedding model". Each dimension is a topic.
# A real model learns thousands of dimensions from data; ours uses a word list
# so you can see exactly where the numbers come from.
TOPICS = ["travel", "food", "money", "tech", "health", "weather"]
LEXICON = {
    "flight": {"travel": 1}, "flights": {"travel": 1}, "airline": {"travel": 1},
    "plane": {"travel": 1}, "airport": {"travel": 1}, "trip": {"travel": 1},
    "holiday": {"travel": 1}, "hotel": {"travel": 1, "money": 0.3},
    "train": {"travel": 1}, "tickets": {"travel": 0.8, "money": 0.5},
    "recipe": {"food": 1}, "cook": {"food": 1}, "dinner": {"food": 1},
    "pasta": {"food": 1}, "rice": {"food": 1}, "curry": {"food": 1},
    "vegetarian": {"food": 1, "health": 0.3}, "restaurant": {"food": 1, "travel": 0.3},
    "cheap": {"money": 1}, "budget": {"money": 1}, "low-cost": {"money": 1},
    "price": {"money": 1}, "save": {"money": 1}, "salary": {"money": 1},
    "bank": {"money": 1}, "loan": {"money": 1}, "expensive": {"money": 1},
    "laptop": {"tech": 1}, "phone": {"tech": 1}, "app": {"tech": 1},
    "battery": {"tech": 1}, "wifi": {"tech": 1}, "password": {"tech": 1},
    "python": {"tech": 1}, "doctor": {"health": 1}, "sleep": {"health": 1},
    "exercise": {"health": 1}, "fever": {"health": 1}, "headache": {"health": 1},
    "diet": {"health": 1, "food": 0.5}, "rain": {"weather": 1},
    "sunny": {"weather": 1}, "forecast": {"weather": 1}, "storm": {"weather": 1},
    "umbrella": {"weather": 1}, "snow": {"weather": 1, "travel": 0.2},
}

def embed(text):
    vector = [0.0] * len(TOPICS)
    for word in text.lower().replace(",", " ").replace(".", " ").replace("?", " ").split():
        for topic, weight in LEXICON.get(word, {}).items():
            vector[TOPICS.index(topic)] += weight
    length = math.sqrt(sum(v * v for v in vector))
    if length == 0:
        return vector
    return [v / length for v in vector]          # unit length, so dot product = cosine

def cosine(a, b):
    return sum(x * y for x, y in zip(a, b))

# Labelled examples: a few tickets we have already sorted by hand
examples = {
    "travel": ["my flight was cancelled", "hotel booking problem", "train tickets refund"],
    "tech": ["the app crashes", "forgot my password", "wifi keeps dropping"],
    "money": ["charged twice on my bank card", "price went up", "loan payment question"],
}

# Classification: average each label's example vectors into one "centroid"
centroids = {}
for label in examples:
    total = [0.0] * len(TOPICS)
    for text in examples[label]:
        vector = embed(text)
        for i in range(len(total)):
            total[i] += vector[i]
    centroids[label] = [value / len(examples[label]) for value in total]

def classify(text):
    vector = embed(text)
    best_label, best_score = None, -1
    for label in centroids:
        score = cosine(vector, centroids[label])
        if score > best_score:
            best_label, best_score = label, score
    return best_label, best_score

for ticket in ["airport lounge was closed", "battery drains overnight", "salary not received", "great service, thanks"]:
    label, score = classify(ticket)
    if score < 0.3:
        label = "unsure: ask a person"
    print(f"{ticket:28} -> {label} ({score:.2f})")

"airport lounge was closed" shares no words with the travel examples, but lands in travel. "great service, thanks" matches nothing well, so it is flagged for a person rather than forced into a wrong category: the same minimum score idea as in search.

An alternative is k-nearest neighbours: instead of centroids, find the k most similar labelled examples and take a vote. It handles categories that have several distinct sub-types better, at the cost of comparing against every example.

Common mistakes

Practice exercise

Classify a new support ticket by its nearest label centroid.

Your solutionPython
import math

centroids = {
    "billing": [0.9, 0.1],
    "bugs": [0.1, 0.9],
}
new_ticket = [0.8, 0.3]

# Print the label whose centroid has the highest cosine similarity
# with new_ticket. Cosine = dot / (length * length)
Knowledge check

You have 20,000 customer reviews and no labels. What can embeddings plus k-means do for you?

Summary

  • Clustering groups unlabelled texts; classification labels new texts from examples.
  • k-means repeats two steps: assign items to the nearest centre, move centres to the average.
  • Nearest centroid and k-nearest neighbours classify new texts from a few labelled examples.
  • Use a minimum score to send unclear items to a person or an LLM.
  • Embedding-based classification is cheap, fast and consistent; LLMs handle subtle cases.

Next: visualising embeddings in two dimensions.

Finished reading? Tick it off to track your progress.