雷達點跡聚類Kmeans C++演練--Apple的學(xué)習(xí)筆記

聚類的應(yīng)用

上周在互聯(lián)網(wǎng)瀏覽無意間了解到雷達信號處理的最后一步是點跡輸出变逃,用的是聚類算法。
搜索了下聚類算法箕宙,好多呀!不過發(fā)現(xiàn)kmeans是我之前學(xué)機器學(xué)習(xí)課程中KNN分類用的资盅。python只要幾行代碼就解決了,用C++演練一把恃慧,就當(dāng)我在開發(fā)雷達了,沒有代碼優(yōu)化渺蒿,僅僅實現(xiàn)功能~

Kmeans的思想

就是根據(jù)離哪類近就判斷屬于哪類痢士,來進行歸類和預(yù)測的。

  1. 初始化K個類茂装,然后每個類初始化一個中心點怠蹂。
  2. 對比每個點到類的距離,到哪個類近就屬于哪類少态。
  3. 通過均值更新每一類的中心城侧。
  4. 循環(huán)第2和第3步驟,知道每個類的中心不再移動彼妻。

昨天完成code嫌佑,今天測試調(diào)試了下,主要解決了一些小bug和一個大bug(在執(zhí)行完聚類過程后澳骤,居然某一類的數(shù)量為0個歧强。至少應(yīng)該有一個為它本身吧澜薄!后來通過萬能的debug解決了)

重要參數(shù)介紹

我的初始化值用的是隨機選擇为肮,初始化值選的不適合,它更新中心點的次數(shù)也會曾多肤京。
如下代碼的輸入點為24個颊艳,選擇設(shè)置為4類茅特,測試點為2個。
同學(xué)們有需要可以自行修改這些可配置參數(shù)棋枕,以適配你的應(yīng)用白修。

C++代碼

KNN.hpp

    /* Author: AppleCai Date 2019/04/28 */
    #include<vector>
    #include<iostream>
    #include<cmath>
    using namespace std;
    
    #define OBJ_LEN  24
    #define TEST_LEN 2
    class Kmeans
    {
    public:
    typedef struct mypoint
    {
        float x;
        float y;
        int tag;
    }st_mypoint;
    
    enum my_enum
    {
        NO=0,
        YES
    };
    Kmeans(int KgNum);
    void dataInit(st_mypoint input[]);
    void updateCenter(st_mypoint point[]);  //set Kcenter;
    float calDistance(st_mypoint p1,st_mypoint p2); //Euclidean distance
    void Cluster(st_mypoint point[]);  //set the Kgrouplist;
    void KNN(st_mypoint input[]);
    bool checkEnd(vector<st_mypoint> p1group,vector<st_mypoint> p2group);
    void KNNtest(st_mypoint input[]);
    
    private:
        int KgroupNum;               //the number of cluster
        vector<st_mypoint> Kcenter;   //the center of each cluster
        vector<vector<int>> Kgrouplist;      //the point to the related group
    };

