Python手动实现kmeans聚类和调用sklearn实现
生活随笔
收集整理的這篇文章主要介紹了
Python手动实现kmeans聚类和调用sklearn实现
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1. 算法步驟
- 隨機選取k個樣本點充當k個簇的中心點;
- 計算所有樣本點與各個簇中心之間的距離,然后把樣本點劃入最近的簇中;
- 根據簇中已有的樣本點,重新計算簇中心;
- 重復步驟2和3,直到簇中心不再改變或改變很小。
2. 手動Python實現
import numpy as np import matplotlib.pyplot as plt from sklearn.datasets.samples_generator import make_blobsn_data = 400 n_cluster = 4 # generate training data X, y = make_blobs(n_samples=n_data, centers=n_cluster, cluster_std=0.60, random_state=0)# generate centers of clusters centers = np.random.rand(4, 2)*5EPOCH = 10 tol = 1e-5 for epoch in range(EPOCH):labels = np.zeros(n_data, dtype=np.int)# 計算每個點到簇中心的距離并分配labelfor i in range(n_data):distance = np.sum(np.square(X[i]-centers), axis=1)label = np.argmin(distance)labels[i] = label# 重新計算簇中心for i in range(n_cluster):indices = np.where(labels == i)[0] # 找出第i簇的樣本點的下標points = X[indices]centers[i, :] = np.mean(points, axis=0) # 更新第i簇的簇中心plt.scatter(X[:, 0], X[:, 1], c=labels, s=40, cmap='viridis') plt.show()運行結果:(注:當簇中心初始化不好時,可能計算會有點錯誤)
3. 調用sklearn實現kmeans
運行結果:
總結
以上是生活随笔為你收集整理的Python手动实现kmeans聚类和调用sklearn实现的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python爬虫中三种数据解析方式
- 下一篇: python argparse理解与实例