kmeans散点图:每个簇绘制不同的颜色

时间:2015-01-30 00:36:37

标签: python numpy matplotlib scipy k-means

我正在尝试做一个kmeans输出的散点图,它将同一主题的句子聚合在一起。我面临的问题是将属于每个群集的点绘制成某种颜色。

sentence_list=["Hi how are you", "Good morning" ...] #i have 10 setences
km = KMeans(n_clusters=5, init='k-means++',n_init=10, verbose=1) 
#with 5 cluster, i want 5 different colors
km.fit(vectorized)
km.labels_ # [0,1,2,3,3,4,4,5,2,5]

pipeline = Pipeline([('tfidf', TfidfVectorizer())])
X = pipeline.fit_transform(sentence_list).todense()
pca = PCA(n_components=2).fit(X)
data2D = pca.transform(X)
plt.scatter(data2D[:,0], data2D[:,1])

km.fit(X)
centers2D = pca.transform(km.cluster_centers_)
plt.hold(True)
labels=np.array([km.labels_])
print labels

我的问题出现在 plt.scatter()的底部代码中;我应该使用什么参数 c

  1. 当我在代码中使用c=labels时,我收到此错误:
  2. number in rbg sequence outside 0-1 range

    2.当我设置c= km.labels_时,我收到错误:

    ValueError: Color array must be two-dimensional

    plt.scatter(centers2D[:,0], centers2D[:,1], 
                marker='x', s=200, linewidths=3, c=labels)
    plt.show()
    

3 个答案:

答案 0 :(得分:11)

from sklearn.cluster import KMeans
import matplotlib.pyplot as plt

# Scaling the data to normalize
model = KMeans(n_clusters=5).fit(X)

# Visualize it:
plt.figure(figsize=(8, 6))
plt.scatter(data[:,0], data[:,1], c=model.labels_.astype(float))

现在,不同群集的颜色不同。

答案 1 :(得分:5)

color=c=属性应为matplotlib颜色,如plot文档中所述。

要将整数标签映射到颜色,只需执行

LABEL_COLOR_MAP = {0 : 'r',
                   1 : 'k',
                   ....,
                   }

label_color = [LABEL_COLOR_MAP[l] for l in labels]
plt.scatter(x, y, c=label_color)

如果您不想使用内置的单字符颜色名称,则可以使用其他颜色定义。请参阅matplotlib颜色的文档。

答案 2 :(得分:0)

应该有效:

from sklearn.cluster import KMeans;
cluster = KMeans(10);
cluster.fit(M);

cluster.labels_;

plt.scatter(M[:,0],M[:,1], c=[matplotlib.cm.spectral(float(i) /10) for i in cluster.labels_]);   
相关问题