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
2686 0
基于Bert的文本聚类工具:BERTopic
|
机器学习/深度学习 自然语言处理 算法
文本分析-使用jieba库进行中文分词和去除停用词(附案例实战)
文本分析-使用jieba库进行中文分词和去除停用词(附案例实战)
11713 145
|
5月前
|
数据采集 算法 量子技术
大模型应用:隐私优先的大模型应用:同态加密与大模型结合的完整实践.101
本文深入浅出解析“同态加密+大模型”技术:以全同态加密(FHE)为核心,实现敏感数据(如金融、医疗信息)在密文状态下完成大模型推理,全程不暴露明文,兼顾隐私与智能。涵盖原理、流程、数学基础及Python简易实现。
555 6
|
7月前
|
消息中间件 缓存 NoSQL
秒杀系统高并发核心优化与落地全指南
本文系统阐述秒杀系统架构设计:剖析瞬时高并发、库存超卖等核心痛点,提出漏斗过滤、读写分离、强一致性等设计原则;详解前端、Nginx、网关、业务、缓存、消息队列及数据库七层优化方案;并给出Redis预扣减+异步落库等生产级解决方案与完整代码实现。
879 3
|
7月前
|
人工智能 Linux API
阿里云计算巢+本地全平台部署OpenClaw攻略:Skills集成+千问/Coding Plan API一站式配置指南
在AI智能体工具日趋普及的2026年,OpenClaw(曾用名Clawdbot)凭借轻量化运行、Skills插件化扩展、多平台无缝兼容的优势,成为个人与小型团队搭建专属AI助理的优选方案。相较于传统云服务器手动部署,阿里云计算巢提供了**一键自动化部署、环境预配置、运维可视化**的云端方案,无需手动处理复杂依赖,大幅降低部署门槛;同时本地三大操作系统也支持极简脚本安装,兼顾隐私需求与离线使用场景。
1585 1
|
7月前
|
Python
使用 Python 实现 Word 文档文本格式化全解析
周一早九点,领导催改50页合同格式?别再手动滚动了!用Python+python-docx库,2秒自动完成公司名加粗红色、段落对齐、标题样式等批量排版。掌握Document-Paragraph-Run三层结构,轻松搞定Word自动化,解放双手,专注真正重要的事。(239字)
776 0
|
机器学习/深度学习 自然语言处理 数据可视化
28_主题建模详解:从LDA到BERTopic - 深度解析与教学
主题建模(Topic Modeling)是自然语言处理(NLP)领域的核心技术之一,旨在从大量非结构化文本中自动发现潜在的主题结构和语义模式。随着大语言模型的崛起,主题建模技术也在不断演进,从传统的统计方法到基于深度学习的高级模型,为文本理解、信息检索、舆情分析等任务提供了强大的技术支撑。
2306 0
|
自然语言处理 算法 数据可视化
NLP-基于bertopic工具的新闻文本分析与挖掘
这篇文章介绍了如何使用Bertopic工具进行新闻文本分析与挖掘,包括安装Bertopic库、加载和预处理数据集、建立并训练主题模型、评估模型性能、分类新闻标题、调优聚类结果的详细步骤和方法。
NLP-基于bertopic工具的新闻文本分析与挖掘