如何在基于密度的聚类中获取属于其簇的文档?

How to obtain the documents that belongs to its cluster in density based clustering?

我对文本文档使用 DBSCAN 聚类,如下所示, 感谢 this post.

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

与我在 here 中提出的问题类似,但我已经测试了那里提供的一些答案:

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)

但这对我没有帮助。如果您有任何建议或方法,请告诉我。

如果您有一个 pandas 数据框 df,其中包含列 idxmessages,那么您所要做的就是

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