python - 如何在基于密度的聚类中获取属于其聚类的文档?
问题描述
感谢这篇文章,我对文本文档使用 DBSCAN 聚类如下。
db = DBSCAN(eps=0.3, min_samples=2).fit(X)
core_samples_mask1 = np.zeros_like(db1.labels_, dtype=bool)
core_samples_mask1[db1.core_sample_indices_] = True
labels1 = db1.labels_
现在我想看看哪个文档属于哪个集群,比如:
[I have a car and it is blue] belongs to cluster0
或者
idx [112] belongs to cluster0
我的问题在这里提出的类似方式,但我已经测试了那里提供的一些答案:
X[labels == 1,:]
我得到了:
array([[0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0]], dtype=int64)
但这对我没有帮助。如果您有任何建议或方法,请告诉我。
解决方案
如果您有一个带有和df
列的 pandas 数据框,那么您所要做的就是idx
messages
df['cluster'] = db.labels_
为了获得cluster
具有集群成员资格的新列。
这是一个带有虚拟数据的简短演示:
import numpy as np
import pandas as pd
from sklearn.cluster import DBSCAN
X = np.array([[1, 2], [5, 8], [2, 3],
[8, 7], [8, 8], [2, 2]])
db = DBSCAN(eps=3, min_samples=2).fit(X)
db.labels_
# array([0, 1, 0, 1, 1, 0], dtype=int64)
# convert our numpy array to pandas:
df = pd.DataFrame({'Column1':X[:,0],'Column2':X[:,1]})
print(df)
# result:
Column1 Column2
0 1 2
1 5 8
2 2 3
3 8 7
4 8 8
5 2 2
# add new column with the belonging cluster:
df['cluster'] = db.labels_
print(df)
# result:
Column1 Column2 cluster
0 1 2 0
1 5 8 1
2 2 3 0
3 8 7 1
4 8 8 1
5 2 2 0
推荐阅读
- c# - dot net core(pomelo mysql provider)中的mysql - 无法访问已处置的对象
- python - sys.stdin.readline 的问题
- c# - myItem.Id,这是跨系统唯一的吗
- android - 使用同一行中最大长度的文本更新 SQLite 列
- html - babylonjs 场景边框的小问题
- mysql - 数据仓库逻辑模型
- python - 不能使用带下标的赋值表达式
- python - 如何在 txt 文件中使用 pandas.DataFrame.to_csv 保存二维数组
- python - 在 Python 中操作列表中的一些值
- autohotkey - 为什么我的代码在最后打印双“k”?自动热键 (ahk)