Python sklearn-KMeans如何获取集群中的值

时间:2016-03-24 07:56:09

标签: python scikit-learn k-means

我正在使用sklearn.cluster KMeans包。一旦我完成聚类,如果我需要知道哪些值组合在一起我该怎么办呢?

说我有100个数据点,KMeans给了我5个集群。现在我想知道集群5中有哪些数据点。我该怎么做。

是否有一个函数来提供集群ID,它将列出该集群中的所有数据点

感谢。

6 个答案:

答案 0 :(得分:21)

我有类似的要求,我正在使用pandas创建一个新数据框,其中包含数据集的索引和标签作为列。

data = pd.read_csv('filename')

km = KMeans(n_clusters=5).fit(data)

cluster_map = pd.DataFrame()
cluster_map['data_index'] = data.index.values
cluster_map['cluster'] = km.labels_

一旦DataFrame可用,很容易过滤, 例如,过滤集群3中的所有数据点

cluster_map[cluster_map.cluster == 3]

答案 1 :(得分:6)

如果您有大型数据集,并且需要按需提取群集,则可以使用numpy.where查看某些加速。以下是iris数据集的示例:

from sklearn.cluster import KMeans
from sklearn import datasets
import numpy as np

centers = [[1, 1], [-1, -1], [1, -1]]
iris = datasets.load_iris()
X = iris.data
y = iris.target

km = KMeans(n_clusters=3)
km.fit(X)

定义一个函数来提取您提供的cluster_id的索引。 (这里有两个函数,对于基准测试,它们都返回相同的值):

def ClusterIndicesNumpy(clustNum, labels_array): #numpy 
    return np.where(labels_array == clustNum)[0]

def ClusterIndicesComp(clustNum, labels_array): #list comprehension
    return np.array([i for i, x in enumerate(labels_array) if x == clustNum])

我们假设您想要群集2中的所有样本:

ClusterIndicesNumpy(2, km.labels_)
array([ 52,  77, 100, 102, 103, 104, 105, 107, 108, 109, 110, 111, 112,
       115, 116, 117, 118, 120, 122, 124, 125, 128, 129, 130, 131, 132,
       134, 135, 136, 137, 139, 140, 141, 143, 144, 145, 147, 148])

Numpy赢得了基准:

%timeit ClusterIndicesNumpy(2,km.labels_)

100000 loops, best of 3: 4 µs per loop

%timeit ClusterIndicesComp(2,km.labels_)

1000 loops, best of 3: 479 µs per loop

现在,您可以提取所有群集2数据点,如下所示:

X[ClusterIndicesNumpy(2,km.labels_)]

array([[ 6.9,  3.1,  4.9,  1.5], 
       [ 6.7,  3. ,  5. ,  1.7],
       [ 6.3,  3.3,  6. ,  2.5], 
       ... #truncated

仔细检查上面截断数组的前三个索引:

print X[52], km.labels_[52]
print X[77], km.labels_[77]
print X[100], km.labels_[100]

[ 6.9  3.1  4.9  1.5] 2
[ 6.7  3.   5.   1.7] 2
[ 6.3  3.3  6.   2.5] 2

答案 2 :(得分:2)

您可以查看属性labels_

例如

km = KMeans(2)
km.fit([[1,2,3],[2,3,4],[5,6,7]])
print km.labels_
output: array([1, 1, 0], dtype=int32)

正如您所见,第一个和第二个点是群集1,群集0中的最后一个点。

答案 3 :(得分:2)

实际上,一种非常简单的方法是:

set.seed(1)

sam<-rnorm(1000,m,s)

mean(sam)

summary(replicate(100,mean(rnorm(1000,m,s))))

cumean<-function(x) cumean(x) / seq_along(x)

plot(cumean(sam), type="l", xlab="Sample", ylab="Cumulative mean",
     panel.first=abline(h=0, col="red"), las=1,axes = F)

第二行返回属于第clusters=KMeans(n_clusters=5) df[clusters.labels_==0] 个簇的df的所有元素。同样,您可以找到其他集群元素。

答案 4 :(得分:1)

要获取每个群集内的点/样本/观察的ID,请执行以下操作:

使用Iris数据和一种不错的pythonic方式的示例:

import numpy as np
from sklearn.cluster import KMeans
from sklearn import datasets

np.random.seed(0)

# Use Iris data
iris = datasets.load_iris()
X = iris.data
y = iris.target

# KMeans with 3 clusters
clf =  KMeans(n_clusters=3)
clf.fit(X,y)

#Coordinates of cluster centers with shape [n_clusters, n_features]
clf.cluster_centers_
#Labels of each point
clf.labels_

# Nice Pythonic way to get the indices of the points for each corresponding cluster
mydict = {i: np.where(clf.labels_ == i)[0] for i in range(clf.n_clusters)}

# Transform this dictionary into list (if you need a list as result)
dictlist = []
for key, value in mydict.iteritems():
    temp = [key,value]
    dictlist.append(temp)

<强>结果

{0: array([ 50,  51,  53,  54,  55,  56,  57,  58,  59,  60,  61,  62,  63,
            64,  65,  66,  67,  68,  69,  70,  71,  72,  73,  74,  75,  76,
            78,  79,  80,  81,  82,  83,  84,  85,  86,  87,  88,  89,  90,
            91,  92,  93,  94,  95,  96,  97,  98,  99, 101, 106, 113, 114,
           119, 121, 123, 126, 127, 133, 138, 142, 146, 149]),
 1: array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16,
           17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33,
           34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
 2: array([ 52,  77, 100, 102, 103, 104, 105, 107, 108, 109, 110, 111, 112,
           115, 116, 117, 118, 120, 122, 124, 125, 128, 129, 130, 131, 132,
           134, 135, 136, 137, 139, 140, 141, 143, 144, 145, 147, 148])}


[[0, array([ 50,  51,  53,  54,  55,  56,  57,  58,  59,  60,  61,  62,  63,
             64,  65,  66,  67,  68,  69,  70,  71,  72,  73,  74,  75,  76,
             78,  79,  80,  81,  82,  83,  84,  85,  86,  87,  88,  89,  90,
             91,  92,  93,  94,  95,  96,  97,  98,  99, 101, 106, 113, 114,
             119, 121, 123, 126, 127, 133, 138, 142, 146, 149])],
 [1, array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16,
            17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33,
            34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49])],
 [2, array([ 52,  77, 100, 102, 103, 104, 105, 107, 108, 109, 110, 111, 112,
             115, 116, 117, 118, 120, 122, 124, 125, 128, 129, 130, 131, 132,
             134, 135, 136, 137, 139, 140, 141, 143, 144, 145, 147, 148])]]

答案 5 :(得分:0)

您可以将标签存储在一个数组中。将数组转换为数据框。然后合并您用于创建K的数据表示具有群集的新数据框。

显示数据框。现在您应该看到具有相应群集的行。如果要列出具有特定群集的所有数据,请使用data.loc [data [&#39; cluster_label_name&#39;] == 2]之类的内容,假设现在为2个群集。