python K-means工具包初解,pythonk-means
最近資料採礦實驗,寫個K-means演算法,寫完也不是很難,寫的過程中想到python肯定有包,雖然師兄說不讓用,不過自己也寫完了,而用包的話,還不是很熟,稍微尋找了下資料,學了下。另外,自己本身寫的太爛了,不敢拿出來,後續改進了再寫出來吧。
1.注意初始的點,需要轉為numpy.array數組格式。
2.若是直接算中心點的話,直接調用kmeans2函數就行,後面的畫圖,只為了可視化。
#!/usr/bin/python import numpyimport matplotlibimport osmatplotlib.use('Agg')from scipy.cluster.vq import *import pylabpylab.close()xy1=[[2,10],[2,5],[8,4],[5,8],[7,5],[6,4],[1,2],[4,9],[7,3],[1,3]]xy2=numpy.array(xy1)cluster_num=3res, idx = kmeans2(numpy.array(zip(xy2[:,0],xy2[:,1])),cluster_num)print "local centre points:\n",rescolors = ([([0.4,1,0.4],[1,0.4,0.4],[0.1,0.8,1])[i] for i in idx])# plot colored pointspylab.scatter(xy2[:,0],xy2[:,1])# mark centroids as (X)pylab.scatter(res[:,0],res[:,1], marker='o', s = 500, linewidths=2, c='none')pylab.scatter(res[:,0],res[:,1], marker='x', s = 500, linewidths=2)#print os.getcwd()pylab.savefig('pic.png'):
#---------------------------------------------------------------------------
參考:http://blog.csdn.net/brandohero/article/details/39967663
#!/usr/bin/python # Adapted from http://hackmap.blogspot.com/2007/09/k-means-clustering-in-scipy.html import numpyimport matplotlibmatplotlib.use('Agg')from scipy.cluster.vq import *import pylabpylab.close() # generate 3 sets of normally distributed points around# different means with different variancespt1 = numpy.random.normal(1, 0.2, (100,2))pt2 = numpy.random.normal(2, 0.5, (300,2))pt3 = numpy.random.normal(3, 0.3, (100,2)) # slightly move sets 2 and 3 (for a prettier output)pt2[:,0] += 1pt3[:,0] -= 0.5 xy = numpy.concatenate((pt1, pt2, pt3)) # kmeans for 3 clustersres, idx = kmeans2(numpy.array(zip(xy[:,0],xy[:,1])),3) colors = ([([0.4,1,0.4],[1,0.4,0.4],[0.1,0.8,1])[i] for i in idx]) # plot colored pointspylab.scatter(xy[:,0],xy[:,1], c=colors) # mark centroids as (X)pylab.scatter(res[:,0],res[:,1], marker='o', s = 500, linewidths=2, c='none')pylab.scatter(res[:,0],res[:,1], marker='x', s = 500, linewidths=2) pylab.savefig('/tmp/kmeans.png')
#------------------------------------
轉載請認證於:http://write.blog.csdn.net/postedit/41158167