機器學習筆記關於python實現Kmean演算法

來源:互聯網
上載者:User

標籤:

這次是一個關於Kmean的類聚演算法,

簡單來說就是到中心點的距離的加權和

看起來很厲害

寫出來一點不厲害

一、隨機取點

import numpy as npimport cv2from matplotlib import pyplot as pltX = np.random.randint(25,50,(25,2))Y = np.random.randint(60,85,(25,2))Z = np.vstack((X,Y))# convert to np.float32Z = np.float32(Z)plt.hist(Z,100,[0,100]),plt.show()

 

二、kmean部分

調用cv2庫裡的kmean

對A、B兩類進行標記

# define criteria and apply kmeans()criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)ret,label,center=cv2.kmeans(Z,2,None,criteria,10,cv2.KMEANS_RANDOM_CENTERS)# Now separate the data, Note the flatten()A = Z[label.ravel()==0]B = Z[label.ravel()==1]

 

三、類聚結果

畫圖畫圖畫圖

# Plot the dataplt.scatter(A[:,0],A[:,1])plt.scatter(B[:,0],B[:,1],c = ‘r‘)plt.scatter(center[:,0],center[:,1],s = 80,c = ‘y‘, marker = ‘s‘)plt.xlabel(‘Height‘),plt.ylabel(‘Weight‘)plt.show()

------------------------------------------------------------------------------------------------------------------------------------------------------

最後

代碼匯總

import numpy as npimport cv2from matplotlib import pyplot as pltX = np.random.randint(25,50,(25,2))Y = np.random.randint(60,85,(25,2))Z = np.vstack((X,Y))# convert to np.float32Z = np.float32(Z)plt.hist(Z,100,[0,100]),plt.show()# define criteria and apply kmeans()criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)ret,label,center=cv2.kmeans(Z,2,None,criteria,10,cv2.KMEANS_RANDOM_CENTERS)# Now separate the data, Note the flatten()A = Z[label.ravel()==0]B = Z[label.ravel()==1]# Plot the dataplt.scatter(A[:,0],A[:,1])plt.scatter(B[:,0],B[:,1],c = ‘r‘)plt.scatter(center[:,0],center[:,1],s = 80,c = ‘y‘, marker = ‘s‘)plt.xlabel(‘Height‘),plt.ylabel(‘Weight‘)plt.show()

  

 

機器學習筆記關於python實現Kmean演算法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.