K-Means 聚类算法

时间:2023-03-09 20:13:10
K-Means 聚类算法

K-Means 概念定义:

K-Means 是一种基于距离的排他的聚类划分方法。

上面的 K-Means 描述中包含了几个概念:

  • 聚类(Clustering):K-Means 是一种聚类分析(Cluster Analysis)方法。聚类就是将数据对象分组成为多个类或者簇 (Cluster),使得在同一个簇中的对象之间具有较高的相似度,而不同簇中的对象差别较大。
  • 划分(Partitioning):聚类可以基于划分,也可以基于分层。划分即将对象划分成不同的簇,而分层是将对象分等级。
  • 排他(Exclusive):对于一个数据对象,只能被划分到一个簇中。如果一个数据对象可以被划分到多个簇中,则称为可重叠的(Overlapping)。
  • 距离(Distance):基于距离的聚类是将距离近的相似的对象聚在一起。基于概率分布模型的聚类是在一组对象中,找到能符合特定分布模型的对象的集合,他们不一定是距离最近的或者最相似的,而是能完美的呈现出概率分布模型所描述的模型。

K-Means 问题描述:

给定一个 n 个对象的数据集,它可以构建数据的 k 个划分,每个划分就是一个簇,并且 k ≤ n。同时还需满足:

  1. 每个组至少包含一个对象。
  2. 每个对象必须属于且仅属于一个簇。

K-Means 聚类算法

Simply speaking, K-Means clustering is an algorithm to classify or to group your objects based on attributes/features, into K number of groups. K is a positive integer number. The grouping is done by minimizing the sum of squares of distances between data and the corresponding cluster centroid. Thus, the purpose of K-means clustering is to classify the data.

例如,有如下包含 10 条数据的集合。集合中每项描述了一个人的身高(Height: inches)和体重(Weight: kilograms)。

Height Weight
-------------
(73.0, 72.6)
(61.0, 54.4)
(67.0, 99.9)
(68.0, 97.3)
(62.0, 59.0)
(75.0, 81.6)
(74.0, 77.1)
(66.0, 97.3)
(68.0, 93.3)
(61.0, 59.0)

通过按照身高和体重的聚类,可以将上述 10 条数据分组成 3 类。

Height Weight
-------------
(67.0, 99.9)
(68.0, 97.3)
(66.0, 97.3)
(68.0, 93.3) (73.0, 72.6)
(75.0, 81.6)
(74.0, 77.1) (61.0, 54.4)
(62.0, 59.0)
(61.0, 59.0)

分类结果可以描述为:中等身高并且很重、很高并且中等体重、矮并且轻。如果用图形来观察分组状况则结果一目了然。

K-Means 聚类算法

K-Means 算法实现:

由于 K-Means 算法值针对给定的完整数据集进行操作,不需要任何特殊的训练数据,所以 K-Means 是一种无监督的机器学习方法(Unsupervised Machine Learning Technique)。

K-Means 算法最常见的实现方式是使用迭代式精化启发法的 Lloyd's algorithm

  • 给定划分数量 k。创建一个初始划分,从数据集中随机地选择 k 个对象,每个对象初始地代表了一个簇中心(Cluster Centroid)。对于其他对象,计算其与各个簇中心的距离,将它们划入距离最近的簇。
  • 采用迭代的重定位技术,尝试通过对象在划分间移动来改进划分。所谓重定位技术,就是当有新的对象加入簇或者已有对象离开簇的时候,重新计算簇的平均值,然后对对象进行重新分配。这个过程不断重复,直到各簇中对象不再变化为止。
randomly assign all data items to a cluster
loop until no change in cluster assignments
compute centroids for each cluster
reassign each data item to cluster of closest centroid
end

简洁点儿的表述即为:

initialize clustering
loop
update centroids
update clustering
end loop

K-Means 聚类算法

应用 K-Means 算法到上述身高与体重的示例,聚类过程如下图所示。

K-Means 聚类算法

K-Means 聚类算法

K-Means 聚类算法

K-Means 聚类算法

K-Means 优缺点:

