如何用 Python、TF-IDF 和凝聚式聚類將關鍵詞分組
Cluster a keyword list into topic groups with Python (TF-IDF + agglomerative clustering)
這篇教學示範如何用 scikit-learn 的 TF-IDF 和凝聚式聚類,將關鍵詞整理成主題羣組,並自動產生標籤。程式可輸出包含關鍵詞、羣組編號及標籤的 CSV,亦可按羣組彙總搜尋量或 Search Console 曝光次數。分組效果取決於詞語相似度,不能辨識同義詞,也不等同按搜尋結果聚類。
A topic cluster, in practical terms, is just a set of keywords that one page, or a small group of linked pages, can reasonably answer together. The hard part isn't the definition. It's getting there from a spreadsheet with 600 loosely related phrases in it.
Paid SEO tools can cluster keywords for you, usually by comparing search results. This post does a lighter version locally with scikit-learn: vectorise the keywords with TF-IDF, group them with agglomerative clustering, and label each cluster automatically. It won't match a results-based clustering tool, but it turns an unreadable list into a reviewable one in a few seconds.
What you'll get
A CSV with each keyword, its cluster number, and a short label made from the cluster's most important words. Sort by cluster, skim the groups, and decide which ones deserve a page.
Setup
pip install pandas scikit-learn
Your input is a CSV with at least a keyword column. An optional volume column is used later for prioritising.
Step 1: Clean the list
import pandas as pd
df = pd.read_csv("keywords.csv")
df["keyword"] = (
df["keyword"].astype(str).str.lower().str.strip()
.str.replace(r"\s+", " ", regex=True)
)
df = df[df["keyword"] != ""].drop_duplicates("keyword").reset_index(drop=True)
Lowercasing and collapsing whitespace stops "Niche Keywords" and "niche keywords" becoming two separate rows.
Step 2: Vectorise with TF-IDF
from sklearn.feature_extraction.text import TfidfVectorizer
vec = TfidfVectorizer(ngram_range=(1, 2), stop_words="english", sublinear_tf=True)
X = vec.fit_transform(df["keyword"])
# Drop keywords made only of stop words: they become all-zero vectors,
# and cosine distance is undefined for those.
nonzero = X.getnnz(axis=1) > 0
df, X = df[nonzero].reset_index(drop=True), X[nonzero]
TfidfVectorizer turns each keyword into a vector of weighted terms. ngram_range=(1, 2) includes single words and two-word phrases, which matters for keywords: "keyword research" means something different from "keyword" and "research" separately (scikit-learn TfidfVectorizer).
Step 3: Cluster without choosing the number of clusters
from sklearn.cluster import AgglomerativeClustering
model = AgglomerativeClustering(
n_clusters=None,
distance_threshold=0.7,
metric="cosine",
linkage="average",
)
df["cluster"] = model.fit_predict(X.toarray())
print(df["cluster"].nunique(), "clusters")
Two details from the AgglomerativeClustering docs matter here:
- When you set
distance_threshold,n_clustersmust beNone. That's useful, because you rarely know in advance how many topics a list contains. - Cosine distance works well for TF-IDF vectors, but it can't be used with the default
wardlinkage.averagelinkage is a sensible alternative.
The .toarray() call converts the sparse matrix to a dense one. That's fine for a few thousand keywords; for much larger lists, cluster in batches or use a different approach.
Step 4: Label each cluster
Cluster numbers aren't readable. Label each group with its highest-weighted terms:
import numpy as np
terms = vec.get_feature_names_out()
dense = X.toarray()
def label_for(cluster_id, top_n=3):
rows = np.where(df["cluster"].to_numpy() == cluster_id)[0]
weights = dense[rows].sum(axis=0)
return " / ".join(terms[weights.argsort()[::-1][:top_n]])
labels = {c: label_for(c) for c in df["cluster"].unique()}
df["label"] = df["cluster"].map(labels)
You'll get labels like customer reviews / reviews / keywords from. They're rough, but they make it obvious what each group is about.
Step 5: Prioritise clusters, not keywords
If you have a volume column, sum it per cluster. Individually tiny keywords often add up to a meaningful topic:
summary = (
df.groupby(["cluster", "label"])
.agg(keywords=("keyword", "count"),
total_volume=("volume", "sum") if "volume" in df else ("keyword", "count"))
.sort_values("total_volume", ascending=False)
.reset_index()
)
summary.to_csv("cluster_summary.csv", index=False)
df.sort_values(["cluster", "keyword"]).to_csv("keyword_clusters.csv", index=False)
Treat tool volume figures as rough estimates. Very specific phrases are often under-reported, so a cluster with many small keywords can be more valuable than its total suggests.
Feeding in your own Search Console queries
Keyword tools are only one source. Your own Search Console data is often richer, especially for specific phrases. Export the Queries table from the Performance report as CSV and append it before Step 1:
gsc = pd.read_csv("Queries.csv") # exported from Search Console
gsc = gsc.rename(columns={gsc.columns[0]: "keyword", "Impressions": "volume"})
df = pd.concat([df, gsc[["keyword", "volume"]]], ignore_index=True)
Search Console column names depend on your export language, so check them first. Using impressions as a stand-in for volume isn't the same as search volume, but it reflects real demand your site already sees, which is often more useful for prioritising.
Tuning the threshold
distance_threshold controls how strict the grouping is:
- Lower (e.g. 0.5): tighter clusters, more of them, and more single-keyword clusters.
- Higher (e.g. 0.85): looser clusters, fewer of them, with a higher risk of unrelated phrases being grouped.
Start around 0.7, read ten clusters, and adjust. If obviously different needs share a cluster, lower it. If near-identical phrasings sit in separate clusters, raise it.
Limits worth knowing
- Words, not meaning. TF-IDF compares wording. "cheap accountant" and "affordable bookkeeper" may not cluster together even though the need is similar. Sentence-embedding models handle synonyms better, at the cost of an extra dependency.
- Words, not search results. Two keywords can share words but need different pages ("seo course" vs "seo service"). Results-based clustering catches that; this doesn't. Always check a sample of clusters against the live results.
- Single-keyword clusters. These are often worth keeping: they can be unique questions that deserve an FAQ entry rather than a page.
Reviewing clusters before you trust them
Automated clusters are a first draft. Before turning one into a brief, run three quick checks:
- Read every keyword in the cluster. If any one of them would need a different page, move it out.
- Search the two most different keywords in the cluster. If the top results are largely the same pages, one page can probably serve both. If they're completely different, split the cluster.
- Name the need in a sentence. If you can't describe what the whole cluster wants in one sentence, it's too broad.
These checks take a few minutes per cluster and catch most of the cases where shared words hide different intents.
Where this fits
Clustering is one step in a bigger process: finding phrases from customer language, qualifying them on intent and difficulty, then mapping clusters to pages. If you're building that process from scratch, this is a sensible companion read: a step-by-step method for finding niche keywords.
Run the script on your list, review the ten biggest clusters by hand, and you'll have the outline of a content plan by the end of the afternoon.
This article was drafted with AI assistance and reviewed by the Prox Digital Agency team. Test the code in your own environment before relying on it.
來源:DEV Community · dev.to