其他分享
首页 > 其他分享> > K-Means例子

K-Means例子

作者:互联网

数据集:(数据集很小所以直接CV即可)
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

源代码如下(下次一定会可视化的~):

from turtle import shape

import numpy as np
#数据预处理函数
def loadDataSet(fileName):
    dataSet = []
    fr = open(fileName)
    for line in fr.readlines():
        curLine = line.strip().split('\t')
        #映射为float类型
        flatLine = list(map(float,curLine))
        dataSet.append(flatLine)
    return dataSet
#欧式距离函数
def disE(vecA,vecB):
    return np.sqrt(np.sum(pow(vecA.A - vecB.A, 2)))
#随机K个聚类中心函数
def randCent(dataMat,k):
    # 获取数据的行列数(属性数)
    n = np.shape(dataMat)[1]
    #创建K行N列的聚类中心的矩阵
    centroids = np.mat(np.zeros((k, n)))
    #因为要随机K个聚类中心的矩阵,随机数的范围要在各个属性的最大值和最小值之间
    for j in range(n):
        #每个属性的最小值
        minCl = float(min(dataMat.A[:,j]))
        #最大值和最小值的差就是这个范围
        rangeCl = float(max(dataMat.A[:,j]))-minCl
        #用最小值加上[0,1)的随机数乘以范围,得到随机的K个聚类中心
        centroids[:,j] = np.mat(minCl+(np.random.rand(k,1)*rangeCl))
    # print(centroids)
    return centroids
def KMeans(dataMat,k):
    #获取数据行数(条目数)
    m = np.shape(dataMat)[0]
    # clusterAssment为聚类簇,m行2列。第1列存数据点所属的簇,第二列存该点到质心的距离。
    clusterAssment = np.mat(np.zeros((m,2)))
    # centorids 为聚类中心
    centroids = np.mat(randCent(dataMat,k))
    # clusterChanged 判断聚类是否改变
    clusterChanged =True
    while clusterChanged:
        clusterChanged = False
        for i in range(m):
            minDis = 999999999999
            minInx = -1
            # 计算每个数据点和各个质心之间的距离,并记录最小的距离和簇
            for j in range(k):
                dis = disE(dataMat[i,:],centroids[j,:])
                if minDis > dis:
                    minDis = dis
                    minInx = j
            #如果聚类结果改变
            if clusterAssment[i,0] != (minInx+1):
                clusterChanged = True
                clusterAssment[i,:] = minInx,minDis**2
        # 计算各个新的质心
        for cent in range(k):
            # nonezero函数范围的值是index,该下标和dataMat中的下标是一一对应的。(去看nonzero函数原理)
            ptsInClust = dataMat[np.nonzero(clusterAssment[:,0]==cent)[0]]
            # 对列进行求均值算出新的质心
            centroids[cent,:] = np.mean(ptsInClust,axis=0)
        return centroids,clusterAssment
def testKMeans():
    dataMat = loadDataSet('testSet.txt')
    myCentroids,clustASSing = KMeans(np.mat(dataMat),4)
    print(myCentroids)
    # print(clustASSing)
    # vis = 0;
    # res = {}
    # for i in range(4):
    #     ind = np.nonzero(clustASSing[:,0] == i)[0]
    #     res[i] = np.sum(clustASSing[ind,1])
    # for i in range(80):
    #     vis += clustASSing[i,1]
    # print(vis)
    # print(res)

if __name__ == "__main__":
    testKMeans()


标签:Means,clusterAssment,centroids,range,例子,聚类,np,dataMat
来源: https://blog.csdn.net/Stydwn/article/details/117628900