BERTopic(一)基本用法

简介: bertopic基本用法

文档 https://maartengr.github.io/BERTopic/algorithm/algorithm.html 提供了基本流程。

Document embeddings
克服了bag-of-words "disregard semantic relationships among words"的缺点

from sentence_transformers import SentenceTransformer
embedding_model = SentenceTransformer("DMetaSoul/Dmeta-embedding")
# 计算嵌入比较慢,可以pre-calculate
embeddings = embedding_model.encode(docs, show_progress_bar=True)

Document clustering
使用umap降维,使用hdbscan聚类
使用hdbscan的原因是"a cluster will not always lie within a sphere around a cluster centroid"

from umap import UMAP
from hdbscan import HDBSCAN

umap_model = UMAP(n_neighbors=15, n_components=5, min_dist=0.0, metric='cosine', random_state=42)
hdbscan_model = HDBSCAN(min_cluster_size=15, metric='euclidean', cluster_selection_method='eom', prediction_data=True)

参数n_neighbors和min_cluster_size相当于调整一个cluster的大小,n_components相当于输出的维度

Topic Representation
这部分是核心,分为vectorize、c-TF-IDF和fine-tune三部分
对于中文,需要分词

from sklearn.feature_extraction.text import CountVectorizer
import jieba

def tokenize_zh(text):
    words = jieba.lcut(text)
    return words

# by increasing the n-gram range we will consider topic representations that are made up of one or two words.
vectorizer = CountVectorizer(tokenizer=tokenize_zh, ngram_range=(1, 3))

The classic TF-IDF procedure combines two statistics, term frequency, and inverse document frequency. We generalize this procedure to clusters of documents. First, we treat all documents in a cluster as a single document by simply concatenating the documents. Then, TF-IDF is adjusted to account for this representation by translating documents to clusters.

from bertopic.vectorizers import ClassTfidfTransformer

ctfidf_model = ClassTfidfTransformer()
from bertopic.representation import KeyBERTInspired

# Create your representation model
# KeyBERTInspired可以减少stop words
representation_model = KeyBERTInspired()

然后把模型组装起来,训练模型

topic_model = BERTopic(
  embedding_model=embedding_model,          # Step 1 - Extract embeddings
  umap_model=umap_model,                    # Step 2 - Reduce dimensionality
  hdbscan_model=hdbscan_model,              # Step 3 - Cluster reduced embeddings
  vectorizer_model=vectorizer_model,        # Step 4 - Tokenize topics
  ctfidf_model=ctfidf_model,                # Step 5 - Extract topic words
  representation_model=representation_model, # Step 6 - (Optional) Fine-tune topic represenations
  verbose=True
)

topics, probs = topic_model.fit_transform(docs,
  embeddings # pre-calculate
)

看看生成了哪些主题

topic_model.get_topic_info()

topic_model.get_topic(0)

最后可视化一下吧

topic_model.visualize_topics()

topic_model.visualize_heatmap()

还可以保存和加载模型

topic_model.save("path/to/my/model_dir", serialization="safetensors", save_ctfidf=True, save_embedding_model=embedding_model)

loaded_model = BERTopic.load("path/to/my/model_dir")
相关文章
|
数据可视化 数据挖掘
基于Bert的文本聚类工具:BERTopic
基于Bert的文本聚类工具:BERTopic
2536 0
基于Bert的文本聚类工具:BERTopic
|
机器学习/深度学习 自然语言处理 算法
文本分析-使用jieba库进行中文分词和去除停用词(附案例实战)
文本分析-使用jieba库进行中文分词和去除停用词(附案例实战)
10869 145
|
7月前
|
机器学习/深度学习 自然语言处理 数据可视化
28_主题建模详解:从LDA到BERTopic - 深度解析与教学
主题建模(Topic Modeling)是自然语言处理(NLP)领域的核心技术之一,旨在从大量非结构化文本中自动发现潜在的主题结构和语义模式。随着大语言模型的崛起,主题建模技术也在不断演进,从传统的统计方法到基于深度学习的高级模型,为文本理解、信息检索、舆情分析等任务提供了强大的技术支撑。
1706 0
|
人工智能 缓存 Cloud Native
DeepSeek-R1 来了,从 OpenAI 平滑迁移到 DeepSeek的方法
Higress 作为一款开源的 AI 网关工具,可以提供基于灰度+观测的平滑迁移方案。
2399 250
|
自然语言处理 算法 数据可视化
NLP-基于bertopic工具的新闻文本分析与挖掘
这篇文章介绍了如何使用Bertopic工具进行新闻文本分析与挖掘,包括安装Bertopic库、加载和预处理数据集、建立并训练主题模型、评估模型性能、分类新闻标题、调优聚类结果的详细步骤和方法。
NLP-基于bertopic工具的新闻文本分析与挖掘
|
PyTorch 调度 算法框架/工具
阿里云PAI-DLC任务Pytorch launch_agent Socket Timeout问题源码分析
DLC任务Pytorch launch_agent Socket Timeout问题源码分析与解决方案
592 18
阿里云PAI-DLC任务Pytorch launch_agent Socket Timeout问题源码分析
|
人工智能 JSON 自然语言处理
Jina Reader:一键将网页内容转为适合 LLM 处理的文本格式,自动抓取和清洗网页内容,支持多种输出格式
Jina Reader 是一款由 Jina AI 推出的开源工具,能够将网页内容快速转换为适合大型语言模型(LLMs)处理的纯文本格式,支持多种输出格式和动态内容处理。
3229 20
Jina Reader:一键将网页内容转为适合 LLM 处理的文本格式,自动抓取和清洗网页内容,支持多种输出格式