簡(jiǎn)單來說,K-means算法是一種無監(jiān)督算法,不需要事先對(duì)數(shù)據(jù)集打上標(biāo)簽,即ground-truth,也可以對(duì)數(shù)據(jù)集進(jìn)行分類,并且可以指定類別數(shù)目 牧師-村民模型
import numpy as np
import matplotlib.pyplot as plt
import sklearn.datasets as datasets
def create_data():
X,y = datasets.make_blobs(n_samples=1000,n_features=2,centers=[[1,0],[5,4],[2,3],[10,8],[7,4]])
return X,y
def init_centers(data,k):
m, n =data.shape
# m 樣本個(gè)數(shù),n特征個(gè)數(shù)
center_ids = np.random.choice(m,k)
centers = data[center_ids]
return centers
def cal_dist(ptA,ptB):
return np.linalg.norm(ptA-ptB)
def kmeans_process(data,k):
centers = init_centers(data, k)
m, n = data.shape
keep_changing = True
pred_y = np.zeros((m,))
while keep_changing:
keep_changing = False
# 計(jì)算剩余樣本所屬類別
for i in range(m):
min_distance = np.inf
for center in range(k):
distance = cal_dist(data[i,:],centers[center,:])
if distancemin_distance: # 判斷離哪個(gè)更近
min_distance = distance
idx = center # 類別換下
if pred_y[i] != idx: # 判斷是否發(fā)生了改變
keep_changing = True
pred_y[i] = idx
# 更新類別中心點(diǎn)坐標(biāo)
for center in range(k):
cluster_data = data[pred_y==center]
centers[center,:] = np.mean(cluster_data, axis=0) # 求相同類別數(shù)據(jù)點(diǎn)的質(zhì)心點(diǎn)
print(centers)
return centers, pred_y
if __name__ == '__main__':
X, y = create_data()
centers , pred_y = kmeans_process(data=X, k=5)
plt.scatter(X[:,0], X[:,1], s=3, c=pred_y)
plt.scatter(centers[:,0], centers[:,1], s=10, c='k')
plt.show()
到此這篇關(guān)于Python實(shí)現(xiàn)K-means聚類算法并可視化生成動(dòng)圖步驟詳解的文章就介紹到這了,更多相關(guān)Python可視化K-means聚類算法內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!