k-means算法
算法思想
K-means主要思想是在给定K值和若干样本(点)的情况下,把每个样本(点)分到离其最近的类簇中心点所代表的类簇中,所有点分配完毕之后,根据一个类簇内的所有点重新计算该类簇的中心点(取平均值),然后再迭代的进行分配点和更新类簇中心点的步骤,直至类簇中心点的变化很小,或者达到指定的迭代次数。
用C语言实现
自定义的数据集共有15个:
(2, 7) (2, 5) (8, 4)
(5, 8) (7, 5) (6, 4)
(1, 2) (4, 9) (7, 3)
(1, 3) (3, 9) (6, 7)
(3, 1) (4, 8) (5, 6)
代码运行的聚类结果:
Cluster-1: (2, 7), (2, 5), (5, 8), (4, 9), (3, 9), (4, 8)
Cluster-2: (8, 4), (7, 5), (6, 4), (7, 3), (6, 7), (5, 6)
Cluster-3: (1, 2), (1, 3), (3, 1)
代码
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#define N 15
#define K 3
typedef struct
{
float x;
float y;
}Point;
int center[N]; /// 判断每个点属于哪个簇
Point point[N] = {
{
2.0, 7.0},
{
2.0, 5.0},
{
8.0, 4.0},
{
5.0, 8.0},
{
7.0, 5.0},
{
6.0, 4.0},
{
1.0, 2.0},
{
4.0, 9.0},
{
7.0, 3.0},
{
1.0, 3.0},
{
3.0, 9.0},
{
6.0, 7.0},
{
3.0, 1.0},
{
4.0, 8.0},
{
5.0, 6.0}
};
Point mean[K];