首页 > 解决方案 > 如何在基于密度的聚类中获取属于其聚类的文档?

问题描述

感谢这篇文章,我对文本文档使用 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)

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

标签: pythonmachine-learningscikit-learncluster-analysisdbscan

解决方案


如果您有一个带有和df列的 pandas 数据框,那么您所要做的就是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  

推荐阅读