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

📄 c.cpp

📁 模式识别 均值 该方法取定C个类别和选取C个初始聚类中心
💻 CPP
字号:
#include <iostream.h>
#include <stdio.h>
#include <math.h>
#define  N 10
int c;
#define  eps   0.00001
struct Pointf//放模式特征向量
{
	int s;
	float x;
	float y;
};

struct PointZ //放中心向量
{
	float x;
	float y;
};

float CalDistancefZ(Pointf x1,PointZ x2)//计算模式特征向量到聚类中心的距离
{
	return sqrtf((x1.x-x2.x)*(x1.x-x2.x)+(x1.y-x2.y)*(x1.y-x2.y));
}
void main()
{   PointZ Z[2];
    Pointf C[2][10];
  
    int i,j;
    int counter1,counter2;
    float temp1x=0;
    float temp1y=0;
    float temp2x=0;
    float temp2y=0;
	float dispx0;
    float dispy0;
    float dispx1;
    float dispy1;
	Pointf pts[N]={
		{0,0.0,0.0},{1,3.0,8.0},{2,2.0,2.0},{3,1.0,1.0},{4,5.0,3.0},
		{5,4.0,8.0},{6,6.0,3.0},{7,5.0,4.0},{8,6.0,4.0},{9,7.0,5.0},
	};
     cout<<"样本集是:"<<endl;
    for(i=0;i<N;i++)
	{
        cout<<"X["<<i<<"]=("<<pts[i].x<<","<<pts[i].y<<"),";
		
		if((i+1)%5==0)
		{
			cout<<"\n";
		}
		
	}
	cout<<"\n";
    cout<<"\n";
step1://选取初始聚类中心
    int count=1;
    Z[0].x=pts[0].x;
    Z[0].y=pts[0].y;
    Z[1].x=pts[2].x;
    Z[1].y=pts[2].y;
    cout<<"第一个初始聚类中心是:("<<Z[0].x<<","<<Z[0].y<<")"<<"\n";
    cout<<"第二个初始聚类中心是:("<<Z[1].x<<","<<Z[1].y<<")";
    cout<<"\n";
step2://classfy
    cout<<"这是第"<<count<<"次迭代:"<<"\n";
    float d1[N];
    float d2[N];
    counter1=0;
	counter2=0;
    for(i=0;i<N;i++)
	{  
 	   d1[i]=CalDistancefZ(pts[i],Z[0]);
       d2[i]=CalDistancefZ(pts[i],Z[1]);
	   if(d1[i]<d2[i])
	   {  
		counter1++;
		C[0][counter1].s=pts[i].s;
	    C[0][counter1].x=pts[i].x;
		C[0][counter1].y=pts[i].y;
	   }
	   else
	   { 
		counter2++;
		C[1][counter2].s=pts[i].s;
	    C[1][counter2].x=pts[i].x;
		C[1][counter2].y=pts[i].y;
	   }
	}
step3://修正聚类中心
	int flag=0;
    temp1x=0;temp1y=0;
    for(j=1;j<=counter1;j++)
       {
		temp1x+=C[0][j].x;
	    temp1y+=C[0][j].y;
	   }
	dispx0=temp1x/(counter1);
    dispy0=temp1y/(counter1);
    temp2x=0;temp2y=0;
    for(j=1;j<=counter2;j++)
       {
	    temp2x+=C[1][j].x;
	    temp2y+=C[1][j].y;
	   }
    dispx1=temp2x/(counter2);
    dispy1=temp2y/(counter2);
  if(Z[0].x!=dispx0||Z[0].y!=dispy0||Z[1].x!=dispx1||Z[1].y!=dispy1)
		{flag=1;}
        Z[0].x=dispx0;
		Z[0].y=dispy0;
		Z[1].x=dispx1;
		Z[1].y=dispy1;
  cout<<"第一个聚类中心是:("<<Z[0].x<<","<<Z[0].y<<")"<<"\n";
  cout<<"包含的元素有:";
  for(j=1;j<=counter1;j++)
		   {
	        cout<<"X["<<C[0][j].s<<"],";
		   }
		   cout<<"\n";
  cout<<"第二个聚类中心是:("<<Z[1].x<<","<<Z[1].y<<")"<<"\n";
  cout<<"包含的元素有:";
  for(j=1;j<=counter2;j++)
		   {
			 cout<<"X["<<C[1][j].s<<"],";
		   }
		   cout<<"\n" ;
   count++;
step4:
  if(flag==1 )
  {
    goto step2;
  }
  else
  { cout<<"分类完毕!";
  }
}
   

⌨️ 快捷键说明

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