首页 > 解决方案 > Python k-mean,质心放置在集群之外

问题描述

我正在尝试使用 k-means 算法对混合数据进行聚类:chemical_1chemical_2-数值,season-分类。season为了在 K-means 算法中使用它,一列被转换为假人。

我已经添加了集群中心,plt.scatter(centers[:,0], centers[:,1], marker="x", color='r')但它把它们放在了错误的位置,在集群之外。
我应该如何处理kmeans.cluster_centers_才能正确绘制它们?

在此处输入图像描述

#Make a copy of DF
df_transformed = df

#Transform the 'season' to dummies
df_transformed = pd.get_dummies(df_transformed, columns=['season'])

#Standardize
columns = ['chemical_1', 'chemical_2', 'season_winter', 'season_spring', 'season_autumn', 'season_summer']
df_tr_std = stats.zscore(df_transformed[columns])

#Cluster the data
kmeans = KMeans(n_clusters=4).fit(df_tr_std)
labels = kmeans.labels_
centers = np.array(kmeans.cluster_centers_)

#Glue back to original data
df_transformed['clusters'] = labels

#Add the column into our list
columns.extend(['clusters'])

#Analyzing the clusters
print(df_transformed[columns].groupby(['clusters']).mean())

          chemical_1  chemical_2  season_winter  season_spring  season_autumn  \
clusters                                                                        
0           7.951500   10.600500              0              0              1   
1           8.119180    8.818852              1              0              0   
2           8.024423    8.009615              0              1              0   
3           7.939432    9.414773              0              0              0   

          season_summer  
clusters                 
0                     0  
1                     0  
2                     0  
3                     1

#Scatter plot of chemical_1 and chemical_2
sns.lmplot('chemical_1', 'chemical_2', 
           data=df_transformed,
           size = 10,
           fit_reg=False, 
           hue="clusters",  
           scatter_kws={"marker": "D", 
                        "s": 100}
          )
plt.scatter(centers[:,0], centers[:,1], marker="x", color='r')

plt.title('Clusters chemical_1 vs chemical_2')
plt.xlabel('chemical_1')
plt.ylabel('chemical_2')
plt.show

UPD:我尝试使用 PCA 进行转换。这是正确的方法吗?另外,我只能用 matplotlib 绘制数据。在这里使用 seaborn 的正确方法是什么?

pca = PCA(n_components=2, whiten=True).fit(df_tr_std)

#Cluster the data
kmeans = KMeans(n_clusters=4)
kmeans.fit(df_tr_std)
labels = kmeans.labels_
centers = pca.transform(kmeans.cluster_centers_)

plt.scatter(df_tr_std[:,0], df_tr_std[:,1])
plt.scatter(centers[:,0], centers[:,1], marker="x", color='r')

现在散点图如下所示:

标签: pythonpandascluster-analysis

解决方案


如果您对 z 分数进行聚类,则生成的中心也将是 z 分数。

Kmeans 显然无法将它们映射回您的旧坐标系 - 您必须自己做。

由于 z 分数变换是一个简单的线性变换,因此可以直接重新创建该函数逆变换。


推荐阅读