当结果簇是密集的,而且簇和簇之间的区别比较明显时,K-Means 的效果较好。对于大数据集,K-Means 是相对可伸缩的和高效的,它的复杂度是 O(nkt),n 是对象的个数,k 是簇的数目,t 是迭代的次数,通常 k << n,且 t << n,所以算法经常以局部最优结束。

K-Means 的最大问题是要求先给出 k 的个数。k 的选择一般基于经验值和多次实验结果,对于不同的数据集,k 的取值没有可借鉴性。另外,K-Means 对孤立点数据是敏感的,少量噪声数据就能对平均值造成极大的影响。

Basic K-Means - Lloyd's algorithm C# 代码实现:

Code below referenced from Machine Learning Using C# Succinctly by James McCaffrey, and article K-Means Data Clustering Using C#.

 using System;

 namespace ClusterNumeric
{
class ClusterNumProgram
{
static void Main(string[] args)
{
Console.WriteLine("\nBegin k-means clustering demo\n"); double[][] rawData = new double[][];
rawData[] = new double[] { , 72.6 };
rawData[] = new double[] { , 54.4 };
rawData[] = new double[] { , 99.9 };
rawData[] = new double[] { , 97.3 };
rawData[] = new double[] { , 59.0 };
rawData[] = new double[] { , 81.6 };
rawData[] = new double[] { , 77.1 };
rawData[] = new double[] { , 97.3 };
rawData[] = new double[] { , 93.3 };
rawData[] = new double[] { , 59.0 }; Console.WriteLine("Raw unclustered height (in.) weight (kg.) data:\n");
Console.WriteLine(" ID Height Weight");
Console.WriteLine("---------------------");
ShowData(rawData, , true, true); int numClusters = ;
Console.WriteLine("\nSetting numClusters to " + numClusters); Console.WriteLine("Starting clustering using k-means algorithm");
Clusterer c = new Clusterer(numClusters);
int[] clustering = c.Cluster(rawData);
Console.WriteLine("Clustering complete\n"); Console.WriteLine("Final clustering in internal form:\n");
ShowVector(clustering, true); Console.WriteLine("Raw data by cluster:\n");
Console.WriteLine(" ID Height Weight");
ShowClustered(rawData, clustering, numClusters, ); Console.WriteLine("\nEnd k-means clustering demo\n");
Console.ReadLine();
} static void ShowData(
double[][] data, int decimals,
bool indices, bool newLine)
{
for (int i = ; i < data.Length; ++i)
{
if (indices == true)
Console.Write(i.ToString().PadLeft() + " "); for (int j = ; j < data[i].Length; ++j)
{
double v = data[i][j];
Console.Write(v.ToString("F" + decimals) + " ");
} Console.WriteLine("");
} if (newLine == true)
Console.WriteLine("");
} static void ShowVector(int[] vector, bool newLine)
{
for (int i = ; i < vector.Length; ++i)
Console.Write(vector[i] + " "); if (newLine == true)
Console.WriteLine("\n");
} static void ShowClustered(
double[][] data, int[] clustering,
int numClusters, int decimals)
{
for (int k = ; k < numClusters; ++k)
{
Console.WriteLine("===================");
for (int i = ; i < data.Length; ++i)
{
int clusterID = clustering[i];
if (clusterID != k) continue;
Console.Write(i.ToString().PadLeft() + " ");
for (int j = ; j < data[i].Length; ++j)
{
double v = data[i][j];
Console.Write(v.ToString("F" + decimals) + " ");
}
Console.WriteLine("");
}
Console.WriteLine("===================");
}
}
} public class Clusterer
{
private int numClusters; // number of clusters
private int[] clustering; // index = a tuple, value = cluster ID
private double[][] centroids; // mean (vector) of each cluster
private Random rnd; // for initialization public Clusterer(int numClusters)
{
this.numClusters = numClusters;
this.centroids = new double[numClusters][];
this.rnd = new Random(); // arbitrary seed
} public int[] Cluster(double[][] data)
{
int numTuples = data.Length;
int numValues = data[].Length;
this.clustering = new int[numTuples]; for (int k = ; k < numClusters; ++k) // allocate each centroid
this.centroids[k] = new double[numValues]; InitRandom(data); Console.WriteLine("\nInitial random clustering:");
for (int i = ; i < clustering.Length; ++i)
Console.Write(clustering[i] + " ");
Console.WriteLine("\n"); bool changed = true; // change in clustering?
int maxCount = numTuples * ; // sanity check
int ct = ;
while (changed == true && ct <= maxCount)
{
++ct; // k-means typically converges very quickly
UpdateCentroids(data); // no effect if fail
changed = UpdateClustering(data); // no effect if fail
} int[] result = new int[numTuples];
Array.Copy(this.clustering, result, clustering.Length);
return result;
} private void InitRandom(double[][] data)
{
int numTuples = data.Length; int clusterID = ;
for (int i = ; i < numTuples; ++i)
{
clustering[i] = clusterID++;
if (clusterID == numClusters)
clusterID = ;
}
for (int i = ; i < numTuples; ++i)
{
int r = rnd.Next(i, clustering.Length);
int tmp = clustering[r];
clustering[r] = clustering[i];
clustering[i] = tmp;
}
} private void UpdateCentroids(double[][] data)
{
int[] clusterCounts = new int[numClusters];
for (int i = ; i < data.Length; ++i)
{
int clusterID = clustering[i];
++clusterCounts[clusterID];
} // zero-out this.centroids so it can be used as scratch
for (int k = ; k < centroids.Length; ++k)
for (int j = ; j < centroids[k].Length; ++j)
centroids[k][j] = 0.0; for (int i = ; i < data.Length; ++i)
{
int clusterID = clustering[i];
for (int j = ; j < data[i].Length; ++j)
centroids[clusterID][j] += data[i][j]; // accumulate sum
} for (int k = ; k < centroids.Length; ++k)
for (int j = ; j < centroids[k].Length; ++j)
centroids[k][j] /= clusterCounts[k]; // danger?
} private bool UpdateClustering(double[][] data)
{
// (re)assign each tuple to a cluster (closest centroid)
// returns false if no tuple assignments change OR
// if the reassignment would result in a clustering where
// one or more clusters have no tuples. bool changed = false; // did any tuple change cluster? int[] newClustering = new int[clustering.Length]; // proposed result
Array.Copy(clustering, newClustering, clustering.Length); double[] distances = new double[numClusters]; // from tuple to centroids for (int i = ; i < data.Length; ++i) // walk through each tuple
{
for (int k = ; k < numClusters; ++k)
distances[k] = Distance(data[i], centroids[k]); int newClusterID = MinIndex(distances); // find closest centroid
if (newClusterID != newClustering[i])
{
changed = true; // note a new clustering
newClustering[i] = newClusterID; // accept update
}
} if (changed == false)
return false; // no change so bail // check proposed clustering cluster counts
int[] clusterCounts = new int[numClusters];
for (int i = ; i < data.Length; ++i)
{
int clusterID = newClustering[i];
++clusterCounts[clusterID];
} for (int k = ; k < numClusters; ++k)
if (clusterCounts[k] == )
return false; // bad clustering Array.Copy(newClustering, clustering, newClustering.Length); // update
return true; // good clustering and at least one change
} // Euclidean distance between two vectors for UpdateClustering()
private static double Distance(double[] tuple, double[] centroid)
{
double sumSquaredDiffs = 0.0;
for (int j = ; j < tuple.Length; ++j)
sumSquaredDiffs += (tuple[j] - centroid[j]) * (tuple[j] - centroid[j]);
return Math.Sqrt(sumSquaredDiffs);
} // helper for UpdateClustering() to find closest centroid
private static int MinIndex(double[] distances)
{
int indexOfMin = ;
double smallDist = distances[];
for (int k = ; k < distances.Length; ++k)
{
if (distances[k] < smallDist)
{
smallDist = distances[k];
indexOfMin = k;
}
}
return indexOfMin;
}
}
}

运行结果如下:

K-Means 聚类算法

参考资料

本篇文章《K-Means 聚类算法》由 Dennis Gao 发表自博客园个人博客,未经作者本人同意禁止以任何的形式转载,任何自动的或人为的爬虫转载行为均为耍流氓。