一:背景引入
机器学习领域需要对数据进行操作,其中有两个常见的操作:聚类和分类。聚类属于物以类聚,寻求数据内部的联系,原始的数据是没有任何标记的,仅仅是一堆数据,名曰无监督学习,就是无标签,比如k-means 算法;而分类属于近朱者赤,数据是有标记的,名曰有监督学习,比如KNN算法。正常的步骤是先聚类再分类。
二:k-means 原理
给定样本数据集 , "k均值"(k-means)算法对聚类所得的类划分
, 目标是最小化平方误差函数:
其中,是每一类的平均值。通俗的讲,误差函数刻画了每一类的紧密程度。
越小,则对每一类而言,该类中的成员离均值越紧密,紧密团结在以均值为核心的类周围。所以,想要最小化误差,有两个办法,一是K的选取,二是均值的选取。找到所有可能的K就能找到最优解,但这是NP难(非多项式时间复杂度)问题,转而从均值着手,采用贪心算法,即通过迭代求解:先初始化均值,然后迭代更新均值,当均值变化不大,如均值改变量小于某个给定阈值
时,我们就可以认为每一类已经趋于稳定,从而可认为算法收敛。
三:代码解析
该代码以均值改变量小于给定阈值为收敛标准。代码源自 https://blog.youkuaiyun.com/zouxy09/article/details/17589329
这里稍加改动,运行环境为Python 3.6, 把不太熟悉的地方稍加解释
1. K_means.py
from numpy import *
import time
import matplotlib.pyplot as plt
# calculate Euclidean distance
def euclDistance(vector1, vector2):
return sqrt(sum(power(vector2 - vector1, 2)))
# init centroids with random samples
def initCentroids(dataSet, k):
numSamples, dim = dataSet.shape
centroids = zeros((k, dim))
for i in range(k):
index = int(random.uniform(0, numSamples))
centroids[i, :] = dataSet[index, :]
return centroids
# k-means cluster
def kmeans(dataSet, k):
numSamples = dataSet.shape[0]
# first column stores which cluster this sample belongs to,
# second column stores the error between this sample and its centroid
clusterAssment = mat(zeros((numSamples, 2)))
clusterChanged = True
## step 1: init centroids
centroids = initCentroids(dataSet, k)
while clusterChanged:
clusterChanged = False
## for each sample
for i in range(numSamples):
minDist = 100000.0
minIndex = 0
## for each centroid
## step 2: find the centroid who is closest
for j in range(k):
distance = euclDistance(centroids[j, :], dataSet[i, :])
if distance < minDist:
minDist = distance
minIndex = j
## step 3: update its cluster
if clusterAssment[i, 0] != minIndex:
clusterChanged = True
clusterAssment[i, :] = minIndex, minDist**2
## step 4: update centroids
for j in range(k):
pointsInCluster = dataSet[nonzero(clusterAssment[:, 0].A == j)[0]]
centroids[j, :] = mean(pointsInCluster, axis = 0)
print ('Congratulations, cluster complete!')
return centroids, clusterAssment
# show your cluster only available with 2-D data
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', '<r', 'pr']
if k > len(mark):
print ("Sorry! Your k is too large! please contact Zouxy")
return 1
# draw all samples
for i in range(numSamples):
markIndex = int(clusterAssment[i, 0])
plt.plot(dataSet[i, 0], dataSet[i, 1], mark[markIndex])
mark = ['Dr', 'Db', 'Dg', 'Dk', '^b', '+b', 'sb', 'db', '<b', 'pb']
# draw the centroids
for i in range(k):
plt.plot(centroids[i, 0], centroids[i, 1], mark[i], markersize = 12)
plt.show()
把这句代码解释下:
pointsInCluster = dataSet[nonzero(clusterAssment[:, 0].A == j)[0]]
clusterAssment[:, 0].A表示将矩阵clusterAssment的第一列转为数组array,nonzero表示取出array中的非0值,nonzero是numpy中的方法。看个例子:
>>>import numpy as np
>>> a=np.mat([[1,2],[2,3],[4,3]])
>>> a
matrix([[1, 2],
[2, 3],
[4, 3]])
>>> a[:,0] #切片操作,取出第一列
matrix([[1],
[2],
[4]])
>>> a.A #可以看到类型变成了array
array([[1, 2],
[2, 3],
[4, 3]])
>>> np.nonzero(a[:,0].A!=0)#结果其实分别表示行,列,即(0,0),(1,0),(2,0)元素不为0
(array([0, 1, 2], dtype=int32), array([0, 0, 0], dtype=int32))
>>> np.nonzero(a[:,0].A!=0)[0]#将行标取出,即0,1,2行
array([0, 1, 2], dtype=int32)
>>> b=np.mat([[2,3],[1,3],[3,4]])
>>> b[np.nonzero(a[:,0].A!=0)[0]]#即取出b的0,1,2行
matrix([[2, 3],
[1, 3],
[3, 4]])
所以这句代码实现了属于同一类的数据的聚合,把dataSet中同一类的数据全部放在pointsincluster这个矩阵中。方便下面求均值。
2. 测试代码
这里设置K=4,即分四类。
K_means_test.py
from numpy import *
from K_means import kmeans, showCluster
import time
import matplotlib.pyplot as plt
## step 1: load data
print ("step 1: load data...")
dataSet = []
fileIn = open('/media/disk_add/myzhao/PycharmProjects/K_means/test.txt')
for line in fileIn.readlines():
lineArr = line.strip().split('\t')
dataSet.append([float(lineArr[0]), float(lineArr[1])])
## step 2: clustering...
print ("step 2: clustering...")
dataSet = mat(dataSet)
k = 4
centroids, clusterAssment = kmeans(dataSet, k)
## step 3: show the result
print ("step 3: show the result...")
showCluster(dataSet, k, centroids, clusterAssment)
数据:
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
3. 运行结果
可以看到分成了4类。菱形代表该类的最终均值。
文章主要参考:https://blog.youkuaiyun.com/zouxy09/article/details/17589329
写的比较具体,大家可以看原文。