聚类(Clustering) K-means算法
聚类(clustering) 属于非监督学习 (unsupervised learning)
无类别标记(class label)
2. 举例:
3. K-means 算法:
3.1 Clustering 中的经典算法,数据挖掘十大经典算法之一
3.2 算法接受参数 k ;然后将事先输入的n个数据对象划分为 k个聚类以便使得所获得的聚类满足:同一
聚类中的对象相似度较高;而不同聚类中的对象相似度较小。
3.3 算法思想:
以空间中k个点为中心进行聚类,对最靠近他们的对象归类。通过迭代的方法,逐次更新各聚类中心
的值,直至得到最好的聚类结果
3.4 算法描述:
(1)适当选择c个类的初始中心;
(2)在第k次迭代中,对任意一个样本,求其到c各中心的距离,将该样本归到距离最短的中心所在
的类;
(3)利用均值等方法更新该类的中心值;
(4)对于所有的c个聚类中心,如果利用(2)(3)的迭代法更新后,值保持不变,则迭代结束,
否则继续迭代。
3.5 算法流程:
输入:k, data[n];
(1) 选择k个初始中心点,例如c[0]=data[0],…c[k-1]=data[k-1];
(2) 对于data[0]….data[n], 分别与c[0]…c[k-1]比较,假定与c[i]差值最少,就标记为i;
(3) 对于所有标记为i点,重新计算c[i]={ 所有标记为i的data[j]之和}/标记为i的个数;
(4) 重复(2)(3),直到所有c[i]值的变化小于给定阈值。
本案例一共ABCD四个点 并切 红色五角星是初始的label 覆盖住了棱形
优点:速度快,简单
缺点:最终结果跟初始点选择相关,容易陷入局部最优,需直到k值
使用python实现
import numpy as np
# Function: K Means
# -------------
# K-Means is an algorithm that takes in a dataset and a constant
# k and returns k centroids (which define clusters of data in the
# dataset which are similar to one another).\
#X传入np数据集矩阵格式 K是分类个数 maxIt是手动定义迭代最大次数
def kmeans(X, k, maxIt):
#读取多少行和列 定义为点和纬度
numPoints, numDim = X.shape
#多加一列全是0的 作为预测结果result
dataSet = np.zeros((numPoints, numDim + 1))
#所有数据的列 第一列和除了最后一列 赋给X
dataSet[:, :-1] = X
# Initialize centroids randomly
#随机选取K个中心点作为初始化中心点 选择4行中的K行 作为中心点
centroids = dataSet[np.random.randint(numPoints, size = k), :]
#centroids = dataSet[0:2, :]
#Randomly assign labels to initial centorid
#给中心点最后一列初始化一个值 新的中心点
centroids[:, -1] = range(1, k +1)
# Initialize book keeping vars.
iterations = 0 #从0开始循环
oldCentroids = None #旧的中心点
# Run the main k-means algorithm
#要不要停止规则 参数1、旧的中心点 2、新的中心点 3、循环次数 4、给定最大循环数限制
while not shouldStop(oldCentroids, centroids, iterations, maxIt):
#打印出1、循环第几轮 2、数据集什么样 3、中心点什么样
print "iteration: \n", iterations
print "dataSet: \n", dataSet
print "centroids: \n", centroids
# Save old centroids for convergence test. Book keeping.
oldCentroids = np.copy(centroids) # 赋值旧中心点变量
iterations += 1
# Assign labels to each datapoint based on centroids
# 根据中心点值和数据集 把最后一列的result 每一点归类重新更新一下
updateLabels(dataSet, centroids)
#按照归类后的数据集和K值 算出新的中心点
# Assign centroids based on datapoint labels
centroids = getCentroids(dataSet, k)
# We can get the labels too by calling getLabels(dataSet, centroids)
return dataSet
# Function: Should Stop
# -------------
# Returns True or False if k-means is done. K-means terminates either
# because it has run a maximum number of iterations OR the centroids
# stop changing.
#停止函数
def shouldStop(oldCentroids, centroids, iterations, maxIt):
if iterations > maxIt: #实际循环次数超过最大预设的值停止
return True
return np.array_equal(oldCentroids, centroids) #对比中心点值array值是否相等
# Function: Get Labels
# -------------
# Update a label for each piece of data in the dataset.
# 传入数据集矩阵与中心点 根据每一行没一点计算k中心点距离 距离最短
def updateLabels(dataSet, centroids):
# For each element in the dataset, chose the closest centroid.
# Make that centroid the element's label.
numPoints, numDim = dataSet.shape
# 对每一行最后一列赋值归类
for i in range(0, numPoints):
dataSet[i, -1] = getLabelFromClosestCentroid(dataSet[i, :-1], centroids)
def getLabelFromClosestCentroid(dataSetRow, centroids):
label = centroids[0, -1]; #等于第一个中心点的行
# 对比中心点循环 更新label
minDist = np.linalg.norm(dataSetRow - centroids[0, :-1])
for i in range(1 , centroids.shape[0]):
dist = np.linalg.norm(dataSetRow - centroids[i, :-1])
if dist < minDist:
minDist = dist
label = centroids[i, -1]
print "minDist:", minDist
return label
# Function: Get Centroids
# -------------
# Returns k random centroids, each of dimension n.
def getCentroids(dataSet, k):
# Each centroid is the geometric mean of the points that
# have that centroid's label. Important: If a centroid is empty (no points have
# that centroid's label) you should randomly re-initialize it.
result = np.zeros((k, dataSet.shape[1]))
for i in range(1, k + 1):
oneCluster = dataSet[dataSet[:, -1] == i, :-1]
result[i - 1, :-1] = np.mean(oneCluster, axis = 0)
result[i - 1, -1] = i
return result
x1 = np.array([1, 1])
x2 = np.array([2, 1])
x3 = np.array([4, 3])
x4 = np.array([5, 4])
testX = np.vstack((x1, x2, x3, x4))
result = kmeans(testX, 2, 10)
print "final result:"
print result

![imgres [1]](http://www.okweex.com/wp-content/uploads/2017/06/imgres-1-2.jpg)

![Image [13]](http://www.okweex.com/wp-content/uploads/2017/06/Image-13-1.png)
![Image [2]](http://www.okweex.com/wp-content/uploads/2017/06/Image-2-4.png)
![Image [11]](http://www.okweex.com/wp-content/uploads/2017/06/Image-11-1.png)
![Image [6]](http://www.okweex.com/wp-content/uploads/2017/06/Image-6-4.png)

![Image [13]](http://www.okweex.com/wp-content/uploads/2017/06/Image-13-2.png)