一.算法介绍
1.模型
K-means算法并没有显式的数学模型,算法的目的是从数据集中得到k个中心点,每个中心点及其周围的点形成一个聚簇。K-means是一种无监督的学习模型。K-means的学习目标如下图所示:
2.策略
K-mean算法采用的损失函数是平方损失函数。每个簇的点距离中心的平方距离之和构成损失函数。
3.算法
首先给出原始数据{x1,x2,…,xn},这些数据没有被标记的。
初始化k个随机数据u1,u2,…,uk作为初始的聚类中心。这些xn和uk都是向量。
根据下面两个公式迭代就能求出最终所有的u,这些u就是最终所有类的中心位置。
公式一:
意思就是,对于每个数据点,都先求出其与当前所有聚簇中心的距离,然后把该点归到距离最近的那个中心所代表的簇。
公式二:
意思就是,在第一轮对所有数据点分配好了聚簇归属之后。针对每个簇,求解当前簇中所有数据点的中心,把这个中心数据点再作为新的聚簇中心。
然后不断迭代两个公式,直到所有的u都不怎么变化了,就算完成了。
K-means的这种求法可视为是一种启发式的算法,其最后的结果还是可能会收敛到局部最优值。
二.Python程序实现
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