肘方法确定KMeans聚类的最佳K值

版权声明:本文为博主原创文章,未经博主允许也可以转载,注明转载即可。 https://blog.csdn.net/xiligey1/article/details/82457271

当Kmeans聚类的K没有指定时,可以通过肘部法来估计聚类数量
K_means参数的最优解是以成本函数最小化为目标,成本函数为各个类畸变程度之和,
每个类的畸变程度等于该类重心与其内部成员位置距离的平方和
但是平均畸变程度会随着K的增大先减小后增大,所以可以求出最小的平均畸变程度

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
from sklearn.cluster import KMeans
from scipy.spatial.distance import cdist
# 1 数据可视化
cluster1 = np.random.uniform(0.5, 1.5, (2, 10))
cluster2 = np.random.uniform(3.5, 4.5, (2, 10))
X = np.hstack((cluster1, cluster2)).T
plt.figure()
plt.axis([0, 5, 0, 5])
plt.grid(True)
plt.plot(X[:, 0], X[:, 1], 'k.')
plt.show()

# 2 肘部法求最佳K值
K = range(1, 10)
mean_distortions = []
for k in K:
    kmeans = KMeans(n_clusters=k)
    kmeans.fit(X)
    mean_distortions.append(
        sum(
            np.min(
                cdist(X, kmeans.cluster_centers_, metric='euclidean'), axis=1))
        / X.shape[0])
plt.plot(K, mean_distortions, 'bx-')
plt.xlabel('k')
font = FontProperties(fname=r'c:\windows\fonts\msyh.ttc', size=20)
plt.ylabel(u'平均畸变程度', fontproperties=font)
plt.title(u'用肘部法确定最佳的K值', fontproperties=font)
plt.show()
13641823-ad8e1aeb15f46e52.png
2.png

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

猜你喜欢

转载自blog.csdn.net/xiligey1/article/details/82457271