python K-means工具包初解,pythonk-means

來源:互聯網
上載者:User

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.