Kmeans算法 python实现(改)

转载自机器学习算法与Python实践之(五)k均值聚类(k-means)

然后做了一些修改,想贴评论区交流来着,结果字数限制贴不开,很是尴尬……

然后当时自己是要算SSE的,又加上了找elbow point的图和代码


#!/usr/bin/python
# -*- coding: utf-8 -*-

from numpy import *
import matplotlib.pyplot as plt

'''
楼主我这有点自己不成熟的建议,不一定恰当
一个是欧式距离没必要开方吧,开方还会造成不必要的误差
还有一个是随机数没有去重操作,在样本点比较少且k比较小的情况下,很容易选重点而少分一类
另一个是
if clusterAssment[i, 0] != minIndex:  
    clusterChanged = True  
    clusterAssment[i, :] = minIndex, minDist**2
因为你的clusterAssment初始化为0,但是你minIndex索引也可能为0,也就是说如果你的
clusterAssment第一次被更新且minIndex为0时,这个分支是进不去的,这个对分簇可能没有影响,但是
如果最后要算SSE的话,累加clusterAssment[i, 1]就不是想要的结果,感觉其实也就是索引从1开始
并且及时更新clusterAssment[i, 1],功用上来说感觉好的多
'''

# 计算距离平方
def euclDistance(vector1, vector2):
    return sum(power(vector2 - vector1, 2))


# 用随机样本初始化centroids
def initCentroids(dataSet, k):
    numSamples, dim = dataSet.shape
    centroids = zeros((k + 1, dim))

    s = set()
    for i in range(1, k + 1):
        while True:
            index = int(random.uniform(0, numSamples))
            if index not in s:
                s.add(index)
                break
        # index = int(random.uniform(0, 2))
        print "random index:"
        print index
        centroids[i, :] = dataSet[index, :]

    # centroids[0, :] = dataSet[0, :]
    # centroids[1, :] = dataSet[2, :]

    # centroids[1, :] = dataSet[0, :]
    # centroids[2, :] = dataSet[2, :]
    return centroids

# 获得cost
def getcost(clusterAssment):
    len = clusterAssment.shape[0]
    Sum = 0.0
    for i in xrange(len):
        Sum = Sum + clusterAssment[i, 1]
    return Sum

# k-means主算法
def kmeans(dataSet, k):
    numSamples = dataSet.shape[0]

    # 第一列存这个样本点属于哪个簇
    # 第二列存这个样本点和样本中心的误差
    clusterAssment = mat(zeros((numSamples, 2)))
    for i in xrange(numSamples):
        clusterAssment[i, 0] = -1
    clusterChanged = True

    # step 1: 初始化centroids
    centroids = initCentroids(dataSet, k)

    # 如果收敛完毕,则clusterChanged为False
    while clusterChanged:
        clusterChanged = False
        # 对于每个样本点
        for i in xrange(numSamples):
            minDist = 100000.0
            minIndex = 0
            # 对于每个样本中心
            # step 2: 找到最近的样本中心
            for j in range(1, k + 1):
                distance = euclDistance(centroids[j, :], dataSet[i, :])
                if distance < minDist:
                    minDist = distance
                    minIndex = j

            # step 3: 更新样本点与中心点的分配关系
            if clusterAssment[i, 0] != minIndex:
                clusterChanged = True
                clusterAssment[i, :] = minIndex, minDist
            else:
                clusterAssment[i, 1] = minDist

        # step 4: 更新样本中心
        print "clusterAssment before:"
        print clusterAssment
        for j in range(1, k + 1):
            # 骚操作
            pointsInCluster = dataSet[nonzero(clusterAssment[:, 0].A == j)[0]]
            centroids[j, :] = mean(pointsInCluster, axis=0)

    print 'Congratulations, cluster complete!'
    return centroids, clusterAssment


# 以2D形式可视化数据
def showCluster(dataSet, k, centroids, clusterAssment):
    numSamples, dim = dataSet.shape
    if dim != 2:
        print "Sorry! I can not draw because the dimension of your data is not 2!"
        return 1

    mark = ['or', 'ob', 'og', 'ok', '^r', '+r', 'sr', 'dr', ' len(mark):
        print "Sorry! Your k is too large!"
        return 1

    # 绘制所有非中心样本点
    for i in xrange(numSamples):
        markIndex = int(clusterAssment[i, 0])
        plt.plot(dataSet[i, 0], dataSet[i, 1], mark[markIndex - 1])

    mark = ['Dr', 'Db', 'Dg', 'Dk', '^b', '+b', 'sb', 'db', '



testSet.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


结果:

Kmeans算法 python实现(改)_第1张图片


# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
#根据k和cost(SSE)绘图找elbow point确定较为恰当的k取值
#X轴,Y轴数据
x = [2, 3, 4, 5, 6, 7, 8]
#就简单取了个均值
y = [792.916856537, 463.649680922, 150.626049073, 136.860464646, 122.657971766, 110.792377091, 91.8706106158]
plt.figure(figsize=(8, 4)) #创建绘图对象
plt.plot(x, y, "b--", linewidth=1)   #在当前绘图对象绘图(X轴,Y轴,蓝色虚线,线宽度)
plt.xlabel("Time(s)") #X轴标签
plt.ylabel("Volt")  #Y轴标签
plt.title("Line plot") #图标题
plt.show()  #显示图

绘图结果:

Kmeans算法 python实现(改)_第2张图片


因此k = 4时应该是效果比较好的



你可能感兴趣的:(机器学习)