我想在散点图中绘制 3 个“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
最佳答案
您的语法data[idx==0,0]
不正确。
>>> data[idx==0,0]
Traceback (most recent call last):
...
IndexError: too many indices for array
稍后,centroids[:,0]
也会导致 IndexError: Too much Index
错误,因为 centroids
是一个 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 坐标
>>> data[idx==0][:,0]
array([1, 1, 1])
簇0
y 坐标
>>> data[idx==0][:,1]
array([1, 1, 1])
关于python - 计算 k 均值并绘制散点图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20139929/