2013-11-22 48 views
1

我想绘制3“k表示”散点图中的点。在散点图上计算k平均值和绘图

from pylab import plot,show 
from numpy import array 
from scipy.cluster.vq import kmeans,vq 

data = array([1,1,1,1,1,1,3,3,3,3,3,3,7,7,7,7,7,7]) 
plot(data,marker='*',linewidth=0) 

centroids,x = kmeans(data,3) 
idx,x = vq(data,centroids) 

plot(data[idx==0,0],data[idx==0,1],'yellow', 
    data[idx==1,0],data[idx==1,1],'yellow', 
    data[idx==2,0],data[idx==2,1],'yellow') 

plot(centroids[:,0],centroids[:,1],'red',markersize=8) 
show() 

什么是错的,因为上面下面的错误得到了代码去:

plot(data[idx==0,0],data[idx==0,1],'yellow', 
IndexError: too many indices for array 
+2

'数据[IDX == 0,0]'你有什么用它来实现?它不是python valide语法 – Oz123

+3

@ Oz123 - 'data [idx == 0,0]'是完全有效的Python语法,它在numpy中是一个非常常见的习惯用法(虽然它在其他地方也是如此)。 –

+0

@JoeKington,我敢说:你能举个实例吗?我想学习新的东西! – Oz123

回答

2

你的语法data[idx==0,0]不正确。

>>> data[idx==0,0] 
Traceback (most recent call last): 
    ... 
IndexError: too many indices for array 

稍后,centroids[:,0]也将导致IndexError: too many indices错误,因为centroids是1 d阵列。

问题在于,您的数据是1-d,并绘制了需要2个坐标值的散点图。下面将做:

>>> data = data.reshape(9,2) # 2d array of x,y coordinates 
>>> data 
array([[1, 1], 
     [1, 1], 
     [1, 1], 
     [3, 3], 
     [3, 3], 
     [3, 3], 
     [7, 7], 
     [7, 7], 
     [7, 7]]) 
>>> centroids, x = kmeans(data,3) # clusters in 2d 
>>> idx, x = vq(data,centroids) 

集群0 X-cooridinates

>>> data[idx==0][:,0] 
array([1, 1, 1]) 

集群0 y坐标

>>> data[idx==0][:,1] 
array([1, 1, 1])