1. K-Means算法缺点

1)对k个初始质心的选择比较敏感,容易陷入局部最小值。如下面这两种情况。K-Means也是收敛了,只是收敛到了局部最小值。

python 肘部法则 肘部算法_python 肘部法则


2)k值得选择是用户指定的,不同的k得到的结果会有挺大的不同,如下图所示,左边是k=3的结果,蓝色的簇太稀疏了,蓝色的簇应该可以再划分成两个簇。右边的是k=5的结果,红色和蓝色的簇应该合并为一个簇

python 肘部法则 肘部算法_python_02


3)存在局限性,如下面这种非球状的数据分布就搞不定了。

python 肘部法则 肘部算法_聚类_03


4)数据量比较大的时候,收敛会比较慢。

2. K-Means算法优化

1)使用多次的随机初始化,计算每一次建模得到的代价函数的值,选取代价函数最小结果作为聚类结果。

python 肘部法则 肘部算法_python_04


2)使用肘部法则来选择k的值。如下图所示:

python 肘部法则 肘部算法_python 肘部法则_05

3. 肘部法则代码实现

注:数据集在文章末尾

import numpy as np
import matplotlib.pyplot as plt  

# 载入数据
data = np.genfromtxt("kmeans.txt", delimiter=" ")
##### 模型训练

# 计算距离 
def euclDistance(vector1, vector2):  
    return np.sqrt(sum((vector2 - vector1)**2))
  
# 初始化质心
def initCentroids(data, k):  
    numSamples, dim = data.shape
    # k个质心,列数跟样本的列数一样
    centroids = np.zeros((k, dim))  
    # 随机选出k个质心
    for i in range(k):  
        # 随机选取一个样本的索引
        index = int(np.random.uniform(0, numSamples))  
        # 作为初始化的质心
        centroids[i, :] = data[index, :]  
    return centroids  
  
# 传入数据集和k的值
def kmeans(data, k):  
    # 计算样本个数
    numSamples = data.shape[0]   
    # 样本的属性,第一列保存该样本属于哪个簇,第二列保存该样本跟它所属簇的误差
    clusterData = np.array(np.zeros((numSamples, 2)))  
    # 决定质心是否要改变的变量
    clusterChanged = True  
  
    # 初始化质心  
    centroids = initCentroids(data, k)  
  
    while clusterChanged:  
        clusterChanged = False  
        # 循环每一个样本 
        for i in range(numSamples):  
            # 最小距离
            minDist  = 100000.0  
            # 定义样本所属的簇
            minIndex = 0  
            # 循环计算每一个质心与该样本的距离
            for j in range(k):  
                # 循环每一个质心和样本,计算距离
                distance = euclDistance(centroids[j, :], data[i, :])  
                # 如果计算的距离小于最小距离,则更新最小距离
                if distance < minDist:  
                    minDist  = distance  
                    # 更新样本所属的簇
                    minIndex = j  
                    # 更新最小距离
                    clusterData[i, 1] = distance
              
            # 如果样本的所属的簇发生了变化
            if clusterData[i, 0] != minIndex:  
                # 质心要重新计算
                clusterChanged = True
                # 更新样本的簇
                clusterData[i, 0] = minIndex
  
        # 更新质心
        for j in range(k):  
            # 获取第j个簇所有的样本所在的索引
            cluster_index = np.nonzero(clusterData[:, 0] == j)
            # 第j个簇所有的样本点
            pointsInCluster = data[cluster_index]  
            # 计算质心
            centroids[j, :] = np.mean(pointsInCluster, axis = 0) 
#         showCluster(data, k, centroids, clusterData)
  
    return centroids, clusterData  
  
