声振论坛

 找回密码
 我要加入

QQ登录

只需一步,快速开始

查看: 5758|回复: 4

[人工智能] KMEANS 聚类算法实现程序

[复制链接]
发表于 2007-6-23 06:53 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?我要加入

x
k均值算法是模式识别的聚分类问题,这是用C实现其算法以下是程序源代码
  1. /****************************************************************************   
  2.    *     KMEANS                                    
  3.    *****************************************************************************/   
  4.    #include   <stdio.h>   
  5.    #include   <stdlib.h>   
  6.    #include   <string.h>   
  7.    #include   <conio.h>   
  8.    #include   <math.h>   
  9.       
  10.    //   FUNCTION   PROTOTYPES   
  11.       
  12.    //   DEFINES   
  13.    #define                           SUCCESS                           1   
  14.    #define                           FAILURE                           0   
  15.    #define                           TRUE                                    1   
  16.    #define                           FALSE                                 0   
  17.    #define                           MAXVECTDIM                  20   
  18.    #define                           MAXPATTERN                  20   
  19.    #define                           MAXCLUSTER                  10   

  20.    char   *f2a(double   x,   int   width){   
  21.             char   cbuf[255];   
  22.             char   *cp;   
  23.             int   i,k;   
  24.             int   d,s;   
  25.    cp=fcvt(x,width,&d,&s);   
  26.    if   (s)   {   
  27.             strcpy(cbuf,"-");   
  28.             }   
  29.       else   {   
  30.             strcpy(cbuf,"   ");   
  31.             }   /*   endif   */   
  32.    if   (d>0)   {   
  33.             for   (i=0;   i<d;   i++)   {   
  34.                      cbuf[i+1]=cp[i];   
  35.                      }   /*   endfor   */   
  36.             cbuf[d+1]=0;   
  37.             cp+=d;   
  38.             strcat(cbuf,".");   
  39.             strcat(cbuf,cp);   
  40.             }   else   {   
  41.                      if   (d==0)   {   
  42.                               strcat(cbuf,".");   
  43.                               strcat(cbuf,cp);   
  44.                               }      
  45.                         else   {   
  46.                               k=-d;   
  47.                               strcat(cbuf,".");   
  48.                               for   (i=0;   i<k;   i++)   {   
  49.                                        strcat(cbuf,"0");   
  50.                                        }   /*   endfor   */   
  51.                               strcat(cbuf,cp);   
  52.                               }   /*   endif   */   
  53.             }   /*   endif   */   
  54.    cp=&cbuf[0];   
  55.    return   cp;   
  56.    }  

  57. //   *****   Defined   structures   &   classes   *****   
  58.    struct   aCluster   {   
  59.             double                     Center[MAXVECTDIM];   

  60.         int                     Member[MAXPATTERN];     //Index   of  
  61. Vectors   belonging   to   this   cluster   
  62.             int                              NumMembers;   
  63.    };   
  64.       
  65.    struct   aVector   {   
  66.             double                     Center[MAXVECTDIM];   
  67.             int                              Size;   
  68.    };   
  69.       
  70.    class   System   {   
  71.    private:   
  72.             double                     Pattern[MAXPATTERN][MAXVECTDIM+1];   
  73.             aCluster               Cluster[MAXCLUSTER];   
  74.             int                              NumPatterns;                              //   Number   of   patterns   

  75.         int                     SizeVector;                       //  
  76. Number   of   dimensions   in   vector   
  77.             int                              NumClusters;                              //   Number   of   clusters   
  78.             void                           DistributeSamples();      //   Step   2   of   K-means   algorithm   
  79.             int                              CalcNewClustCenters();//   Step   3   of   K-means   algorithm   
  80.             double                     EucNorm(int,   int);         //   Calc   Euclidean   norm   vector   
  81.             int                              FindClosestCluster(int);   //ret   indx   of   clust   closest   to   pattern   

  82.                                                                        
  83.             //whose   index   is   arg   
  84.    public:   
  85.             system();   
  86.             int   LoadPatterns(char   *fname);                  //   Get   pattern   data   to   be   clustered   
  87.             void   InitClusters();                                                //   Step   1   of   K-means   algorithm   

  88.         void   RunKMeans();                                       //  
  89. Overall   control   K-means   process   
  90.             void   ShowClusters();                                                //   Show   results   on   screen   
  91.             void   SaveClusters(char   *fname);               //   Save   results   to   file   
  92.             void   ShowCenters();   
  93.    };   
  94.       
  95.    void   System::ShowCenters(){   
  96.    int   i,j;   
  97.    printf("Cluster   centers:\n");   
  98.    for   (i=0;   i<NumClusters;   i++)   {   
  99.             Cluster[i].Member[0]=i;   
  100.             printf("ClusterCenter[%d]=(%f,%f)\n",i,Cluster[i].Center[0],Cluster[i].Center[1]);   
  101.             }   /*   endfor   */   
  102.    printf("\n");   
  103.    }   
  104.       
  105.    int   System::LoadPatterns(char   *fname){   
  106.             FILE   *InFilePtr;   
  107.             int            i,j;   
  108.             double   x;   
  109.    if((InFilePtr   =   fopen(fname,   "r"))   ==   NULL)   
  110.                return   FAILURE;   
  111.    fscanf(InFilePtr,   "%d",   &NumPatterns);      //   Read   #   of   patterns   
  112.    fscanf(InFilePtr,   "%d",   &SizeVector);         //   Read   dimension   of   vector   
  113.    fscanf(InFilePtr,   "%d",   &NumClusters);      //   Read   #   of   clusters   for   K-Means   
  114.    for   (i=0;   i<NumPatterns;   i++)   {                           //   For   each   vector   
  115.             for   (j=0;   j<SizeVector;   j++)   {                     //   create   a   pattern   
  116.                      fscanf(InFilePtr,"%lg",&x);                     //   consisting   of   all   elements   
  117.                      Pattern[i][j]=x;   
  118.                      }   /*   endfor   */   
  119.             }   /*   endfor   */   
  120.    printf("Input   patterns:\n");   
  121.    for   (i=0;   i<NumPatterns;   i++)   {   
  122.             printf("Pattern[%d]=(%2.3f,%2.3f)\n",i,Pattern[i][0],Pattern[i][1]);   
  123.             }   /*   endfor   */   
  124.    printf("\n--------------------\n");   
  125.    return   SUCCESS;   
  126.    }   
  127.    //***************************************************************************   
  128.   //   InitClusters                                                   
  129.     //  Arbitrarily   assign   a   vector   to   each   of  the   K   clusters                                     *   
  130.    //   We   choose   the   first   K   vectors   to   do   this         
  131.    //***************************************************************************   
  132.    void   System::InitClusters(){   
  133.    int   i,j;   
  134.    printf("Initial   cluster   centers:\n");   
  135.    for   (i=0;   i<NumClusters;   i++)   {   
  136.             Cluster[i].Member[0]=i;   
  137.             for   (j=0;   j<SizeVector;   j++)   {   
  138.                      Cluster[i].Center[j]=Pattern[i][j];   
  139.                      }   /*   endfor   */   
  140.             }   /*   endfor   */   
  141.    for   (i=0;   i<NumClusters;   i++)   {   
  142.             printf("ClusterCenter[%d]=(%f,%f)\n",i,Cluster[i].Center[0],Cluster[i].Center[1]);   
  143.             }   /*   endfor   */   
  144.    printf("\n");   
  145.    }   
  146.       
  147.    void   System::RunKMeans(){   
  148.          int   converged;   
  149.          int   pass;   
  150.    pass=1;   
  151.    converged=FALSE;   
  152.    while   (converged==FALSE)   {   
  153.             printf("PASS=%d\n",pass++);   
  154.             DistributeSamples();   
  155.             converged=CalcNewClustCenters();   
  156.             ShowCenters();   
  157.             }   /*   endwhile   */   
  158.    }   
  159.       
  160.    double   System::EucNorm(int   p,   int   c){         //   Calc   Euclidean   norm   of   vector   difference   

  161.   double   dist,x;                                                   
  162. //   between   pattern   vector,   p,   and   cluster   
  163.    int  
  164. i;                                                                    
  165. //   center,   c.   
  166.    char   zout[128];   
  167.    char   znum[40];   
  168.    char   *pnum;   
  169.       
  170.    pnum=&znum[0];   
  171.    strcpy(zout,"d=sqrt(");   
  172.    printf("The   distance   from   pattern   %d   to   cluster   %d   is   calculated   as:\n",c,p);   
  173.    dist=0;   
  174.    for   (i=0;   i<SizeVector   ;i++){   
  175.             x=(Cluster[c].Center[i]-Pattern[p][i])*(Cluster[c].Center[i]-Pattern[p][i]);   
  176.             strcat(zout,f2a(x,4));   
  177.             if   (i==0)   
  178.                      strcat(zout,"+");   
  179.             dist   +=   (Cluster[c].Center[i]-Pattern[p][i])*(Cluster[c].Center[i]-Pattern[p][i]);   
  180.             }   /*   endfor   */   
  181.    printf("%s)\n",zout);   
  182.    return   dist;   
  183.    }   
  184.       
  185.    int   System::FindClosestCluster(int   pat){   
  186.             int   i,   ClustID;   
  187.             double   MinDist,   d;   
  188.    MinDist   =9.9e+99;   
  189.    ClustID=-1;   
  190.    for   (i=0;   i<NumClusters;   i++)   {   
  191.             d=EucNorm(pat,i);   
  192.             printf("Distance   from   pattern   %d   to   cluster   %d   is   %f\n\n",pat,i,sqrt(d));   
  193.             if   (d<MinDist)   {   
  194.                      MinDist=d;   
  195.                      ClustID=i;   
  196.                      }   /*   endif   */   
  197.             }   /*   endfor   */   
  198.    if   (ClustID<0)   {   
  199.             printf("Aaargh");   
  200.             exit(0);   
  201.             }   /*   endif   */   
  202.    return   ClustID;   
  203.    }   
  204.       
  205.    void   System::DistributeSamples(){   
  206.    int   i,pat,Clustid,MemberIndex;   
  207.    //Clear   membership   list   for   all   current   clusters   
  208.    for   (i=0;   i<NumClusters;i++){   
  209.             Cluster[i].NumMembers=0;   
  210.             }   
  211.    for   (pat=0;   pat<NumPatterns;   pat++)   {   
  212.             //Find   cluster   center   to   which   the   pattern   is   closest   
  213.             Clustid=   FindClosestCluster(pat);   
  214.             printf("patern   %d   assigned   to   cluster   %d\n\n",pat,Clustid);   
  215.             //post   this   pattern   to   the   cluster   
  216.             MemberIndex=Cluster[Clustid].NumMembers;   
  217.             Cluster[Clustid].Member[MemberIndex]=pat;   
  218.             Cluster[Clustid].NumMembers++;   
  219.             }   /*   endfor   */   
  220.    }   
  221.       
  222.    int      System::CalcNewClustCenters(){   
  223.             int   ConvFlag,VectID,i,j,k;   
  224.             double   tmp[MAXVECTDIM];   
  225.             char   xs[255];   
  226.             char   ys[255];   
  227.             char   nc1[20];   
  228.             char   nc2[20];   
  229.             char   *pnc1;   
  230.             char   *pnc2;   
  231.             char   *fpv;   
  232.       
  233.    pnc1=&nc1[0];   
  234.    pnc2=&nc2[0];   
  235.    ConvFlag=TRUE;   
  236.    printf("The   new   cluster   centers   are   now   calculated   as:\n");   
  237.    for   (i=0;   i<NumClusters;   i++)   {                                          //for   each   cluster   
  238.             pnc1=itoa(Cluster[i].NumMembers,nc1,10);   
  239.             pnc2=itoa(i,nc2,10);   
  240.             strcpy(xs,"Cluster   Center");   
  241.             strcat(xs,nc2);   
  242.             strcat(xs,"(1/");   
  243.             strcpy(ys,"(1/");   
  244.             strcat(xs,nc1);   
  245.             strcat(ys,nc1);   
  246.             strcat(xs,")(");   
  247.             strcat(ys,")(");   
  248.             for   (j=0;   j<SizeVector;   j++)   {                                    //   clear   workspace   
  249.                      tmp[j]=0.0;   
  250.                      }   /*   endfor   */   
  251.             for   (j=0;   j<Cluster[i].NumMembers;   j++)   {   //traverse   member   vectors   
  252.                      VectID=Cluster[i].Member[j];   
  253.                      for   (k=0;   k<SizeVector;   k++)   {                           //traverse   elements   of   vector   

  254.                     tmp[k]   +=   Pattern[VectID][k];               //
  255.   add   (member)   pattern   elmnt   into   temp   
  256.                               if   (k==0)   {   
  257.                                              strcat(xs,f2a(Pattern[VectID][k],3));   
  258.                                        }   else   {   
  259.                                              strcat(ys,f2a(Pattern[VectID][k],3));   
  260.                                              }   /*   endif   */   
  261.                               }   /*   endfor   */   
  262.                      if(j<Cluster[i].NumMembers-1){   
  263.                               strcat(xs,"+");   
  264.                               strcat(ys,"+");   
  265.                               }   
  266.                            else   {   
  267.                               strcat(xs,")");   
  268.                               strcat(ys,")");   
  269.                               }   
  270.                      }   /*   endfor   */   
  271.             for   (k=0;   k<SizeVector;   k++)   {                                    //traverse   elements   of   vector   
  272.                      tmp[k]=tmp[k]/Cluster[i].NumMembers;   
  273.                      if   (tmp[k]   !=   Cluster[i].Center[k])   
  274.                               ConvFlag=FALSE;   
  275.                      Cluster[i].Center[k]=tmp[k];   
  276.                      }   /*   endfor   */   
  277.             printf("%s,\n",xs);   
  278.             printf("%s\n",ys);   
  279.             }   /*   endfor   */   
  280.    return   ConvFlag;   
  281.    }   
  282.       
  283.    void   System::ShowClusters(){   
  284.             int   cl;   
  285.    for   (cl=0;   cl<NumClusters;   cl++)   {   
  286.             printf("\nCLUSTER   %d   ==>[%f,%f]\n",   cl,Cluster[cl].Center[0],Cluster[cl].Center[1]);   
  287.             }   /*   endfor   */   
  288.    }   
  289.       
  290.    void   System::SaveClusters(char   *fname){   
  291.    }   
  292.       
  293.       
  294.    main(int   argc,   char   *argv[])   {   
  295.             System   kmeans;   
  296.    if   (argc<2)   {   
  297.             printf("USAGE:   KMEANS   PATTERN_FILE\n");   
  298.             exit(0);   
  299.             }   
  300.    if   (kmeans.LoadPatterns(argv[1])==FAILURE   ){   
  301.             printf("UNABLE   TO   READ   PATTERN_FILE:%s\n",argv[1]);   
  302.             exit(0);   
  303.             }   
  304.    kmeans.InitClusters();   
  305.    kmeans.RunKMeans();   
  306.    kmeans.ShowClusters();   
  307.    }   
