embedding做HDBSCAN

目标,发掘文本噪音

import numpy as np
import hdbscan
import matplotlib.pyplot as plt
import seaborn as sns
import umap

# 1. 读取 embedding 数据
X = np.load("your_embedding.npy")  # 替换成你的路径

# 2. 使用 HDBSCAN 进行聚类
clusterer = hdbscan.HDBSCAN(min_cluster_size=30, min_samples=10)
cluster_labels = clusterer.fit_predict(X)
probabilities = clusterer.probabilities_

# 3. 提取噪声样本(label = -1)
noise_mask = (cluster_labels == -1)
noise_indices = np.where(noise_mask)[0]
print(f"识别出噪声样本数量: {len(noise_indices)} / {len(X)}")

# 4. 可选:找出代表性样本(高置信度)
representative_indices = probabilities.argsort()[::-1][:100]

# 5. 用 UMAP(余弦距离)降维可视化
reducer = umap.UMAP(n_neighbors=15, min_dist=0.1)
X_2d = reducer.fit_transform(X)

# 6. 绘图
plt.figure(figsize=(10, 6))
sns.scatterplot(x=X_2d[:, 0], y=X_2d[:, 1], hue=cluster_labels, palette='tab20', s=10, legend=None)
plt.title("HDBSCAN 聚类 + 噪声识别(使用余弦距离)")
plt.show()
``` from bertopic import BERTopic from sentence_transformers import SentenceTransformer from umap import UMAP from hdbscan import HDBSCAN from bertopic.vectorizers import ClassTfidfTransformer import plotly.io as pio import pandas as pd from sklearn.feature_extraction.text import CountVectorizer from bertopic.representation import KeyBERTInspired data = pd.read_excel("数据.xlsx") # Step 1 - Embed documents embedding_model = SentenceTransformer('all-MiniLM-L12-v2') # Step 2 - Reduce dimensionality降维 # umap_model = UMAP(n_neighbors=15, n_components=5,min_dist=0.0, metric='cosine') umap_model = UMAP(n_neighbors=15, n_components=5,min_dist=0.0, metric='cosine', random_state=28) # Step 3 - Cluster reduced embeddings对降维向量聚类 hdbscan_model = HDBSCAN(min_cluster_size=15, metric='euclidean', prediction_data=True) # Step 4 - Create topic representation创造主题候选词 vectorizer_model = CountVectorizer(stop_words=None) # vectorizer_model = CountVectorizer(stop_words=["人工智能","ai","AI"]) # Step 5 - Create topic representation ctfidf_model = ClassTfidfTransformer() # Step 6 - (Optional) Fine-tune topic representations with a `bertopic.representation` model representation_model = KeyBERTInspired() # 训练bertopic主题模型 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 representations ) # 使用fit_transform对输入文本向量化,然后使用topic_model模型提取主题topics,并且计算主题文档概率probabilities filtered_text = data["内容"].astype(str).tolist() topics, probabilities = topic_model.fit_transform(filtered_text) document_info = topic_model.get_document_info(filtered_text) print(document_info) # 查看每个主题数量 topic_freq = topic_model.get_topic_freq() print(topic_freq) # 查看某个主题-词的概率分布 topic = topic_model.get_topic(0) print(topic) # 主题-词概率分布 pic_bar = topic_model.visualize_barchart() pio.show(pic_bar) # 文档主题聚类 embeddings = embedding_model.encode(filtered_text, show_progress_bar=False) pic_doc = topic_model.visualize_documents(filtered_text, embeddings=embeddings) pio.show(pic_doc) # 聚类分层 pic_hie = topic_model.visualize_hierarchy() pio.show(pic_hie) # 主题相似度热力图 pic_heat = topic_model.visualize_heatmap() pio.show(pic_heat) # 主题模排名图 pic_term_rank = topic_model.visualize_term_rank() pio.show(pic_term_rank) # 隐含主题主题分布图 pic_topics = topic_model.visualize_topics() pio.show(pic_topics) #DTM图 summary=data['内容'].astype(str).tolist() timepoint = data['时间'].tolist() timepoint = pd.Series(timepoint) print(timepoint[:10]) topics_over_time = topic_model.topics_over_time(summary, timepoint, datetime_format='mixed', nr_bins=20, evolution_tuning=True) DTM = topic_model.visualize_topics_over_time(topics_over_time, title='DTM',) pio.show(DTM)```请解释这个代码内容
03-13
已经进行切词、去除停用词、标点符号的英文专利摘要文本保存在'tokenized_abstract.csv'中,并且在静态主题建模时已经进行了加载,专利摘要对应的时间数据保存在'date.txt'中,尚未加载,已经执行的静态主题模型的参数设置如下:from sentence_transformers import SentenceTransformer # Step 1 - Extract embeddings embedding_model = SentenceTransformer("C:\\Users\\18267\\.cache\\huggingface\\hub\\models--sentence-transformers--all-mpnet-base-v2\\snapshots\\9a3225965996d404b775526de6dbfe85d3368642") embeddings = np.load('clean_emb_last.npy') print(f"嵌入的形状: {embeddings.shape}") # Step 2 - Reduce dimensionality umap_model = UMAP(n_neighbors=7, n_components=10, min_dist=0.0, metric='cosine',random_state=42) # Step 3 - Cluster reduced embeddings hdbscan_model = HDBSCAN(min_samples=7, min_cluster_size=60,metric='euclidean', cluster_selection_method='eom', prediction_data=True) # Step 4 - Tokenize topics # Combine custom stop words with scikit-learn's English stop words custom_stop_words = ['h2', 'storing', 'storage', 'include', 'comprise', 'utility', 'model', 'disclosed', 'embodiment', 'invention', 'prior', 'art', 'according', 'present', 'method', 'system', 'device', 'may', 'also', 'use', 'used', 'provide', 'wherein', 'configured', 'predetermined', 'plurality', 'comprising', 'consists', 'following', 'characterized', 'claim', 'claims', 'said', 'first', 'second', 'third', 'fourth', 'fifth', 'one', 'two', 'three','hydrogen'] # Create combined stop words set all_stop_words = set(custom_stop_words).union(ENGLISH_STOP_WORDS) vectorizer_model = CountVectorizer(stop_words=list(all_stop_words)) # Step 5 - Create topic representation ctfidf_model = ClassTfidfTransformer() # All steps together 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 top_n_words=50 )
03-15
## 软件功能详细介绍 1. **文本片段管理**:可以添加、编辑、删除常用文本片段,方便快速调用 2. **分组管理**:支持创建多个分组,不同类型的文本片段可以分类存储 3. **热键绑定**:为每个文本片段绑定自定义热键,实现一键粘贴 4. **窗口置顶**:支持窗口置顶功能,方便在其他应用程序上直接使用 5. **自动隐藏**:可以设置自动隐藏,减少桌面占用空间 6. **数据持久化**:所有配置和文本片段会自动保存,下次启动时自动加载 ## 软件使用技巧说明 1. **快速添加文本**:在文本输入框中输入内容后,点击"添加内容"按钮即可快速添加 2. **批量管理**:可以同时编辑多个文本片段,提高管理效率 3. **热键冲突处理**:如果设置的热键与系统或其他软件冲突,会自动提示 4. **分组切换**:使用分组按钮可以快速切换不同类别的文本片段 5. **文本格式化**:支持在文本片段中使用换行符和制表符等格式 ## 软件操作方法指南 1. **启动软件**:双击"大飞哥软件自习室——快捷粘贴工具.exe"文件即可启动 2. **添加文本片段**: - 在主界面的文本输入框中输入要保存的内容 - 点击"添加内容"按钮 - 在弹出的对话框中设置热键和分组 - 点击"确定"保存 3. **使用热键粘贴**: - 确保软件处于运行状态 - 在需要粘贴的位置按下设置的热键 - 文本片段会自动粘贴到当前位置 4. **编辑文本片段**: - 选中要编辑的文本片段 - 点击"编辑"按钮 - 修改内容或热键设置 - 点击"确定"保存修改 5. **删除文本片段**: - 选中要删除的文本片段 - 点击"删除"按钮 - 在确认对话框中点击"确定"即可删除
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值