[Study notes] to see K-means algorithm to understand its implementation

algorithm

  1. Classification:
    clustering (clustering) is a non-supervised learning (unsupervised learning)
    Classless mark (class label)

  2. For example:
    Here Insert Picture Description

  3. K-means algorithm:

    3.1 Clustering classic algorithms, data mining one of the top ten classical algorithm

    3.2 algorithm accepts parameter k; n then the previously inputted data object into k clusters in order to satisfy such clusters obtained: the same cluster objects high similarity; different similarity clustering objects small.

    3.3 algorithm ideological
    space in cluster k points centered on the subject closest to their classification. Iterative method by sequentially updating the value of each cluster center, until a best clustering results

    3.4 Algorithm Description:
    (1) suitably selected classes of the initial center c;
    (2) at the k th iteration, for any one sample to find that the centers of the distance c, the center of the sample where the shortest distance to return class;
    (3) method using the average value and the like of the center value of the class (class of the same at all points averaged to give the new center);
    (4) for all c cluster centers, if the use of (2) (3 ) after updating the iterative method, the value remains the same, the end of the iteration, otherwise continue iteration.

    3.5 algorithmic process:
    Input: k, Data [n-];
    (. 1) to select the k initial centers, for example, C [0] = Data [0], ... C [. 1-k] = Data [-k. 1];
    ( 2) the data [0] ... .data [n ], respectively, c [0] ... c [k -1] compared with the minimum difference value is assumed c [i], is marked as I;
    (. 3) for all markers i point is recalculated c [i] = {i, all marked data [j]} and the sum / number i is marked;
    (4) repeat (2) (3), until all the values of c [i] It changes less than a given threshold.

  4. Example:
    Here Insert Picture Description
    The four drugs fall into two categories

Object Feature1(X): weight index Feature2(Y): pH
Medicine A 1 1
Medicine B 2 1
Medicine C 4 3
Medicine D 5 4

Here Insert Picture Description
Take A (1, 1) and B (2, 1) is a central point
Here Insert Picture Description
represented by the first row of the matrix to four points center1 (A) from the point of
the second row of the matrix represents a four point center2 (B) from the point

Then see column, which can be attributed to the types of small, the results are as follows:
Here Insert Picture Description
the first type: A
second category: B, C, D

Next, averaging resetting center point
c1 = (1, 1)
Here Insert Picture Description
updated as shown below:
Here Insert Picture Description
Here Insert Picture Description
Here Insert Picture Description
The first category: A, B
of the second category: C, D

Here Insert Picture Description
After updating as shown below:
Here Insert Picture Description
Here Insert Picture Description
Here Insert Picture Description
The first category: A, B
of the second category: C, D

The results did not change, stopHere Insert Picture Description

Advantages: fast, simple
Disadvantages: The end result associated with the initial point selection, easy to fall into local optimum, the need to know the value of k

achieve

import numpy as np

def kmeans(X, k, maxIt):
    '''
    X 数据集
    k k类
    maxIt最大迭代次数
    '''
    numPoints, numDim = X.shape     # numPoints:行数 numDim:列数

    dataSet = np.zeros((numPoints, numDim + 1))
    dataSet[:,:-1] = X

    # Initialize centroids randomly
    centroids = dataSet[np.random.randint(numPoints, size= k),:]    # 随机选取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: ', iterations)
        print('dataSet: ', dataSet)
        print('centroids: ', 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

def shouldStop(oldCentroids, centroids, iterations, maxIt):
    if iterations > maxIt:
        return True
    return np.array_equal(oldCentroids, centroids)  # 旧中心点和新中心点是否相同,相同返回True

# Update a label for each piece of data in the dataset
def updateLabels(dataSet, centroids):
    # For each element in the dataset, chose the closest centroids
    # 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)  # 对每一行最后一列赋最近中心点的label

def getLabelFromClosestCentroid(dataSetRow, centroids):
    label = centroids[0, -1]
    minDist = np.linalg.norm(dataSetRow - centroids[0, :-1])    # 初始化label和minDist
    # np.linalg.norm()计算两个向量的距离
    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

# Returns k random centroids, each of dimension n
def getCentroids(dataSet, k):
    result = np.zeros((k, dataSet.shape[1]))
    for i in range(1, k + 1):
        oneCluster = dataSet[dataSet[:, -1] == i, :-1]  # 找出label为i的值
        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)

iteration:  0
dataSet:  [[1. 1. 0.]
 [2. 1. 0.]
 [4. 3. 0.]
 [5. 4. 0.]]
centroids:  [[1. 1. 1.]
 [5. 4. 2.]]
minDist:  0.0
minDist:  1.0
minDist:  1.4142135623730951
minDist:  0.0
iteration:  1
dataSet:  [[1. 1. 1.]
 [2. 1. 1.]
 [4. 3. 2.]
 [5. 4. 2.]]
centroids:  [[1.5 1.  1. ]
 [4.5 3.5 2. ]]
minDist:  0.5
minDist:  0.5
minDist:  0.7071067811865476
minDist:  0.7071067811865476
final result:
[[1. 1. 1.]
 [2. 1. 1.]
 [4. 3. 2.]
 [5. 4. 2.]]
Published 11 original articles · won praise 3 · Views 922

Guess you like

Origin blog.csdn.net/qq_36551226/article/details/104225698