【问题标题】:How to identify and separate clusters using K Means in python?如何在 python 中使用 K 均值识别和分离集群?
【发布时间】:2019-11-20 11:08:02
【问题描述】:

我正在尝试使用 K-means 方法在数据集中查找集群。我从肘部方法中获得了集群的数量,但不知道如何识别和分离这些集群以便对每个集群进行进一步分析,例如对每个集群应用线性回归。我的数据集包含两个以上的变量。

我通过肘法得到了簇的数量

应用 Kmeans

distortions = []
K = range(1,10)
for k in K:
kmeanModel = KMeans(n_clusters=k).fit(df)
kmeanModel.fit(df)
distortions.append(sum(np.min(cdist(df, kmeanModel.cluster_centers_, 'euclidean'), axis=1))**2 / df.shape[0])

簇数的肘法

plt.plot(K, distortions, 'bx-')
plt.xlabel('k')
plt.ylabel('Distortion')
plt.title('The Elbow Method showing the optimal k')
plt.show()

【问题讨论】:

    标签: python cluster-analysis linear-regression k-means unsupervised-learning


    【解决方案1】:

    假设您使用 Elbow 方法发现值 k 是您的数据的最佳聚类数。

    所以你可以使用下面的代码将数据分成不同的集群:

    kmeans = KMeans(n_clusters=k, random_state=0).fit(df)
    y = kmeans.labels_    # Will return the cluster numbers for each datapoint
    y_pred = kmeans.predict(<unknown_sample>)    # If want to predict for a new sample
    

    之后,您可以根据集群将数据分离为:

    for i in range(k):
        cluster_i = df[y == i, :]    # Subset of the datapoints that have been assigned to the cluster i
        # Do analysis on this subset of datapoints.
    

    您可以在此链接中找到与不同参数相关的更多详细信息:https://scikit-learn.org/stable/modules/generated/sklearn.cluster.KMeans.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-13
      • 2021-06-07
      • 2011-09-04
      • 2020-05-17
      • 2015-06-02
      • 1970-01-01
      • 2022-01-02
      相关资源
      最近更新 更多