我们来介绍K均值聚类算法,首先读者要知道,聚类是一类无监督的学习,它将相似的对象归到同一个簇中。簇内的数据越相似,则聚类效果越好。无监督学习是指没有事先标记好训练集的类型。聚类和分类都是对记录进行分组;但分类则有预先定义的类别。
K均值聚类算法其实很简单,就如上图所述,我们紧接着就引出K均值聚类的算法。
K均值聚类算法的优点就是算法简单,读者在上面也看到了;而它的缺点是:可能收敛到局部最小值,在大规模数据集上收敛较慢。K均值聚类适应的数据类型是,数值型数据。直观上看,K均值聚类算法的结果就是这样的:
在普遍的算法实现中,我们都可以按照以下流程了进行:
K-均值聚类的一般流程
(1) 收集数据:使用任意方法。
(2) 准备数据:需要数值型数据来计算距离,也可以将标称型数据映射为二值型数据再用
于距离计算。
(3) 分析数据:使用任意方法。
(4) 训练算法:不适用于无监督学习,即无监督学习没有训练过程。
(5) 测试算法:应用聚类算法、观察结果。可以使用量化的误差指标如误差平方和(后面
会介绍)来评价算法的结果。
(6) 使用算法:可以用于所希望的任何应用。通常情况下,簇质心可以代表整个簇的数据
来做出决策。
导入数据
def loadDataSet(fileName): #general function to parse tab -delimited floats
dataMat = [] #assume last column is target value
fr = open(fileName)
for line in fr.readlines():
curLine = line.strip().split('\t')
fltLine = list(map(float,curLine)) #map all elements to float()
dataMat.append(fltLine)
return dataMat
计算欧式距离
def distEclud(vecA, vecB):
return sqrt(sum(power(vecA - vecB, 2))) #la.norm(vecA-vecB)
产生随机质心
def randCent(dataSet, k):
n = shape(dataSet)[1]
centroids = mat(zeros((k,n)))#create centroid mat
for j in range(n):#create random cluster centers, within bounds of each dimension
minJ = min(dataSet[:,j])
rangeJ = float(max(dataSet[:,j]) - minJ)
centroids[:,j] = mat(minJ + rangeJ * random.rand(k,1))
return centroids
K均值聚类算法
def kMeans(dataSet, k, distMeas=distEclud, createCent=randCent):
m = shape(dataSet)[0]
clusterAssment = mat(zeros((m,2)))#create mat to assign data points
#to a centroid, also holds SE of each point
centroids = createCent(dataSet, k)
clusterChanged = True
while clusterChanged:
clusterChanged = False
for i in range(m):#for each data point assign it to the closest centroid
minDist = inf; minIndex = -1
for j in range(k):
distJI = distMeas(centroids[j,:],dataSet[i,:])
if distJI < minDist:
minDist = distJI; minIndex = j
if clusterAssment[i,0] != minIndex: clusterChanged = True
clusterAssment[i,:] = minIndex,minDist**2
print(centroids)
for cent in range(k):#recalculate centroids
ptsInClust = dataSet[nonzero(clusterAssment[:,0].A==cent)[0]]#get all the point in this cluster
centroids[cent,:] = mean(ptsInClust, axis=0) #assign centroid to mean
return centroids, clusterAssment
但是K均值聚类算法是有缺陷的
为了克服这一缺陷,我们引入2分-K均值聚类算法。首先,我们说明数理统计中的一个概念SSE
接下来,我们正式进行引入。
思路:将所有的点作成一个簇,然后选择可以使得SSE最大程度降低的簇一分为二,不断循环到满足数目为止。
二分K-均值算法的伪代码形式如下:
二分K-均值聚类算法
def biKmeans(dataSet, k, distMeas=distEclud):
m = shape(dataSet)[0]
clusterAssment = mat(zeros((m,2)))
centroid0 = mean(dataSet, axis=0).tolist()[0]
centList =[centroid0] #create a list with one centroid
for j in range(m):#calc initial Error
clusterAssment[j,1] = distMeas(mat(centroid0), dataSet[j,:])**2
while (len(centList) < k):
lowestSSE = inf
for i in range(len(centList)):
ptsInCurrCluster = dataSet[nonzero(clusterAssment[:,0].A==i)[0],:]#get the data points currently in cluster i
centroidMat, splitClustAss = kMeans(ptsInCurrCluster, 2, distMeas)
sseSplit = sum(splitClustAss[:,1])#compare the SSE to the currrent minimum
sseNotSplit = sum(clusterAssment[nonzero(clusterAssment[:,0].A!=i)[0],1])
print("sseSplit, and notSplit: ",sseSplit,sseNotSplit)
if (sseSplit + sseNotSplit) < lowestSSE:
bestCentToSplit = i
bestNewCents = centroidMat
bestClustAss = splitClustAss.copy()
lowestSSE = sseSplit + sseNotSplit
bestClustAss[nonzero(bestClustAss[:,0].A == 1)[0],0] = len(centList) #change 1 to 3,4, or whatever
bestClustAss[nonzero(bestClustAss[:,0].A == 0)[0],0] = bestCentToSplit
print('the bestCentToSplit is: ',bestCentToSplit)
print('the len of bestClustAss is: ', len(bestClustAss))
centList[bestCentToSplit] = bestNewCents[0,:].tolist()[0]#replace a centroid with two best centroids
centList.append(bestNewCents[1,:].tolist()[0])
clusterAssment[nonzero(clusterAssment[:,0].A == bestCentToSplit)[0],:]= bestClustAss#reassign new clusters, and SSE
return mat(centList), clusterAssment