在 python 中获取 sklearn 中的簇大小
Get the cluster size in sklearn in python
我正在使用 sklearn DBSCAN 对我的数据进行如下聚类。
#Apply DBSCAN (sims == my data as list of lists)
db1 = DBSCAN(min_samples=1, metric='precomputed').fit(sims)
db1_labels = db1.labels_
db1n_clusters_ = len(set(db1_labels)) - (1 if -1 in db1_labels else 0)
#Returns the number of clusters (E.g., 10 clusters)
print('Estimated number of clusters: %d' % db1n_clusters_)
现在我想根据大小(每个集群中的数据点数)对前 3 个集群进行排序。请让我知道如何在 sklearn 中获取簇大小?
你可以 Bincount Function in Numpy to get the frequencies of labels. For example, we will use the example for DBSCAN 使用 scikit-learn:
#Store the labels
labels = db.labels_
#Then get the frequency count of the non-negative labels
counts = np.bincount(labels[labels>=0])
print counts
#Output : [243 244 245]
然后使用 argsort in numpy 获得前 3 个值。在我们的示例中,由于只有 3 个集群,我将提取前 2 个值:
top_labels = np.argsort(-counts)[:2]
print top_labels
#Output : [2 1]
#To get their respective frequencies
print counts[top_labels]
另一种选择是使用 numpy.unique
:
db1_labels = db1.labels_
labels, counts = np.unique(db1_labels[db1_labels>=0], return_counts=True)
print labels[np.argsort(-counts)[:3]]
我正在使用 sklearn DBSCAN 对我的数据进行如下聚类。
#Apply DBSCAN (sims == my data as list of lists)
db1 = DBSCAN(min_samples=1, metric='precomputed').fit(sims)
db1_labels = db1.labels_
db1n_clusters_ = len(set(db1_labels)) - (1 if -1 in db1_labels else 0)
#Returns the number of clusters (E.g., 10 clusters)
print('Estimated number of clusters: %d' % db1n_clusters_)
现在我想根据大小(每个集群中的数据点数)对前 3 个集群进行排序。请让我知道如何在 sklearn 中获取簇大小?
你可以 Bincount Function in Numpy to get the frequencies of labels. For example, we will use the example for DBSCAN 使用 scikit-learn:
#Store the labels
labels = db.labels_
#Then get the frequency count of the non-negative labels
counts = np.bincount(labels[labels>=0])
print counts
#Output : [243 244 245]
然后使用 argsort in numpy 获得前 3 个值。在我们的示例中,由于只有 3 个集群,我将提取前 2 个值:
top_labels = np.argsort(-counts)[:2]
print top_labels
#Output : [2 1]
#To get their respective frequencies
print counts[top_labels]
另一种选择是使用 numpy.unique
:
db1_labels = db1.labels_
labels, counts = np.unique(db1_labels[db1_labels>=0], return_counts=True)
print labels[np.argsort(-counts)[:3]]