1,聚類(clustering) 屬於非監督學習 (unsupervised learning),屬於迴歸問題,比如下圖的聚類分析。
2. K-means 算法:
2.1 Clustering 中的經典算法,數據挖掘十大經典算法之一
2.2 算法接受參數 k ;然後將事先輸入的n個數據對象劃分爲 k個聚類以便使得所獲得的聚類滿足:同一聚類中的對象相似度較高;而不同聚類中的對象相似度較小。
2.3 算法思想:
以空間中k個點爲中心進行聚類,對最靠近他們的對象歸類。通過迭代的方法,逐次更新各聚類中心 的值,直至得到最好的聚類結果
2.4 算法描述:
(1)適當選擇c個類的初始中心;
(2)在第k次迭代中,對任意一個樣本,求其到c各中心的距離,將該樣本歸到距離最短的中心所在的類;
(3)利用均值等方法更新該類的中心值;
(4)對於所有的c個聚類中心,如果利用(2)(3)的迭代法更新後,值保持不變,則迭代結束,否則繼續迭代。
(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]值的變化小於給定閾值。
4,舉例分析:
比如有a(1,1),b(2,1),c(4,3),d(5,4),我們首先選擇a和b作爲中心點。
求距離:A(x1,y1),B(x2,y2)的距離是:dist =sqrt((x2-x1)^2+(y2-y1)^2)),所以我們首先選擇a(1,1),b(2,1)作爲中心點,從而計算a,b分別到a,b,c,d的距離,於是距離計算如下:
對數據進行分類,也就是數據大的作爲0,數據小的作爲1,我們更新分類如下:
我們來重新更新中心點,第一類是a,均值是(1,1),對於b,c,d三點計算平均值:
重新計算a,b,c,d到(1,1)和(11/3,8/3)距離如下:
更新數據分類如下:
所以現在數據分作兩類,我們重新計算平均值和距離:
再次更新平均值和距離:
分類和前次一樣,所以分類截至了。
5,spyder建立python代碼(k_means.py):
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).
def kmeans(X, k, maxIt):
numPoints, numDim = X.shape
dataSet = np.zeros((numPoints, numDim + 1))
dataSet[:, :-1] = X
# Initialize centroids randomly
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
oldCentroids = None
# Run the main k-means algorithm
while not shouldStop(oldCentroids, centroids, iterations, maxIt):
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
updateLabels(dataSet, centroids)
# 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)
# Function: Get Labels
# -------------
# Update a label for each piece of data in the dataset.
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];
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
結果打印如下:
通過對比,可以看到結果和手工計算一致。