复制代码


来自:中国视觉网

[ 本帖最后由 christy 于 2007-6-23 06:55 编辑 ]

评分

1

查看全部评分

回复
分享到:

使用道具 举报

 楼主| 发表于 2007-6-23 06:56 | 显示全部楼层
基于MATLAB的KMEANS 聚类程序

程序和数据如下:
  1. %K-means算法主程序
  2. k=4;
  3. x =[ 1.2126    2.1338    0.5115    0.2044
  4.    -0.9316    0.7634    0.0125   -0.2752
  5.    -2.9593    0.1813   -0.8833    0.8505
  6.     3.1104   -2.5393   -0.0588    0.1808
  7.    -3.1141   -0.1244   -0.6811    0.9891
  8.    -3.2008    0.0024   -1.2901    0.9748
  9.    -1.0777    1.1438    0.1996    0.0139
  10.    -2.7213   -0.1909    0.1184    0.1013
  11.    -1.1467    1.3820    0.1427   -0.2239
  12.     1.1497    1.9414   -0.3035    0.3464
  13.     2.6993   -2.2556    0.1637   -0.0139
  14.    -3.0311    0.1417    0.0888    0.1791
  15.    -2.8403   -0.1809   -0.0965    0.0817
  16.     1.0118    2.0372    0.1638   -0.0349
  17.    -0.8968    1.0260   -0.1013    0.2369
  18.     1.1112    1.8802   -0.0291   -0.1506
  19.     1.1907    2.2041   -0.1060    0.2167
  20.    -1.0114    0.8029   -0.1317    0.0153
  21.    -3.1715    0.1041   -0.3338    0.0321
  22.     0.9718    1.9634    0.0305   -0.3259
  23.    -1.0377    0.8889   -0.2834    0.2301
  24.    -0.8989    1.0185   -0.0289    0.0213
  25.    -2.9815   -0.4798    0.2245    0.3085
  26.    -0.8576    0.9231   -0.2752   -0.0091
  27.    -3.1356    0.0026   -1.2138    0.7733
  28.     3.4470   -2.2418    0.2014   -0.1556
  29.     2.9143   -1.7951    0.1992   -0.2146
  30.     3.4961   -2.4969   -0.0121    0.1315
  31.    -2.9341   -0.1071   -0.7712    0.8911
  32.    -2.8105   -0.0884   -0.0287   -0.1279
  33.     3.1006   -2.0677   -0.2002   -0.1303
  34.     0.8209    2.1724    0.1548    0.3516
  35.    -2.8500    0.3196    0.1359   -0.1179
  36.    -2.8679    0.1365   -0.5702    0.7626
  37.    -2.8245   -0.1312    0.0881   -0.1305
  38.    -0.8322    1.3014   -0.3837    0.2400
  39.    -2.6063    0.1431    0.1880    0.0487
  40.    -3.1341   -0.0854   -0.0359   -0.2080
  41.     0.6893    2.0854   -0.3250   -0.1007
  42.     1.0894    1.7271   -0.0176    0.6553
  43.    -2.9851   -0.0113    0.0666   -0.0802
  44.     1.0371    2.2724    0.1044    0.3982
  45.    -2.8032   -0.2737   -0.7391    1.0277
  46.    -2.6856    0.0619   -1.1066    1.0485
  47.    -2.9445   -0.1602   -0.0019    0.0093
  48.     1.2004    2.1302   -0.1650    0.3413
  49.     3.2505   -1.9279    0.4462   -0.2405
  50.    -1.2080    0.8222    0.1671    0.1576
  51.    -2.8274    0.1515   -0.9636    1.0675
  52.     2.8190   -1.8626    0.2702    0.0026
  53.     1.0507    1.7776   -0.1421    0.0999
  54.    -2.8946    0.1446   -0.1645    0.3071
  55.    -1.0105    1.0973    0.0241    0.1628
  56.    -2.9138   -0.3404    0.0627    0.1286
  57.    -3.0646   -0.0008    0.3819   -0.1541
  58.     1.2531    1.9830   -0.0774    0.2413
  59.     1.1486    2.0440   -0.0582   -0.0650
  60.    -3.1401   -0.1447   -0.6580    0.9562
  61.    -2.9591    0.1598   -0.6581    1.1937
  62.    -2.9219   -0.3637   -0.1538   -0.2085
  63.     2.8948   -2.2745    0.2332   -0.0312
  64.    -3.2972   -0.0219   -0.0288   -0.1436
  65.    -1.2737    0.7648    0.0643    0.0858
  66.    -1.0690    0.8108   -0.2723    0.3231
  67.    -0.5908    0.7508   -0.5456    0.0190
  68.     0.5808    2.0573   -0.1658    0.1709
  69.     2.8227   -2.2461    0.2255   -0.3684
  70.     0.6174    1.7654   -0.3999    0.4125
  71.     3.2587   -1.9310    0.2021    0.0800
  72.     1.0999    1.8852   -0.0475   -0.0585
  73.    -2.7395    0.2585   -0.8441    0.9987
  74.    -1.2223    1.0542   -0.2480   -0.2795
  75.    -2.9212   -0.0605   -0.0259    0.2591
  76.     3.1598   -2.2631    0.1746    0.1485
  77.     0.8476    1.8760   -0.2894   -0.0354
  78.     2.9205   -2.2418    0.4137   -0.2499
  79.     2.7656   -2.1768    0.0719   -0.1848
  80.    -0.8698    1.0249   -0.2084   -0.0008
  81.    -1.1444    0.7787   -0.4958    0.3676
  82.    -1.0711    1.0450   -0.0477   -0.4030
  83.     0.5350    1.8110   -0.0377    0.1622
  84.     0.9076    1.8845   -0.1121    0.5700
  85.    -2.7887   -0.2119    0.0566    0.0120
  86.    -1.2567    0.9274    0.1104    0.1581
  87.    -2.9946   -0.2086   -0.8169    0.6662
  88.     1.0536    1.9818   -0.0631    0.2581
  89.    -2.8465   -0.2222    0.2745    0.1997
  90.    -2.8516    0.1649   -0.7566    0.8616
  91.    -3.2470    0.0770    0.1173   -0.1092
  92.    -2.9322   -0.0631   -0.0062   -0.0511
  93.    -2.7919    0.0438   -0.1935   -0.5023
  94.     0.9894    1.9475   -0.0146   -0.0390
  95.    -2.9659   -0.1300    0.1144    0.3410
  96.    -2.7322   -0.0427   -1.0758    0.9718
  97.    -1.4852    0.8592   -0.0503   -0.1373
  98.     2.8845   -2.1465   -0.0533   -0.1044
  99.    -3.1470    0.0536    0.1073    0.3323
  100.     2.9423   -2.1572    0.0505    0.1180
  101.    -3.0683    0.3434   -0.6563    0.8960
  102.     1.3215    2.0951   -0.1557    0.3994
  103.    -0.7681    1.2075   -0.2781    0.2372
  104.    -0.6964    1.2360   -0.3342    0.1662
  105.    -0.6382    0.8204   -0.2587    0.3344
  106.    -3.0233   -0.1496   -0.2607   -0.0400
  107.    -0.8952    0.9872    0.0019    0.3138
  108.    -0.8172    0.6814   -0.0691    0.1009
  109.    -3.3032    0.0571   -0.0243   -0.1405
  110.     0.7810    1.9013   -0.3996    0.7374
  111.    -0.9030    0.8646   -0.1498    0.1112
  112.    -0.8461    0.9261   -0.1295   -0.0727
  113.     2.8182   -2.0818   -0.1430   -0.0547
  114.     2.9295   -2.3846   -0.0244   -0.1400
  115.     1.0587    2.2227   -0.1250    0.0957
  116.     3.0755   -1.7365   -0.0511    0.1500
  117.    -1.3076    0.8791   -0.3720    0.0331
  118.    -2.8252   -0.0366   -0.6790    0.7374
  119.    -2.6551   -0.1875    0.3222    0.0483
  120.    -2.9659   -0.1585    0.4013   -0.1402
  121.    -3.2859   -0.1546    0.0104   -0.1781
  122.    -0.6679    1.1999    0.1396   -0.3195
  123.    -1.0205    1.2226    0.1850    0.0050
  124.    -3.0091   -0.0186   -0.9111    0.9663
  125.    -3.0339    0.1377   -0.9662    1.0664
  126.     0.8952    1.9594   -0.3221    0.3579
  127.    -2.8481    0.1963   -0.1428    0.0382
  128.     1.0796    2.1353   -0.0792    0.6491
  129.    -0.8732    0.8985   -0.0049    0.0068
  130.     1.0620    2.1478   -0.1275    0.3553
  131.     3.4509   -1.9975    0.1285   -0.1575
  132.    -3.2280   -0.0640   -1.1513    0.8235
  133.    -0.6654    0.9402    0.0577   -0.0175
  134.    -3.2100    0.2762   -0.1053    0.0626
  135.     3.0793   -2.0043    0.2948    0.0411
  136.     1.3596    1.9481   -0.0167    0.3958
  137.    -3.1267    0.1801    0.2228    0.1179
  138.    -0.7979    0.9892   -0.2673    0.4734
  139.     2.5580   -1.7623   -0.1049   -0.0521
  140.    -0.9172    1.0621   -0.0826    0.1501
  141.    -0.7817    1.1658    0.1922    0.0803
  142.     3.1747   -2.1442    0.1472   -0.3411
  143.     2.8476   -1.8056   -0.0680    0.1536
  144.    -0.6175    1.4349   -0.1970   -0.1085
  145.     0.7308    1.9656    0.2602    0.2801
  146.    -1.0310    1.0553   -0.2928   -0.1647
  147.    -2.9251   -0.2095    0.0582   -0.1813
  148.    -0.9827    1.2720   -0.2225    0.2563
  149.    -1.0830    1.1158   -0.0405   -0.1181
  150.    -2.8744    0.0195   -0.3811    0.1455
  151.     3.1663   -1.9241    0.0455    0.1684
  152.    -1.0734    0.7681   -0.4725   -0.1976];
  153. [n,d] = size(x);
  154. bn=round(n/k*rand);%第一个随机数在前1/K的范围内
  155. nc=[x(bn,:);x(2*bn,:);x(3*bn,:);x(4*bn,:)];%初始聚类中心

  156. [cid,nr,centers] = kmeans(x,k,nc)%调用kmeans函数

  157. for i=1:150,
  158.     if cid(i)==1,
  159.       plot(x(i,1),x(i,2),'r*') % 显示第一类
  160.       hold on
  161.     else
  162.      if cid(i)==2,
  163.          plot(x(i,1),x(i,2),'b*') %显示第二类
  164.          hold on
  165.      else
  166.          if cid(i)==3,
  167.              plot(x(i,1),x(i,2),'g*') %显示第三类
  168.              hold on
  169.          else
  170.                if cid(i)==4,
  171.              plot(x(i,1),x(i,2),'k*') %显示第四类
  172.              hold on
  173.                end
  174.          end
  175.      end
  176.     end
  177. end
  178. strt=['红色*为第一类;蓝色*为第二类;绿色*为第三类;黑色*为第四类' ];
  179. text(-4,-3.6,strt);
