当前位置:   article > 正文

肘方法确定KMeans聚类的最佳K值_肘部法则确定 kmeans方法中的k

肘部法则确定 kmeans方法中的k

Kmeans聚类的K没有指定时,可以通过肘部法来估计聚类数量


K_means参数的最优解是以成本函数最小化为目标

成本函数为各个类畸变程度之和

每个类的畸变程度等于该类重心与其内部成员位置距离的平方和

但是平均畸变程度会随着K的增大先减小后增大,所以可以求出最小的平均畸变程度

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. from matplotlib.font_manager import FontProperties
  4. from sklearn.cluster import KMeans
  5. from scipy.spatial.distance import cdist
  6. # 1 数据可视化
  7. cluster1 = np.random.uniform(0.5, 1.5, (2, 10))
  8. cluster2 = np.random.uniform(3.5, 4.5, (2, 10))
  9. X = np.hstack((cluster1, cluster2)).T
  10. plt.figure()
  11. plt.axis([0, 5, 0, 5])
  12. plt.grid(True)
  13. plt.plot(X[:, 0], X[:, 1], 'k.')
  14. plt.show()
  15. # 2 肘部法求最佳K值
  16. K = range(1, 10)
  17. mean_distortions = []
  18. for k in K:
  19. kmeans = KMeans(n_clusters=k)
  20. kmeans.fit(X)
  21. mean_distortions.append(
  22. sum(
  23. np.min(
  24. cdist(X, kmeans.cluster_centers_, metric='euclidean'), axis=1))
  25. / X.shape[0])
  26. plt.plot(K, mean_distortions, 'bx-')
  27. plt.xlabel('k')
  28. font = FontProperties(fname=r'c:\windows\fonts\msyh.ttc', size=20)
  29. plt.ylabel(u'平均畸变程度', fontproperties=font)
  30. plt.title(u'用肘部法确定最佳的K值', fontproperties=font)
  31. plt.show()
 
13641823-ad8e1aeb15f46e52.png
 

从图中可以看出图片像一只手肘,肘处的K即为最佳K值:K=2

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
  

闽ICP备14008679号