KNN.cpp

    /* Author: AppleCai Date 2019/04/28 */
    #include "KNN.hpp"
    
    Kmeans::Kmeans(int KgNum)
    {
          KgroupNum = KgNum;
    }
    
    /* init the K group and select the group center */
    void Kmeans::dataInit(st_mypoint input[])
    {
          int i,N;
          for(i=0;i<KgroupNum;i++)
          {
                N = rand() % OBJ_LEN; 
                Kcenter.push_back(input[N]);
                cout<<"Kcenter="<<Kcenter[i].x<<" "<<Kcenter[i].y<<endl;
          }
          for(i=0;i<KgroupNum;i++)  /* we shall init the space,otherwise it will said not available in the running time*/
        {
            vector<int> temp;
            Kgrouplist.push_back(temp);
        } 
    }
    
    /*Calculate average value,update center*/
    void Kmeans::updateCenter(st_mypoint point[])
    {
          int i=0;
          int j=0;
          for(i=0;i<KgroupNum;i++)
          {
                st_mypoint sum={0,0};
                for(j=0;j<Kgrouplist.at(i).size();j++)
                {
                      point[Kgrouplist[i][j]].tag = i;   /* add tag to each of the point */
                      // for debug
                      // cout<<"Kgrouplist[i][j]"<<point[Kgrouplist[i][j]].x<<point[Kgrouplist[i][j]].y<<"size"<<Kgrouplist.at(i).size()<<endl;
                      sum.x=(sum.x+point[(Kgrouplist[i][j])].x);
                      sum.y=(sum.y+point[(Kgrouplist[i][j])].y);
                }
                sum.x = sum.x/Kgrouplist.at(i).size();
                sum.y = sum.y/Kgrouplist.at(i).size();
                Kcenter[i]=sum;
                Kcenter[i].tag = i;      /* add tag for center */
                cout<<"updateCenter=["<<i<<"]="<<sum.x<<" "<<sum.y<<" "<<Kcenter[i].tag<<endl;
          }     
    }
    
    /*Euclidean distance*/
    float Kmeans::calDistance(st_mypoint p1,st_mypoint p2)
    {
          float dis=0;
          dis=sqrt(pow((p1.x-p2.x),2)
                +pow((p1.y-p2.y),2)
                );
          return dis;
    }
    
    /* Cluster */
    void Kmeans::Cluster(st_mypoint point[])
    {
          float mindistance;
          float curdistance;
          int index=0;
          int i,j;
    
          //shall add, otherwise the size of Kgrouplist will become large
          for(i=0;i<KgroupNum;i++)
        {
                Kgrouplist.at(i).clear(); 
        }     
             
          for(j=0;j<OBJ_LEN;j++)
          {
                /* calculate the distance between the first group and point,pretend that's the smallest one*/
                mindistance= calDistance(Kcenter[0],point[j]);
                index=0;  /* prepare group list index, suppose the first group is the nearst one*/
                for(i=1;i<KgroupNum;i++)
                {
                      curdistance = calDistance(Kcenter[i],point[j]);
                      if(curdistance<mindistance)
                      {
                            mindistance = curdistance;
                            index=i;
                      }
                }
                /* put the point to the minimal group list */
                Kgrouplist.at(index).push_back(j);
          }
          
          /* TODO: used for debug,later shall delete*/
          // for(i=0;i<KgroupNum;i++)
          // {
          //       cout<<"Size of grouplist="<<Kgrouplist[i].size()<<endl;
          //       for(j=0;j<Kgrouplist[i].size();j++)
          //       {
          //             cout<<"Kgrouplist["<<i<<"]["<<j<<"]="<<Kgrouplist[i][j]<<endl;
          //       }
          //       cout<<"next group:"<<endl;
          // }
          
    }
    
    bool Kmeans::checkEnd(vector<st_mypoint> p1group,vector<st_mypoint> p2group)
    {
          bool ret = YES;
          int i;
          for(i=0;i<KgroupNum;i++)
          {     /* set the check condition to stop KNN */
                if(fabs(p1group[i].x - p2group[i].x)>0.001||
                   fabs(p1group[i].y - p2group[i].y)>0.001
                )
                {
                      ret = NO;
                }
          }
          return ret;
    }
    
    void Kmeans::KNN(st_mypoint input[])
    {
          bool flag=NO;
          int cnt=0;
          int i;
          dataInit(input);
          vector<st_mypoint> preKcenter(KgroupNum);
          for(i=0;i<KgroupNum;i++)
          {
                preKcenter[i].x=0;
                preKcenter[i].y=0;
          }
    
          while((NO == flag)&&(cnt<100))
          {
                cnt++;
                Cluster(input);
                updateCenter(input);
                flag = checkEnd(preKcenter,Kcenter);
                copy(Kcenter.begin(),Kcenter.end(),preKcenter.begin());
          }
          cout<<"cnt="<<cnt<<endl;
          for(i=0;i<KgroupNum;i++)
          {
                cout<<"Kcenter["<<i<<"]="<<Kcenter[i].x<<" "<<Kcenter[i].y<<endl;
          }
    }
    
    void Kmeans::KNNtest(st_mypoint input[])
    {
          int i,j;
          float mindistance,curdistance;
          for(j=0;j<TEST_LEN;j++)
          {
                /* calculate the distance between the first group and point,pretend that's the smallest one*/
                mindistance= calDistance(Kcenter[0],input[j]);
                input[j].tag = 0;  /* pretend all the initial tag is 0 */
                for(i=1;i<KgroupNum;i++)
                {
                      curdistance = calDistance(Kcenter[i],input[j]);
                      if(curdistance<mindistance)
                      {
                            mindistance = curdistance;
                            input[j].tag = i;  /* if found the smaller distance,update tag */
                            cout<<"input["<<i<<"].tag="<<i<<endl;
                      }
                }
          }
          // for debug
          // for(j=0;j<KgroupNum;j++)
          // {
          //       cout<<"The result of TestData["<<j<<"] is "<<input[j].tag<<endl;
          // }      
    }

