⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 c均值法.cpp

📁 模式识别中动态聚类方法的C均值算法的c++源程序。一种比较好的算法程序。
💻 CPP
字号:
// c均值法.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "math.h"
#include "iostream.h"

#define NUM 5
#define NN 8
#define CNUM 4
typedef struct
{
	double X[NUM];
}pattern;

pattern TOTAL[NN]={{1,2,2,2,1},{2,30,30,4,5},{1,10,40,30,20},{2,3,2,1,2},{1,2,2,1,2},{200,200,700,800,900},{3,3,5,4,3},{1,1,1,1,1}};
pattern CT[CNUM]={{1,2,2,2,1},{2,30,30,4,5},{1,10,40,30,20},{2,3,2,1,2}};
pattern OLDCT[CNUM];
int CINNUM[CNUM];
int CINDEX[CNUM][NN];

double Euclidean(pattern a,pattern b)
{
	int i;
	double d=0.0;
	for(i=0;i<NUM;i++)
		d+=(a.X[i]-b.X[i])*(a.X[i]-b.X[i]);
	return sqrt(d);
}

bool ctest(pattern CT[CNUM],pattern OLDCT[CNUM])
{
	int i;
	double d=0.0;
	for(i=0;i<CNUM;i++)
		d+=Euclidean(CT[i],OLDCT[i]);
	if(d<0.000001)
		return true;
	else
		return false;
}

void cequal()
{
	int i,j,k,point;
	double d;
	do
	{
		for(i=0;i<NUM;i++)
		{
			for(j=0;j<CNUM;j++)
			{
				OLDCT[j].X[i]=CT[j].X[i];
			}
		}
		for(i=0;i<NUM;i++)
		{
			for(j=0;j<CNUM;j++)
			{
				for(k=0;k<CINNUM[j];k++)
				{
					d=d+TOTAL[CINDEX[j][k]].X[i];
				}
				if(CINNUM[j]!=0)
				CT[j].X[i]=d/CINNUM[j];
			}
		}
		for(i=0;i<CNUM;i++)
			CINNUM[i]=0;
		for(i=0;i<NN;i++)
		{
			point=0;
			d=Euclidean(TOTAL[i],CT[0]);
			for(j=0;j<CNUM;j++)
			{
				if(d>Euclidean(TOTAL[i],CT[j]))
				{
					d=Euclidean(TOTAL[i],CT[j]);
					point=j;
				}
			}
			CINDEX[point][CINNUM[point]]=i;
			CINNUM[point]++;
			cout<<point<<" "<<CINNUM[point]<<" "<<CINDEX[j][CINNUM[point]]<<endl;
		}

	}while(!ctest(CT,OLDCT));
}

void print()
{
	//int i,j;
	int i,j;
	for(i=0;i<CNUM;i++)
	{
		cout<<"第"<<i<<"类的元素序号为:"<<endl;
        for(j=0;j<CINNUM[i];j++)
			cout<<CINDEX[i][j]<<"    ";
		cout<<endl;
	}
}

int main(int argc, char* argv[])
{
	cequal();
	print();
	//int i,j;
	//for(i=0;i<CNUM;i++)
	//	cout<<CINNUM[i]<<" ";
	//return 0;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -