DEV Community

Santiago Alvarez
Santiago Alvarez

Posted on Edited on

Semantic and zero-shot topic classification with embeddings

Day Topic Example Status
1 Talking to an LLM from code Classifying emails by category and urgency ✅ Code
2 Roles, examples and delimiters in prompts Translating technical language into plain language ✅ Code
3 Structured output with JSON, validated with Pydantic Turning a chat order into a table ✅ Code
4 Images with vision models Scanning a receipt and returning a JSON with the products and the total ✅ Code
5 Embeddings: meaning as numbers Assigning a topic to each news headline 📍 You're here

Day 5: Zero-shot topic classification with embeddings

Zero-shot topic classification is an NLP technique that assigns topics to text without training on labeled examples for those topics first. Embeddings turn text into vectors (lists of numbers) that capture its meaning.

The goal: assign the right topic to each headline.

I used the model SentenceTransformer("all-MiniLM-L6-v2").

THRESHOLD = 0.10 is the minimum score needed to accept a topic. If the best score is below it, the result is marked as unclear.

The following image shows the topics dictionary and the headlines list:

Topics dictionary and headlines list

model.encode() only accepts a string or a list, so it's a good practice to convert the topics dictionary into lists: I get the names with .keys() and the descriptions with .values().

The function similarity() receives a headline and calculates the cosine similarity between the headline embedding and each topic embedding. Then it picks the top score and compares it with the THRESHOLD. That way, we only keep the topic that best fits the headline.

def similarity(headline: str) -> None:
    """Print the Topic closest in meaning to the headlines"""

    headline_embedding = model.encode(headline)

    scores = util.cos_sim(headline_embedding, topic_embeddings)[0]  # One score per topic

    best = scores.argsort(descending=True)  # descending order or best similarities

    print(f"\n>>> {headline}")

    winner = best[0]  # POSITION of the winning topic
    winner_score = scores[winner]  # its score

    if winner_score > THRESHOLD:
        print(f"{winner_score:.2f} {topic_names[winner]}")
    else:
        print(f"{winner_score:.2f}  unclear")
Enter fullscreen mode Exit fullscreen mode

Results

It finds the best match for each headline:

Each headline with its best topic and score

One headline, "Star striker signs a record-breaking contract", was classified as unclear because its score was below 0.10. It probably doesn't fit any of my topics well.

What I learned

  • The model runs locally and isn't trained on my topics, so if I want to cover more cases, I just add more topics to the dictionary.
  • Without the if and the selection of the winner, it would print the scores for every topic.
  • An embedding turns text into a vector, and cos_sim() measures how similar two vectors are. The words don't have to be identical. That's the trick here: it compares meaning, not words.

👉 Full code: day5_topic_classifier.py

Top comments (0)