main.cpp

    /* Author: AppleCai Date 2019/04/28 */
    #include<iostream>
    #include<fstream>
    #include<vector>
    #include"KNN.hpp"
    using namespace std;
    
    
    int main(void)
    {
        Kmeans::st_mypoint TrainData[OBJ_LEN];
        Kmeans::st_mypoint TestData[TEST_LEN];
        int i;
        ifstream fin("in.txt");
        ofstream fout("out.txt");
        for(int i=0;i<OBJ_LEN;i++)
        {
            fin>>TrainData[i].x>>TrainData[i].y;
            cout<<TrainData[i].x<<","<<TrainData[i].y<<endl;
        }
        fin.close();
        Kmeans mytest(4);  //Kgourp set to 4
        mytest.KNN(TrainData);
    
        TestData[0].x = 6;
        TestData[0].y = 6;
        TestData[1].x = 0;
        TestData[1].y = 1;
    
        mytest.KNNtest(TestData);
        for(i=0;i<TEST_LEN;i++)
        {
            fout<<"The result of TestData is:"<<TestData[i].x<<" "<<TestData[i].y<<" "<<TestData[i].tag<<endl;
        } 
        return 0;   
    }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市重斑,隨后出現(xiàn)的幾起案子兵睛,更是在濱河造成了極大的恐慌,老刑警劉巖窥浪,帶你破解...
    沈念sama閱讀 217,826評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件祖很,死亡現(xiàn)場離奇詭異,居然都是意外死亡漾脂,警方通過查閱死者的電腦和手機假颇,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,968評論 3 395
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來骨稿,“玉大人笨鸡,你說我怎么就攤上這事√构冢” “怎么了形耗?”我有些...
    開封第一講書人閱讀 164,234評論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長蓝牲。 經(jīng)常有香客問我趟脂,道長,這世上最難降的妖魔是什么例衍? 我笑而不...
    開封第一講書人閱讀 58,562評論 1 293
  • 正文 為了忘掉前任昔期,我火速辦了婚禮,結(jié)果婚禮上佛玄,老公的妹妹穿的比我還像新娘硼一。我一直安慰自己,他們只是感情好梦抢,可當(dāng)我...
    茶點故事閱讀 67,611評論 6 392
  • 文/花漫 我一把揭開白布般贼。 她就那樣靜靜地躺著,像睡著了一般奥吩。 火紅的嫁衣襯著肌膚如雪哼蛆。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,482評論 1 302
  • 那天霞赫,我揣著相機與錄音腮介,去河邊找鬼。 笑死端衰,一個胖子當(dāng)著我的面吹牛叠洗,可吹牛的內(nèi)容都是我干的甘改。 我是一名探鬼主播,決...
    沈念sama閱讀 40,271評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼灭抑,長吁一口氣:“原來是場噩夢啊……” “哼十艾!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起腾节,我...
    開封第一講書人閱讀 39,166評論 0 276
  • 序言:老撾萬榮一對情侶失蹤忘嫉,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后案腺,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體榄融,經(jīng)...
    沈念sama閱讀 45,608評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,814評論 3 336
  • 正文 我和宋清朗相戀三年救湖,在試婚紗的時候發(fā)現(xiàn)自己被綠了愧杯。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,926評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡鞋既,死狀恐怖力九,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情邑闺,我是刑警寧澤跌前,帶...
    沈念sama閱讀 35,644評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站陡舅,受9級特大地震影響抵乓,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜靶衍,卻給世界環(huán)境...
    茶點故事閱讀 41,249評論 3 329
  • 文/蒙蒙 一灾炭、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧颅眶,春花似錦蜈出、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,866評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至商叹,卻和暖如春燕刻,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背剖笙。 一陣腳步聲響...
    開封第一講書人閱讀 32,991評論 1 269
  • 我被黑心中介騙來泰國打工朗恳, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留疼蛾,地道東北人矾克。 一個月前我還...
    沈念sama閱讀 48,063評論 3 370
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親酪夷。 傳聞我的和親對象是個殘疾皇子榴啸,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,871評論 2 354

推薦閱讀更多精彩內(nèi)容