Kmeans演算法手動實現

2021-09-21 07:34:31 字數 1628 閱讀 9310

背景:平面上有兩堆資料(資料以(x,y)的二維座標形式表示),目標是找出兩堆資料的中心點

隨機生成兩個點作為兩堆資料的中心點

計算所有點分別到兩個中心點的距離

對於平面的每乙個點,比較到哪乙個中心點的距離近,就被歸為哪一類

對於歸類後的資料重新計算中心點的座標

判斷中心點是否有明顯變化,如果有,跳轉到2,如果沒有,跳轉到6

程式結束,輸出中心點的座標

下面是用python**實現

from sklearn.datasets import make_blobs

import matplotlib.pyplot as plt

import numpy as np

#kmeans演算法實現原理

def k_means():

x,y = make_blobs(n_samples=150,random_state=170,centers=2)

a_point = np.array([-12,-8])

b_point = np.array([-2,2])

tol = true #容忍度,是否繼續程式的迭代

while tol:

a_lens = np.linalg.norm(x - a_point,axis = 1) #計算所有點到a點的距離

b_lens = np.linalg.norm(x - b_point,axis = 1) #計算所有點到b點的距離

a_sets = x[a_lens < b_lens]

b_sets = x[b_lens < a_lens]

a_new_point = a_sets.mean(axis = 0) #計算分類後的新的中心點的座標

b_new_point = b_sets.mean(axis = 0) #計算分類後的新的中心點的座標

#計算新的中心點和上次計算的中心點對比,有無明顯位移

tol_move = np.linalg.norm(a_new_point - a_point) + np.linalg.norm(b_new_point - b_point)

#如果位移不明顯,跳出迴圈,1.0是對於明顯性的容忍度,根據需要設定

if tol_move < 1.0:

tol = false

a_point = a_new_point

b_point = b_new_point

return a_point,b_point

print(k_means())

注:因為系統中有kmeans這個函式,所以不能和系統中的函式重名,因為python中有已定義的函式,實現如下
from sklearn.cluster import kmeans

#使用系統kmeans方法進行聚類

x,y = make_blobs(n_samples=150,random_state=170,centers=2)

km = kmeans(n_clusters=2,random_state=170).fit(x)

#列印聚類後的中心

print(km.cluster_centers_)

#原始資料的聚類結果

print(km.predict(x))

希望對大家有幫助

二 k means聚類演算法的手動實現

import numpy as np import pandas as pd import matplotlib as mpl import matplotlib.pyplot as plt matplotlib inline 為了減少迭代次數,我們可以盡量把質心初始化在資料分布的內部 def ra...

Kmeans演算法實現

include opencv2 highgui highgui.hpp include opencv2 core core.hpp include using namespace cv using namespace std static void help int main int argc ch...

K means演算法實現

import math import numpy class point data reader file name str def init self,file name point data reader.file name file name defget data list self,num...