在 python 中使用 kmeans sklearn 聚类数据点

Cluster datapoints using kmeans sklearn in python

我正在使用以下 python 代码使用 kmeans 对我的数据点进行聚类。

data =  np.array([[30, 17, 10, 32, 32], [18, 20, 6, 20, 15], [10, 8, 10, 20, 21], [3, 16, 20, 10, 17], [3, 15, 21, 17, 20]])
kmeans_clustering = KMeans( n_clusters = 3 )
idx = kmeans_clustering.fit_predict( data )

#use t-sne
X = TSNE(n_components=2).fit_transform( data )

fig = plt.figure(1)
plt.clf()

#plot graph
colors = np.array([x for x in 'bgrcmykbgrcmykbgrcmykbgrcmyk'])
plt.scatter(X[:,0], X[:,1], c=colors[kmeans_clustering.labels_])
plt.title('K-Means (t-SNE)')
plt.show()

然而,我得到的簇图是错误的,因为我把所有的东西都集中在一个点上。

因此,请让我知道我的代码哪里出错了?我想在我的散点图中单独查看 kmeans 聚类。

编辑

我得到的t-sne值如下。

[[  1.12758575e-04   9.30458337e-05]
 [ -1.82559784e-04  -1.06657936e-04]
 [ -9.56485652e-05  -2.38951623e-04]
 [  5.56515580e-05  -4.42453191e-07]
 [ -1.42039677e-04  -5.62548119e-05]]

使用TSNEperplexity参数。 perplexity 的默认值是 30,这对你的情况来说似乎太多了,即使文档指出 TSNE 对此参数非常不敏感。

The perplexity is related to the number of nearest neighbors that is used in other manifold learning algorithms. Larger datasets usually require a larger perplexity. Consider selecting a value between 5 and 50. The choice is not extremely critical since t-SNE is quite insensitive to this parameter.

X = TSNE(n_components=2, perplexity=2.0).fit_transform( data )

您也可以使用 PCA(主成分分析)代替 t-SNE 来绘制您的集群:

import numpy as np
import pandas as pd  
from sklearn.cluster import Kmeans
from sklearn.decomposition import PCA

data =  np.array([[30, 17, 10, 32, 32], [18, 20, 6, 20, 15], [10, 8, 10, 20, 
21], [3, 16, 20, 10, 17], [3, 15, 21, 17, 20]])
kmeans = KMeans(n_clusters = 3)
labels = kmeans.fit_predict(data)    

pca = PCA(n_components=2)
data_reduced = pca.fit_transform(data)
data_reduced = pd.DataFrame(data_reduced)

ax = data_reduced.plot(kind='scatter', x=0, y=1, c=labels, cmap='rainbow')
ax.set_xlabel('PC1')
ax.set_ylabel('PC2')
ax.set_title('Projection of the clustering on a the axis of the PCA')

for x, y, label in zip(data_reduced[0], data_reduced[1], kmeans.labels_):
    ax.annotate('Cluster {0}'.format(label), (x,y))