本篇的数据和代码参见:https://github.com/stonycat/ML-in-Action
一、K-均值聚类算法
聚类是一种无监督的学习,它将相似的对象归到同一簇中,类似全自动分类。簇内的对象越相似,聚类的效果越好。K-均值聚类是每个类别簇都是采用簇中所含值的均值计算而成。聚类与分类的区别在于分类前目标已知,而聚类为无监督分类。
1.1 K-均值算法的伪代码如下:
创建k个点作为起始质心(通常随机选择)
当任意一个点的簇分配结果发生改变时:
对数据集中的每个点:
对每个质心:
计算质心与数据点之间的距离
将数据点分配到距离其最近的簇
对每一个簇,计算簇中所有点的均值并将均值作为质心。
基本功能函数:加载数据、计算距离、初始化k个中心三个函数。
1.2 以下为kMeans.py文件内容
from numpy import *
import numpy as np
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)
minJ = float(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)))#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
1.3 代码运用
# kMeans.py
import kMeans
# 加载数据
datMat = mat(kMeans.loadDataSet('testSet.txt'))
datMat[:5]
#matrix([[ 1.658985, 4.285136],
# [-3.453687, 3.424321],
# [ 4.838138, -1.151539],
# [-5.379713, -3.362104],
# [ 0.972564, 2.924086]])
#运用kMeans算法
myCentroids, clustAssing = kMeans.kMeans(datMat,4)
# 中心点
myCentroids
#matrix([[ 2.6265299 , 3.10868015],
# [-2.46154315, 2.78737555],
# [-3.38237045, -2.9473363 ],
# [ 2.80293085, -2.7315146 ]])
# 聚类信息
clustAssing[:5]
#matrix([[0. , 2.3201915 ],
# [1. , 1.39004893],
# [3. , 6.63839104],
# [2. , 4.16140951],
# [0. , 2.7696782 ]])
# 绘制散点图
point_x = array(datMat[:,0])
point_y = array(datMat[:,1])
Centroid_x = array(myCentroids[:,0])
Centroid_y = array(myCentroids[:,1])
fig, ax = plt.subplots(figsize=(10,5))
colors = array(clustAssing[:,0])
ax.scatter(point_x, point_y, s=30, c=colors, marker="o")
ax.scatter(Centroid_x,Centroid_y, s=300, c="b", marker="+", label="Centroid")
ax.legend()
ax.set_xlabel("factor1")
ax.set_ylabel("factor2")
.
二、用后处理来提高聚类性能
聚类算法中,k的值是由用户初始定义的,如何才能判断k值定义是否合适,就需要用误差来评价聚类效果的好坏,误差是各个点与其所属类别质心的距离决定的。K-均值聚类的方法效果较差的原因是会收敛到局部最小值,而且全局最小。一种评价聚类效果的方法是SSE(Sum of Squared Error)误差平方和的方法,取平方的结果是使得远离中心的点变得更加突出。
一种降低SSE的方法是增加簇的个数,即提高k值,但是违背了聚类的目标,聚类的目标是在不改变簇数目的前提下提高簇的质量。可选的改进的方法是对生成的簇进行后处理,将最大SSE值的簇划分成两个(K=2的K-均值算法),然后再进行相邻的簇合并。具体方法有两种:1、合并最近的两个质心(合并使得SSE增幅最小的两个质心)2、遍历簇 合并两个然后计算SSE的值,找到使得SSE最小的情况。
下面将使用上述技术得到更好的聚类结果方法。
三、二分K-均值算法
二分K-均值类似后处理的切分思想,初始状态所有数据点属于一个大簇,之后每次选择一个簇切分成两个簇,这个切分满足使SSE值最大程度降低,直到簇数目达到k。另一种思路是每次选择SSE值最大的一个簇进行切分。
3.1 满足使SSE值最大程度降低伪代码如下:
将所有点看成一个簇
当簇数目小于k时
对于每一个簇:
计算总误差
在给定的簇上面进行K-均值聚类(k=2)
计算将该簇一分为二后的总误差
选择使得误差最小的那个簇进行划分操作
函数biKmeans是上面二分K-均值聚类算法的实现,首先创建clusterAssment储存数据集中每个点的分类结果和平方误差,用centList保存所有已经划分的簇,初始状态为整个数据集。while循环不停对簇进行划分,寻找使得SSE值最大程度减小的簇并更新,添加新的簇到centList中。
3.2 以下为kMeans.py文件内容
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
3.3 代码运用
datMat3 = mat(kMeans.loadDataSet('testSet2.txt'))
centList,myNewAssments = kMeans.biKmeans(datMat3,3)
#sseSplit, and notSplit: 570.7227574246755 0.0
#the bestCentToSplit is: 0
#the len of bestClustAss is: 60
#sseSplit, and notSplit: 22.971771896318412 532.6598067890178
#sseSplit, and notSplit: 68.68654812621844 38.06295063565756
#the bestCentToSplit is: 1
#the len of bestClustAss is: 40
# 中心点
centList
#matrix([[-2.94737575, 3.3263781 ],
# [-0.45965615, -2.7782156 ],
# [ 2.93386365, 3.12782785]])
# 聚类信息
myNewAssments[:5]
#matrix([[2. , 0.14546105],
# [0. , 0.68021383],
# [1. , 1.02184582],
# [2. , 1.3454876 ],
# [0. , 1.35376464]])
# 绘制散点图
point_x = array(datMat3[:,0])
point_y = array(datMat3[:,1])
Centroid_x = array(centList[:,0])
Centroid_y = array(centList[:,1])
fig, ax = plt.subplots(figsize=(10,5))
colors = array(myNewAssments[:,0])
ax.scatter(point_x, point_y, s=30, c=colors, marker="o")
ax.scatter(Centroid_x,Centroid_y, s=300, c="b", marker="+", label="Centroid")
ax.legend()
ax.set_xlabel("factor1")
ax.set_ylabel("factor2")