標籤:
這次是一個關於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演算法