K-均值聚类算法
首先,随机确定k个初始点作为质心,然后将数据集中的每个点分配到一个簇中,即为每个点找距其最近的质心,并将其分配给该质心对应的簇,然后每个簇的质心更新为该簇所有点的平均值。算法流程如下:
创建K个点作为起始质心(一般随机选择)
任意一个点所属簇的结果发生改变时
对数据集中每个点
对每个质心
计算数据与质心间的距离
将数据划分到与它最近的簇
对于每个簇,重新计算质心(所有点的均值)
二分K-均值算法
首先将所有点作为一个簇,然后将该簇一分为二,之后选择其中一个簇继续划分,选择哪一个簇取决于是否可以很大程度降低SSE(误差平方和)的值,循环直到得到指定的簇。算法流程如下:
将所有点看成一个簇
当簇数目小于k时
对于每一个簇
计算总误差
在给定的簇上面进行K均值聚类(K=2)
计算将该簇一分为二之后的总误差
选择使得误差最小的那个簇进行划分操作
from numpy import *
def loadDataSet(filename):
dataMat = []
fr = open(filename)
for line in fr.readlines():
curLine = line.strip().split('\t')
fltLine = [float(x) for x in curLine]
dataMat.append(fltLine)
return dataMat
def distEclud(vecA,vecB):
return sqrt(sum(power(vecA - vecB, 2)))
def randCent(dataSet,k):
n = shape(dataSet)[1]
centroids = mat(zeros((k,n)))
for j in range(n):
minJ = min(dataSet[:,j])
rangeJ = float(max(dataSet[:,j]) - minJ)
centroids[:,j] = mat(minJ + rangeJ * random.rand(k,1))
return centroids
def kMeans(dataSet,k,distMeas=distEclud,createCent=randCent):
m = shape(dataSet)[0]
clusterAssment = mat(zeros((m,2)))
centroids = createCent(dataSet,k)
clusterChanged = True
while clusterChanged:
clusterChanged = False
for i in range(m):
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):
ptsInClust = dataSet[nonzero(clusterAssment[:,0].A == cent)[0]]
centroids[cent,:] = mean(ptsInClust,axis=0)
return centroids,clusterAssment
def biKmeans(dataSet,k,distMeas=distEclud):
m = shape(dataSet)[0]
clusterAssment = mat(zeros((m,2)))
centorid0 = mean(dataSet,axis=0).tolist()[0]
centList = [centorid0]
for j in range(m):
clusterAssment[j,1] = distMeas(mat(centorid0),dataSet[j,:])**2
while (len(centList) < k):
lowestSSE = inf
for i in range(len(centList)):
ptsIncurrCluster = dataSet[nonzero(clusterAssment[:,0].A == i)[0],:]
centroidMat,splitClustAss = kMeans(ptsIncurrCluster,2,distMeas)
sseSplit = sum(splitClustAss[:,1])
sseNotSplit = sum(clusterAssment[nonzero(clusterAssment[:,0].A != i)[0],1])
print(sseSplit,sseNotSplit)
if (sseSplit + sseNotSplit) < lowestSSE:
bestCentToSplit = i
bestNewCents = centroidMat
bestClustAss = splitClustAss.copy()
lowestSSE = sseNotSplit + sseSplit
bestClustAss[nonzero(bestClustAss[:,0].A == 1)[0],0] = len(centList)
bestClustAss[nonzero(bestClustAss[:,0].A == 0)[0],0] = bestCentToSplit
centList[bestCentToSplit] = bestNewCents[0,:].tolist()[0]
centList.append(bestNewCents[1,:])
clusterAssment[nonzero(clusterAssment[:,0].A == bestCentToSplit)[0],:] = bestClustAss
return mat(centList),clusterAssment
dataSet = mat(loadDataSet('testSet.txt'))
a,b = biKmeans(dataSet,3)