K-mean算法
前言:K-mean算法的思想和实现都不难,整个算法主要分为两步:1、找到与每个样本距离最近的质心,将样本与最近的质心关联起来;2、根据每个质心的关联样本,重新计算质心的位置。下面是吴恩达课件里的说明,说的十分清晰。
在实现K-mean算法的过程中,质心的初始位置一般是随机选取样本点作为质心。例如需要将样本分为K类,那么从样本中随机选取K个样本作为初始化质心即可。样本的初始位置选取与最终的分类效果有很大的关系。
下面给出作业中的关键代码。
findClosestCentroids.m
这个函数实现的功能是找到距离每个样本点最近的质心,并将质心的序号用一个矩阵存储起来,便于之后重新计算质心的位置使用。如下图给出的解释,其中c(i)和idx(i)是一样的,都代表距离第i个样本点最近的质心的序号。
因此,这个函数的主要实现是一个距离计算并求最小值的过程。下面给出MATLAB实现代码。
function idx = findClosestCentroids(X, centroids)
%FINDCLOSESTCENTROIDS computes the centroid memberships for every example
% idx = FINDCLOSESTCENTROIDS (X, centroids) returns the closest centroids
% in idx for a dataset X where each row is a single example. idx = m x 1
% vector of centroid assignments (i.e. each entry in range [1..K])
%
% Set K
K = size(centroids, 1);%质心的数量
% You need to return the following variables correctly.
idx = zeros(size(X,1), 1);%用于存储每个点最近的质心的序号
% ====================== YOUR CODE HERE ======================
% Instructions: Go over every example, find its closest centroid, and store
% the index inside idx at the appropriate location.
% Concretely, idx(i) should contain the index of the centroid
% closest to example i. Hence, it should be a value in the
% range 1..K
%
% Note: You can use a for-loop over the examples to compute this.
%
val = zeros(K,1);%创建一个变量用于存储每个中心点到数据点的距离,之后取其中最小的
for i = 1 : size(X,1);
for j =