2013-11-22 3 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]'은 완벽하게 유효한 파이썬 문법입니다. numpy에서는 매우 일반적인 관용구입니다 (다른 곳에서도 사용되었지만). –

+0

@JoeKington, 나는 감히 말하고있다 : 실제 사례를 보여줄 수 있습니까? 새로운 것을 배우고 싶습니다! – Oz123

답변

2

귀하의 구문 data[idx==0,0]이 올바르지 않습니다. centroids은 1 차원 배열로

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

나중에, centroids[:,0] 또한 IndexError: too many indices 오류가 발생할 것이다.

데이터가 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])