Finding Common Topics

machine learning
Published

February 10, 2025

How do you find thematic clusters in a large corpus of text documents? The techniques baked into sklearn (e.g. nonnegative matrix factorization, LDA) give you some intuition about common themes. But contemporary NLP has largely moved on from bag-of-words representations. We can do better with LLMs!

For demonstration purposes, I’ll use a few categories from the standard 20-newsgroups dataset. Ideally, we should be able to recover the four categories in the dataset (atheism, computer graphics, space and religion).

import json
import numpy as np
import requests
from sklearn.datasets import fetch_20newsgroups
from sklearn.cluster import KMeans
from pydantic import BaseModel, Field
import pandas as pd
from IPython.display import Markdown
categories = [
    "alt.atheism",
    "talk.religion.misc",
    "comp.graphics",
    "sci.space",
]

dataset = fetch_20newsgroups(
    remove=("headers", "footers", "quotes"),
    subset="all",
    categories=categories,
    shuffle=True,
    random_state=42,
)

Some of the documents in the dataset are only a few words; I only want to deal with documents that are least a couple hundred characters. At the other end, a handful are rambling enough to blow past the context window, so I truncate each one to its first 500 words.

X = np.array([" ".join(d.split()[:500])
              for d in dataset.data if len(d.strip()) > 200])

First, I’ll map each document to its embedding using the open Gemma-embed model. It’s currently running on llama.cpp at port 8002

EMBEDDING_URI = "http://localhost:8002"
def get_embeddings(X, batch_size=64):
    vecs = []
    for i in range(0, len(X), batch_size):
        resp = requests.post(f"{EMBEDDING_URI}/v1/embeddings",
                             json={"input": list(X[i:i + batch_size])}, timeout=120)
        resp.raise_for_status()
        vecs.extend(d["embedding"] for d in resp.json()["data"])
    vecs = np.array(vecs)
    return vecs / np.linalg.norm(vecs, axis=1, keepdims=True)

Next, I’ll cluster the embeddings with the standard k-means algorithm. There’s far more sophisticated clustering techniques in sklearn, but this should be sufficient for the toy problem.

def get_clusters(embeddings):
    neural_kmeans = KMeans(n_clusters=4, n_init=25)
    neural_kmeans.fit(embeddings)
    docs_per_label = pd.DataFrame({'labels': neural_kmeans.labels_}).value_counts()
    return neural_kmeans, docs_per_label

Finally, I’ll take a random set of documents closest to the center of each cluster and ask Gemma to find a title for the collection.

def top_per_cluster(X, embeddings, kmeans, k=25, m=8):
    return [np.random.choice(
        X[kmeans.labels_ == i][np.argsort(((embeddings[kmeans.labels_ == i]
                                                - c)**2).sum(axis=-1))[:k]], m)
        for i, c in enumerate(kmeans.cluster_centers_)]

I’ll let the LLM contemplate common themes to itself before deciding on a title. llama.cpp will happily constrain its own sampler to a JSON schema, so I can ask for both fields at once and get them back parsed.

CHAT_URI = "http://localhost:8001"
class SampleAnalysis(BaseModel):
    analysis: str = Field(description='Analysis of the texts.')
    category: str = Field(description='Category of the cluster.')
SYSTEM = """
Your task is to understand why the given documents were assigned to the same cluster.
- First analyze the documents in the cluster for common topics.
- Then, propose a short category name for the cluster containing these documents based on the analysis."""

def llama_summarize(strs):
    resp = requests.post(f"{CHAT_URI}/v1/chat/completions", timeout=300, json={
        "messages": [{"role": "system", "content": SYSTEM}]
                    + [{"role": "user", "content": s} for s in strs],
        "temperature": 0,
        "response_format": {"type": "json_schema", "json_schema":
                            {"name": "analysis",
                             "schema": SampleAnalysis.model_json_schema()}}})
    resp.raise_for_status()
    return SampleAnalysis(**json.loads(resp.json()["choices"][0]["message"]["content"]))

Let’s try it out!

def get_topics(X):
    embeddings = get_embeddings(X)
    neural_kmeans, docs_per_label = get_clusters(embeddings)
    top_embeddings = top_per_cluster(X, embeddings, neural_kmeans)
    results = [llama_summarize([a for a in t]) for t in top_embeddings]
    return pd.DataFrame({
        'category': [r.category for r in results],
        'n_docs': [int(docs_per_label[a]) for a in range(len(docs_per_label))]
    }).sort_values(by='n_docs', ascending=False)
Markdown(get_topics(X).to_markdown())
category n_docs
2 Computer Graphics and Visualization 726
1 Philosophy of Religion and Belief Systems 704
3 Space Program Strategy and Technology 670
0 War Ethics and Political Philosophy 557

Sounds about right!