资源简介
K-means聚类算法c语言实现。代码正确,有详细注释,欢迎下载参考!
代码片段和文件信息
#include
#include
#include
#include
#include
#define N 11
#define K 3
typedef struct
{
float x;
float y;
}Point;
int belongCluster[N]; /// 判断每个点属于哪个簇
Point point[N] = {
{2.0 10.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}
};
Point clusterCenter[K]; /// 保存每个簇的中心点
float getDistance(Point point1 Point point2)
{
float d;
d = sqrt((point1.x - point2.x) * (point1.x - point2.x) + (point1.y - point2.y) * (point1.y - point2.y));
return d;
}
/// 计算每个簇的中心点
void getCenter(int belongCluster[N])
{
Point tep;
int i j count = 0;
for(i = 0; i < K; ++i)
{
count = 0;
tep.x = 0.0; /// 每算出一个簇的中心点值后清0
tep.y = 0.0;
for(j = 0; j < N; ++j)
{
if(i == belongCluster[j])
{
count++;
tep.x += point[j].x;
tep.y += point[j].y;
}
}
tep.x /= count;
tep.y /= count;
clusterCenter[i] = tep;
}
for(i = 0; i < K; ++i)
{
printf(“The new centerCluster point of %d is : \t( %f %f )\n“ i+1 clusterCenter[i].x clusterCenter[i].y);
}
}
/// 计算平方误差函数,在每个簇中每个点与中心点的距离平方和
float getE()
{
int i j;
float cnt = 0.0 sum = 0.0;
for(i = 0; i < K; ++i)
{
for(j = 0; j < N; ++j)
{
if(i == belongCluster[j])
{
cnt = (point[j].x - clusterCenter[i].x) * (point[j].x - clusterCenter[i].x) + (point[j].y - clusterCenter[i].y) * (point[j].y - clusterCenter[i].y);
sum += cnt;
}
}
}
return sum;
}
/// 把N个点聚类,标出每个点属于哪个中心
void cluster()
{
int i j q;
float min;
float distance[N][K];
for(i = 0; i < N; ++i)
评论
共有 条评论