复制代码
函数如下:
  1. %BasicKMeans.m主类
  2. function [cid,nr,centers] = kmeans(x,k,nc)
  3. [n,d] = size(x);
  4. % 设置cid为分类结果显示矩阵
  5. cid = zeros(1,n);
  6. % Make this different to get the loop started.
  7. oldcid = ones(1,n);
  8. % The number in each cluster.
  9. nr = zeros(1,k);
  10. % Set up maximum number of iterations.
  11. maxgn= 100;
  12. iter = 1;
  13. while iter < maxgn
  14. %计算每个数据到聚类中心的距离
  15. for i = 1:n
  16.   dist = sum((repmat(x(i,:),k,1)-nc).^2,2);
  17.   [m,ind] = min(dist); % 将当前聚类结果存入cid中
  18.   cid(i) = ind;
  19. end
  20. for i = 1:k
  21. %找到每一类的所有数据,计算他们的平均值,作为下次计算的聚类中心
  22.   ind = find(cid==i);
  23.   nc(i,:) = mean(x(ind,:));
  24.   % 统计每一类的数据个数
  25.   nr(i) = length(ind);
  26. end
  27.   iter = iter + 1;
  28. end

  29. % Now check each observation to see if the error can be minimized some more.
  30. % Loop through all points.
  31. maxiter = 2;
  32. iter = 1;
  33. move = 1;
  34. while iter < maxiter & move ~= 0
  35. move = 0;
  36. % 对所有的数据进行再次判断,寻求最佳聚类结果
  37. for i = 1:n
  38.   dist = sum((repmat(x(i,:),k,1)-nc).^2,2);
  39.   r = cid(i);  % 将当前数据属于的类给r
  40.   dadj = nr./(nr+1).*dist'; % 计算调整后的距离
  41.   [m,ind] = min(dadj); % 早到该数据距哪个聚类中心最近
  42.   if ind ~= r  % 如果不等则聚类中心移动
  43.    cid(i) = ind;%将新的聚类结果送给cid
  44.    ic = find(cid == ind);%重新计算调整当前类别的聚类中心
  45.    nc(ind,:) = mean(x(ic,:));
  46.    move = 1;
  47.   end
  48. end
  49. iter = iter+1;
  50. end
  51. centers = nc;
  52. if move == 0
  53. disp('No points were moved after the initial clustering procedure.')
  54. else
  55. disp('Some points were moved after the initial clustering procedure.')
  56. end
复制代码
分类效果图
14_7774_ecd62647e667583.jpg

来自:中国AI创业研发俱乐部
发表于 2007-11-2 11:01 | 显示全部楼层

请求帮忙!

如果我输入的是彩色图像,我如何能用该算法把我图像里的颜色用聚类的算法实现?
发表于 2010-6-22 14:36 | 显示全部楼层
:@) 下载来我看看,谢谢LZ
发表于 2011-7-28 12:23 | 显示全部楼层
收藏了,学习一下
您需要登录后才可以回帖 登录 | 我要加入

本版积分规则

QQ|小黑屋|Archiver|手机版|联系我们|声振论坛

GMT+8, 2024-9-28 06:49 , Processed in 0.083600 second(s), 26 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表