如何在一个kmeans之后描述每个组?

2024-05-15 12:34:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我做了一个Kmeans算法并绘制了结果。一切都很顺利,但我想知道哪些人在哪一组。有没有一种方法(以及它是什么)让个人从一个特定的群体? 谢谢你的回答


Tags: 方法算法绘制群体kmeans
2条回答

你的问题不清楚

Here are the assumptions with respect to your questions,

  1. You want to get the label for the given data-point
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)

现在定义一个函数来提取标签,使用numpy

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

现在使用相同的函数检索标签

ClusterIndices(1, km.labels_)
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])

获取数据点

X[ClusterIndicesNumpy(1,km.labels_)]
array([[5.1, 3.5, 1.4, 0.2],
       [4.9, 3. , 1.4, 0.2],
       [4.7, 3.2, 1.3, 0.2],
       [4.6, 3.1, 1.5, 0.2],
       [5. , 3.6, 1.4, 0.2],
       [5.4, 3.9, 1.7, 0.4],
       [4.6, 3.4, 1.4, 0.3],
       [5. , 3.4, 1.5, 0.2],
       [4.4, 2.9, 1.4, 0.2],
       [4.9, 3.1, 1.5, 0.1],...[4.8, 3. , 1.4, 0.3],
   [5.1, 3.8, 1.6, 0.2],
   [4.6, 3.2, 1.4, 0.2],
   [5.3, 3.7, 1.5, 0.2],
   [5. , 3.3, 1.4, 0.2]])

下面是我如何解决类似任务的:

import matplotlib.pyplot as plt
colors = ["g", "r", "m", "c", "y", "k"]

for i in range(len(feature_coords)):
    plt.scatter(feature_coords[i][0], feature_coords[i][1], c=colors[kmeans.labels_[i]], s=10)

plt.title('Clusterization of the topics')
plt.show()

相关问题 更多 >