结合无监督聚类任务与 Scikit-LLM

作者:Iván Palomares Carrascosa,KDnuggets 技术内容专家,2026 年 11 月 27 日,语言模型栏目
传统的无监督文本聚类方法通常生成的簇群是以数学方式、相当"匿名"的方式定义的。很多时候,我们还背负着额外的负担:需要基于人工关键词检查来猜测每个簇群背后的主题。
本文提出一种替代性的动手实践方法:借助 Scikit-LLM 由大语言模型(LLM)驱动的摘要工具,配合本地文本嵌入,我们构建了一个两阶段流程,它可以:
基于深层语义而非像 TF-IDF 等经典方法那样基于词语重叠来对文本文档进行聚类
在 Scikit-LLM 所封装的预训练 LLM 文本摘要能力辅助下,为每个簇群自动生成丰富、可读性强的标签
我们即将构建的这一方案零成本,即便在 notebook 环境中也易于运行。
构建两阶段主题发现流程
本示例可以完全在 Google Colab notebook 中运行。它使用 Groq 的 LLM API,从而完全依赖免费模型。前置条件是访问 Groq 网站、注册并生成你自己的 API 密钥。生成后,请仔细复制你的 API 密钥(它只显示一次),并在 Google Colab 中将其添加为新的"Secret"——可在 Colab 左侧的钥匙图标下找到。在那里粘贴你复制的 API 密钥,并将该 secret 命名为 GROQ_API_KEY。
之后,我们通过安装 Scikit-LLM 和 sentence-transformers 来开始我们的 notebook:
!pip install scikit-llm sentence-transformers -q
现在,让我们开始编写 Python 代码。第一步是配置 Scikit-LLM 相关的环境,把我们的请求路由到 Groq 的 API,而不是默认的 OpenAI API。这样,我们就能利用 Groq 免费层的预训练模型,并避免按 Token 计费。
from google.colab import userdata from skllm.config import SKLLMConfig # Routing to Groq's free-tier OpenAI-compatible endpoint groq_key = userdata.get('GROQ_API_KEY') SKLLMConfig.set_gpt_url("https://api.groq.com/openai/v1") SKLLMConfig.set_openai_key(groq_key)
接下来,我们获取一些真实数据。现实世界的无监督学习场景假设数据在收集时并不带有干净的类别标签。我们通过 scikit-learn 的 fetch_20newsgroups() 函数,从公开可用的 20 Newsgroups 数据集中加载几百篇帖子,并且不使用它们附带的标签,以此模拟这一用例。我们专门选取三个主题的文档:太空、汽车和计算机图形,这样我们就能大致评估我们的流水线从发现的聚类中提取主题的效果,而这些主题应当与这三个原始标签相似。
这里的另一个重要步骤是进行一些基本的“数据清洗”,去除以极短文档形式存在的噪声——这类文档缺乏明确的主题语义——否则这些离群文档可能会劫持我们的聚类结果:
from sklearn.datasets import fetch_20newsgroups categories = ['sci.space', 'rec.autos', 'comp.graphics'] dataset = fetch_20newsgroups( subset='train', categories=categories, remove=('headers', 'footers', 'quotes'), random_state=42 ) # 在抽取 300 篇文档样本之前,过滤掉空字符串和过短的残留内容(噪声数据) X_unlabeled = [doc for doc in dataset.data if len(doc.strip()) > 50][:300] print(f"已加载 {len(X_unlabeled)} 篇干净的无标签文档用于聚类。")
下一步是构建两阶段流水线,从语义聚类阶段开始。借助 sentence-transformers,特别是轻量级本地嵌入模型 all-MiniLM-L6-v2,我们将原始文本转换为嵌入向量;然后将其传入 k=3 的 k-means 聚类算法,以根据语义相似度找出分组:
from sentence_transformers import SentenceTransformer from sklearn.base import BaseEstimator, TransformerMixin from sklearn.pipeline import Pipeline from sklearn.cluster import KMeans # 1. 为 Sentence Transformers 创建自定义 Scikit-learn 包装器 # 这让我们可以将本地、零成本的嵌入模型直接放入管道 class LocalSemanticEmbedder(BaseEstimator, TransformerMixin): def __init__(self, model_name='all-MiniLM-L6-v2'): self.model_name = model_name self.model = None def fit(self, X, y=None): # 仅在拟合开始时加载模型 self.model = SentenceTransformer(self.model_name) return self def transform(self, X): # 将原始文本转换为稠密语义向量 return self.model.encode(X) # 2. 语义聚类管道 # 嵌入器负责语义;KMeans 对生成的空间坐标进行分组。 clustering_pipeline = Pipeline([ ('embedder', LocalSemanticEmbedder()), ('clusterer', KMeans(n_clusters=3, random_state=42, n_init=10)) ]) # 基于深层语义相似度(嵌入)而非重叠关键词(例如 TF-IDF)对 300 篇文档进行分组 cluster_assignments = clustering_pipeline.fit_predict(X_unlabeled)
管道的后半部分正是 Scikit-LLM 发挥所长之处。一旦我们将文档分成三个聚类,就把由 Groq 提供服务的预训练 LLM 包装进一个 GPTSummarizer 对象,这让我们可以要求模型“命名”这些聚类。出于效率考虑并避免 API Token 限制,我们没有使用整个数据集,而是从每个聚类中随机抽取 10 篇文档并截断,假设这样能给模型提供足够真实的画面,以区分不同主题:
import random from skllm.models.gpt.text2text.summarization import GPTSummarizer # 为 LLM 准备具有代表性的样本以供阅读 cluster_samples = [""] * 3 for i in range(3): # 找出所有分配给聚类 'i' 的文档 docs_in_cluster = [X_unlabeled[j] for j in range(len(X_unlabeled)) if cluster_assignments[j] == i] # 打乱顺序并随机选取 10 篇文档,以捕捉该聚类的真实多样性 random.shuffle(docs_in_cluster) diverse_sample = docs_in_cluster[:10] # 截断至 300 个字符,以符合 API 限制并聚焦核心内容 truncated_docs = [doc[:300].replace('\n', ' ') + "..." for doc in diverse_sample if len(doc.strip()) > 20] cluster_samples[i] = "\n---\n".join(truncated_docs) # 初始化摘要器,以提取简洁有力的准确标题 theme_extractor = GPTSummarizer( model="custom_url::openai/gpt-oss-20b", max_words=10 ) # 为匿名聚类生成人类可读的标签 cluster_themes = theme_extractor.fit_transform(cluster_samples) print("\n--- AI 生成的聚类主题 ---") for i, theme in enumerate(cluster_themes): print(f"聚类 {i} 规模:{list(cluster_assignments).count(i)} 篇文档。") print(f"聚类 {i} 主题:{theme.strip()}") print("-" * 70)
--- AI 生成的聚类主题 --- 聚类 0 规模:130 篇文档。聚类 0 主题:航天轶事、迷思与无关闲聊的混合内容。 ---------------------------------------------------------------------- 聚类 1 规模:87 篇文档。聚类 1 主题:关于图形软件、格式转换与设计问题的论坛帖。 ---------------------------------------------------------------------- 聚类 2 规模:83 篇文档。聚类 2 主题:购车建议、保养维护与各种奇特的汽车轶事。 ----------------------------------------------------------------------
作为首次尝试,这已经不错了!这条流水线成功地将原始、未标注的文本重新映射回它们原本(被视为未知)的类别,准确率尚可。例如,聚类 0 基本把原本属于 sci.space 类别的文档子集单独分离了出来,同时也以论坛闲聊的形式,温和地承认了原始数据混乱的现实。
总体来看,这些结果表明,这种混合式、轻量化的策略按预期奏效。话虽如此,在第一阶段使用语义文本嵌入,对后续的 Scikit-LLM 摘要器干净利落地完成工作而言,被证明是必不可少的。如果改用 TF-IDF 这类基于关键词的文本表示,最终结果很可能会更差,因为它们无法捕捉底层语境,而且容易被重叠词汇“带偏”——比如“engines”这个词,在关于汽车和航天飞机的讨论中都很常见。文本嵌入能更有效地处理这些细微差别。
我们为话题发现构建的这种基于聚类与 LLM 驱动摘要的混合方法,在稳健的机器学习基础与将预训练 LLM 同 Scikit-LLM 进行实用集成之间取得了理想的平衡。此外,在这一过程中,我们在本地完成了语义排序这项繁重工作。
Iván Palomares Carrascosa 是 AI、机器学习、深度学习与 LLM 领域的领军人物、作家、演讲者和顾问。他培训并指导他人在现实世界中运用 AI。
译文由英文原文机器翻译,术语按行业惯例统一,可在文末展开原文核对。
查看英文原文(Blending Unsupervised Clustering Tasks with Scikit-LLM)
By Iván Palomares Carrascosa, KDnuggets Technical Content Specialist on November 27, 2026 in Language Models