# 显示结果 
def showCluster(data, k, centroids, clusterData):  
    numSamples, dim = data.shape  
    if dim != 2:  
        print("dimension of your data is not 2!")  
        return 1  
  
    # 用不同颜色形状来表示各个类别
    mark = ['or', 'ob', 'og', 'ok', '^r', '+r', 'sr', 'dr', '<r', 'pr']  
    if k > len(mark):  
        print("Your k is too large!")  
        return 1  
  
    # 画样本点  
    for i in range(numSamples):  
        markIndex = int(clusterData[i, 0])  
        plt.plot(data[i, 0], data[i, 1], mark[markIndex])  
  
    # 用不同颜色形状来表示各个类别
    mark = ['*r', '*b', '*g', '*k', '^b', '+b', 'sb', 'db', '<b', 'pb']  
    # 画质心点 
    for i in range(k):  
        plt.plot(centroids[i, 0], centroids[i, 1], mark[i], markersize = 20)  
  
    plt.show()
list_lost = []
for k in range(2,10):
    min_loss = 10000
    min_loss_centroids = np.array([])
    min_loss_clusterData = np.array([])
    for i in range(50):
        # centroids 簇的中心点 
        # cluster Data样本的属性,第一列保存该样本属于哪个簇,第二列保存该样本跟它所属簇的误差
        centroids, clusterData = kmeans(data, k)  
        loss = sum(clusterData[:,1])/data.shape[0]
        if loss < min_loss:
            min_loss = loss
            min_loss_centroids = centroids
            min_loss_clusterData = clusterData
    list_lost.append(min_loss)
print(list_lost)

# print('loss',min_loss)
# print('cluster complete!')      
# centroids = min_loss_centroids
# clusterData = min_loss_clusterData
# 显示结果
# showCluster(data, k, centroids, clusterData)

输出:

python 肘部法则 肘部算法_聚类_06

# 画图
plt.plot(range(2,10),list_lost)
plt.xlabel('k')
plt.ylabel('loss')
plt.show()

输出:

python 肘部法则 肘部算法_python 肘部法则_07


数据集:“kmeans.txt”:

1.658985 4.285136  
-3.453687 3.424321  
4.838138 -1.151539  
-5.379713 -3.362104  
0.972564 2.924086  
-3.567919 1.531611  
0.450614 -3.302219  
-3.487105 -1.724432  
2.668759 1.594842  
-3.156485 3.191137  
3.165506 -3.999838  
-2.786837 -3.099354  
4.208187 2.984927  
-2.123337 2.943366  
0.704199 -0.479481  
-0.392370 -3.963704  
2.831667 1.574018  
-0.790153 3.343144  
2.943496 -3.357075  
-3.195883 -2.283926  
2.336445 2.875106  
-1.786345 2.554248  
2.190101 -1.906020  
-3.403367 -2.778288  
1.778124 3.880832  
-1.688346 2.230267  
2.592976 -2.054368  
-4.007257 -3.207066  
2.257734 3.387564  
-2.679011 0.785119  
0.939512 -4.023563  
-3.674424 -2.261084  
2.046259 2.735279  
-3.189470 1.780269  
4.372646 -0.822248  
-2.579316 -3.497576  
1.889034 5.190400  
-0.798747 2.185588  
2.836520 -2.658556  
-3.837877 -3.253815  
2.096701 3.886007  
-2.709034 2.923887  
3.367037 -3.184789  
-2.121479 -4.232586  
2.329546 3.179764  
-3.284816 3.273099  
3.091414 -3.815232  
-3.762093 -2.432191  
3.542056 2.778832  
-1.736822 4.241041  
2.127073 -2.983680  
-4.323818 -3.938116  
3.792121 5.135768  
-4.786473 3.358547  
2.624081 -3.260715  
-4.009299 -2.978115  
2.493525 1.963710  
-2.513661 2.642162  
1.864375 -3.176309  
-3.171184 -3.572452  
2.894220 2.489128  
-2.562539 2.884438  
3.491078 -3.947487  
-2.565729 -2.012114  
3.332948 3.983102  
-1.616805 3.573188  
2.280615 -2.559444  
-2.651229 -3.103198  
2.321395 3.154987  
-1.685703 2.939697  
3.031012 -3.620252  
-4.599622 -2.185829  
4.196223 1.126677  
-2.133863 3.093686  
4.668892 -2.562705  
-2.793241 -2.149706  
2.884105 3.043438  
-2.967647 2.848696  
4.479332 -1.764772  
-4.905566 -2.911070