kmeans是最簡單的聚類算法之一,但是運用十分廣泛。最近在工作中也經常遇到這個算法。kmeans一般在數據分析前期使用,選取適當的k,將數據分類后,然后分類研究不同聚類下數據的特點。
kmeans算法步驟:
1 隨機選取k個中心點
2 遍歷所有數據,將每個數據劃分到最近的中心點中
3 計算每個聚類的平均值,并作為新的中心點
4 重復2-3,直到這k個聚類中心點不再變化(收斂了),或執行了足夠多的迭代
下面是一個對二維數據用K-means進行聚類的示例,類中心標記為綠色大圓環,聚類出的兩類分別標記為藍色星號和紅色點。
實現代碼:
~~~
from scipy.cluster.vq import *
from numpy.random import randn
from numpy import vstack
from numpy import array
from numpy import where
from matplotlib.pyplot import figure
from matplotlib.pyplot import plot
from matplotlib.pyplot import axis
from matplotlib.pyplot import show
class1=1.5*randn(100,2)
class2=randn(100,2)+array([5,5])
features=vstack((class1,class2))
centriods,variance=kmeans(features,2)
code,distance=vq(features,centriods)
figure()
ndx=where(code==0)[0]
plot(features[ndx,0],features[ndx,1],'*')
ndx=where(code==1)[0]
plot(features[ndx,0],features[ndx,1],'r.')
plot(centriods[:,0],centriods[:,1],'go')
axis('off')
show()
~~~