Traditional approaches for unsupervised text clustering usually produce groups that are defined in a mathematical, rather "anonymous" way. More often than not, we have the extra burden of guessing the underlying themes characterizing each cluster based on manual keyword inspection.
This article proposes an alternative, hands-on approach: aided by Scikit-LLM's summarization tools fueled by large language models (LLMs) alongside local text embeddings, we build a two-stage pipeline that:
Clusters text documents based on deep meaning rather than overlapping terms, as TF-IDF and other classical methods do
Automatically generates rich, human-readable labels for each cluster, aided by a pre-trained LLM for text summarization wrapped by Scikit-LLM
The solution we are about to build is cost-free and easy to run even in a notebook environment.
Building a Two-Stage Topic Discovery Pipeline
This example can be run entirely in a Google Colab notebook. It uses Groq's LLM API to rely fully on free models. A prerequisite is to visit the Groq website, register, and generate your own API key. Once it is generated, carefully copy your API key (it is shown only once) and add it as a new "Secret" in Google Colab — found under the key icon on the left-hand side of Colab. There, paste your copied API key and name the secret GROQ_API_KEY.
After that, we start our notebook by installing Scikit-LLM and sentence-transformers:
!pip install scikit-llm sentence-transformers -q
Now, let's start writing our Python code. The first step is to configure the environment surrounding Scikit-LLM, routing our requests through Groq's API instead of the default OpenAI API. This way, we can leverage Groq's free-tier pre-trained models and avoid per-token costs.
from google.colab import userdata
from skllm.config import SKLLMConfig
# Routing to Groq's free-tier OpenAI-compatible endpoint
groq_key = userdata.get('GROQ_API_KEY')
SKLLMConfig.set_gpt_url("https://api.groq.com/openai/v1")
SKLLMConfig.set_openai_key(groq_key)
Next, we get some real data. Real-world unsupervised learning scenarios assume data are gathered without clean category tags. We simulate this use case by loading a few hundred posts from the publicly available 20 Newsgroups dataset, using scikit-learn's fetch_20newsgroups() function, without their associated labels. We specifically target documents from three topics: space, automobiles, and computer graphics, so that we can broadly assess how well our pipeline extracts topics from discovered clusters that resemble these three original labels.
Another important step here is applying some basic "data hygiene" and removing noise in the form of extremely short documents without clear topic semantics — these outlier documents might otherwise hijack our clustering results:
from sklearn.datasets import fetch_20newsgroups
categories = ['sci.space', 'rec.autos', 'comp.graphics']
dataset = fetch_20newsgroups(
subset='train',
categories=categories,
remove=('headers', 'footers', 'quotes'),
random_state=42
)
# Filtering out empty strings and tiny remnants (noisy data) before taking our 300-document sample
X_unlabeled = [doc for doc in dataset.data if len(doc.strip()) > 50][:300]
print(f"Loaded {len(X_unlabeled)} clean, unlabeled documents for clustering.")
The next step is building the two-stage pipeline, starting with a semantic clustering phase. Aided by sentence-transformers, in particular the lightweight, local embedding model all-MiniLM-L6-v2, we convert raw texts into embedding vectors; then we pass them to a k-means clustering algorithm with k=3 to find groups based on semantic similarity:
from sentence_transformers import SentenceTransformer
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.pipeline import Pipeline
from sklearn.cluster import KMeans
# 1. CREATING A CUSTOM SCIKIT-LEARN WRAPPER FOR SENTENCE TRANSFORMERS
# This allows us to drop a local, zero-cost embedding model directly into the pipeline
class LocalSemanticEmbedder(BaseEstimator, TransformerMixin):
def __init__(self, model_name='all-MiniLM-L6-v2'):
self.model_name = model_name
self.model = None
def fit(self, X, y=None):
# Load the model only when fitting begins
self.model = SentenceTransformer(self.model_name)
return self
def transform(self, X):
# Convert raw text into dense semantic vectors
return self.model.encode(X)
# 2. SEMANTIC CLUSTERING PIPELINE
# The embedder handles the meaning; KMeans groups the resulting spatial coordinates.
clustering_pipeline = Pipeline([
('embedder', LocalSemanticEmbedder()),
('clusterer', KMeans(n_clusters=3, random_state=42, n_init=10))
])
# Grouping the 300 documents based on profound semantic similarity (embeddings) rather than overlapping keywords (e.g. TF-IDF)
cluster_assignments = clustering_pipeline.fit_predict(X_unlabeled)
The second half of the pipeline is where Scikit-LLM comes into its own. Once we have separated the documents into three clusters, we wrap a pre-trained LLM served by Groq in a GPTSummarizer object, which allows us to ask the model to "name" the clusters. For the sake of efficiency and to avoid API token limits, instead of using the whole dataset, 10 documents are randomly sampled from each cluster and truncated, assuming this will give the model a realistic enough picture to discern between topics:
import random
from skllm.models.gpt.text2text.summarization import GPTSummarizer
# Preparing representative samples for the LLM to read
cluster_samples = [""] * 3
for i in range(3):
# Find all documents assigned to cluster 'i'
docs_in_cluster = [X_unlabeled[j] for j in range(len(X_unlabeled)) if cluster_assignments[j] == i]
# Shuffling and picking 10 random documents to capture the cluster's true diversity
random.shuffle(docs_in_cluster)
diverse_sample = docs_in_cluster[:10]
# Truncating to 300 characters to stay within API limits and focus on core content
truncated_docs = [doc[:300].replace('\n', ' ') + "..." for doc in diverse_sample if len(doc.strip()) > 20]
cluster_samples[i] = "\n---\n".join(truncated_docs)
# Initializing the summarizer to extract a punchy, accurate title
theme_extractor = GPTSummarizer(
model="custom_url::openai/gpt-oss-20b",
max_words=10
)
# Generating human-readable labels for the anonymous clusters
cluster_themes = theme_extractor.fit_transform(cluster_samples)
print("\n--- AI-GENERATED CLUSTER THEMES ---")
for i, theme in enumerate(cluster_themes):
print(f"Cluster {i} Size: {list(cluster_assignments).count(i)} documents.")
print(f"Cluster {i} Theme: {theme.strip()}")
print("-" * 70)
--- AI-GENERATED CLUSTER THEMES ---
Cluster 0 Size: 130 documents.
Cluster 0 Theme: Mixed spaceflight anecdotes, myths, and unrelated chatter.
----------------------------------------------------------------------
Cluster 1 Size: 87 documents.
Cluster 1 Theme: Forum posts about graphics software, conversion, and design queries.
----------------------------------------------------------------------
Cluster 2 Size: 83 documents.
Cluster 2 Theme: Car buying tips, maintenance, and quirky automotive anecdotes.
----------------------------------------------------------------------
Not bad for a first attempt! The pipeline managed to map raw, unlabeled texts back to their original (treated as unknown) categories with a reasonable level of accuracy. For instance, cluster 0 largely isolated the subset of documents that originally belonged to the sci.space category, while gently acknowledging the messy reality of the raw data in the form of forum chatter.
Overall, these results show that the hybrid, lightweight strategy works as intended. That said, using semantic text embeddings in the first stage turned out to be essential for the subsequent Scikit-LLM summarizer to do its job neatly. Using keyword-based text representations like TF-IDF would likely have yielded poorer final results, due to their inability to capture underlying context and a tendency to be "distracted" by overlapping vocabulary — like the word "engines", which is common in discussions about both cars and space shuttles. Text embeddings handle these nuances much more effectively.
The hybrid approach we built for topic discovery based on clustering and LLM-driven summarization strikes an ideal balance between robust machine learning basics and practical integration of pre-trained LLMs with Scikit-LLM. Moreover, along the way, we handled the heavy lifting of semantic sorting locally.
Iván Palomares Carrascosa is a leader, writer, speaker, and adviser in AI, machine learning, deep learning & LLMs. He trains and guides others in harnessing AI in the real world.
原文为英文,正文由自动抓取并保留原文。
原文发布于 KDnuggets(Blending Unsupervised Clustering Tasks with Scikit-LLM),标题、摘要与正文由机器翻译,术语按行业惯例统一,未经人工逐句校订。