Kmeans Clustering algorithm for strong calculation demonstrator

Source: Internet
Author: User
Tags pow

These days to do C # experiments and this Kmeans algorithm demonstrator, learn OpenGL, feel need to strengthen.

Point.h/*point structure Definition and realization structure weight contains 2 operators: 1.==//infers that the coordinate values of two point are equal 2.<<//is used for display (overloaded with a friend function) */#ifndef point_h_# Define Point_h_#include <iostream> #include <string> #include <iomanip>using namespace Std;const int      mwidth=3;      Displays the structure of each character width//hold point coordinate struct point{string name;//dot name double x;      X-axis coordinate double y;      Y-Axis coordinates//default struct-constructor point (): X ( -999), Y ( -999) {}-point (double xx,double yy,string N): X (xx), Y (yy), name (n) { }//Copy constructor point (const point &p): X (p.x), Y (p.y), name (p.name) {}//Assign copy function point operator= (const point &          P) {if (this==&p) return *this;          x=p.x;          Y=P.Y;          Name=p.name;      return *this;       }//infer that two point coordinate values are equal bool operator== (const point &point) const{return x==point.x&&y==point.y; }//Reload << friend ostream& operator<< (ostream &os,const point &p) {os<&lt ; SETW (Mwidth) <<right<<p.name<< "(" &LT;&LT;SETW (mwidth) <<left<<p.x<< "," &LT;&LT;SETW (mwidth) <<  p.y<< ")" << "";    return OS;   }  };  #endif

Functions.h is mainly a number of functions

Functions.h#ifndef functions_h_#define functions_h_#include <iostream> #include <cstdlib> #include < ctime> #include <vector> #include <iomanip> #include <string> #include <sstream> #include &l t;vector> #include <iterator> #include <algorithm> #include "Point.h" #include <ctime> #include  <windows.h>using namespace Std;        const int MAX=20;     Number of cluster points const int m_group=3; Number of clusters const int limit=20;    Consent to the maximum number of clusters of const int x_limit=15;    X-axis maximum coordinate const int y_limit=15; Y----//numeric to string numbertostring (int i) {stringstream s;s<<i;return s.str ();};/ /delay (n) delay n sec void Delay (double sec) {time_t start_time, cur_time;//variable declaration time (&start_time);d o {time (&cur_time) ;} while ((Cur_time-start_time) < sec);};/      /Generate random points//size the number of random points generated by bool Randpoint (vector<point> &vp,int size) {vp.clear (); Srand (Time (0)); int i=0;          Generates a random point while (i<size) {int x=rand ()%x_limit; int Y=rand ()%y_limit;string name= "P"; string num=numbertostring (i+1); name+=num;//is added to the array vp.push_back (Point (X,y,name));      i++; } if (i==size) return True;elsereturn false;};/ /output single coordinate static int counttimes=0;//for output format control void Outpoint (Point &p) {cout<<p;counttimes++;if (counttimes%5==0 ) cout<<endl;};/ /output array all points//show all points of the function void display (vector<point> &vp) {Counttimes=0;for_each (Vp.begin (), Vp.end (), outpoint) ;};/  /empty stream contents void Eatline () {while (Cin.get ()! = ' \ n ') continue;  }; Select the Starting center point enter an array of//center storage Center points//VP All points bool Inputcenter (vector<point>¢er,vector<point> &AMP;VP) {// The maximum number of clusters is int vpsize=vp.size ();//emptying Center content center.clear ();cout<< "\ n Please enter the number of clusters: 0--" <<vpsize<<endl ; int Group;cin>>group;while (group<=0| | group>vpsize) {cout<< "wrong input! "<<endl;cout<<" \ n Please enter the number of clusters: 0--"<<vpsize<<endl;cin>>group;}    Select the starting center point int j=0;   while (j<group) {int locate; cout<< "Please select" <<group<< "coordinates point as the starting point,Enter 1 for P1: "<<endl; Cin>>locate;if (locate>0&&locate<=vpsize) {point temp=vp[locate-1]; cout<< "Successfully selected" < <j+1<< "A starting point!"  <<temp;     Center.push_back (temp);  if (j!=group-1) cout<< "Please continue over the remaining options:" <<endl; else{cout<< "\ n Select finished! The selected center point is: "<<endl;display (center); return true;}  j + +; }else{cout<< "Wrong choice!  "<<" Please enter the correct value again: "<<1<<"--"<<vpSize<<": "<<endl; } eatline ();//Empty Stream} return false;}; #endif

Kmeans.h#ifndef kmeans_h_#define kmeans_h_/* @author: Unparalleled @date: 2014-6-5 @version: 9.0 Clustering algorithm K-means implementation: Using a strong algorithm to randomly generate 20 points , and then divided into three clusters of change: coordinate point to double type//completed clustering algorithm//deprecated pointer, all use vector<point> Replace//interface version opengl*/#include "Functions.h" # Include "OpenglFunc.h" #include "Point.h" #include <vector> #include <cmath>//for one-dimensional array, array size, cluster size, selected initial point// The return value is the number of clusters performed//inferred two times whether the center is equal to bool IsEqual (vector<point> &lhs,vector<Point> &rhs) {int size=rhs.size (); for (int i=0;i<size;i++) {if (Lhs[i]==rhs[i]) Continue;elsereturn false;} Return true;};/ /center point//when size is 0 o'clock, returns a ( -999,-999) representing no element point Calcenter (vector<point> &arr) {int size=arr.size (); if (size!= 0) {double xsum=0;double ysum=0;for (int i=0;i<size;i++) {xsum+=arr[i].x;//note priority ysum+=arr[i].y;}  Double x=xsum/size;double Y=ysum/size;return Point (x, Y, "center"); }else return Point ( -999,-999, "center Point repeated, the center has no dots");};/ /calculates the distance between two points double pointtopoint (const point &lhs,const point &rhs) {double xtox=abs (lhs.x-rhs.x);d ouble ytoy= ABS (LHS.Y-RHS.Y);d ouble sum=pow (xtox,2) +pow (ytoy,2);d ouble f=sqrt (sum); return f;};/ /KMEANS//VP Points Group//center Start Center Points Group Int Kmeans (vector<point> &vp,vector<point>¢er) {vector<point>    first;//records the last central vector<point> second of the cluster; Record this time the center of the cluster vector<vector<point>> group;//storage Cluster/* Center and group relationship subscript corresponding 01234center01234group000102030410111213142021222324..........*/int centersize=center.size (); int vpsize=vp.size ();//Copy start point to first cluster Center for (int i=0;i<centersize;i++) First.push_back (Center[i]);cout<< "\ n the starting center point for the selection is: "<<endl;display (first);cout<<" is the center point marked red: "<<endl;//indicates the center point of the primary selection Paintcenterpoint ( first);//number clustering the number of times int number=0;//color is used to display the point when it chooses its own color int color=0;//The center point of the selection should not be erased bool flag=true;do{// The first group has the corresponding array group.clear (); for (int i=0;i<centersize;i++) {vector<point> p;group.push_back (p);} Assign each point to the array go for (int i=0;i<vpsize;i++) {//locate The coordinates of the nearest center point are in center subscript int locate=0;double min=999;for (int j=0;j <centersize;j++) {DoUble F=pointtopoint (vp[i],first[j]);//mark the shortest distance of the center point if (f<min) {min=f;locate=j;}} Assign a point to the corresponding Vector<point>group[locate].push_back (Vp[i]);//Output point assignment information//cout<<vp[i]<< "will be assigned to cluster" < <locate+1<< ";"  <<endl;  }//Show cluster cout<< "cluster case after clustering:" <<endl; for (int i=0;i<centersize;i++) {cout<< "\ n cluster" <<numbertostring (i+1) << ":" <<endl;display (  Group[i]);cout<<endl;  } for (int i=0;i<centersize;i++) {if (color==5) color=0;//resets Colorsetcolor (color++);p aintvectorpoint (Group[i]); }//again compute the cluster center and store it in second//Empty secondsecond.clear (); for (int i=0;i<centersize;i++) {Second.push_back (Calcenter (  Group[i])); }for (int i=0;i<centersize;i++) {if (second[i].x!=-999&&second[i].y!=-999) second[i].name= "C" + Numbertostring (i+1);} cout<< "\ n the new cluster Center is:" <<endl;display (second);//Erase Old center point if (!flag) removecenterpoint (first); else{flag=false;} Mark each new center Paintcenterpoint (second), if (IsEqual (first,second)) {cout<< "\ n cluster complete!" <<endl;cout<< "Copolymer" <<number<< "Times" <<endl;break;} else if (number>limit) {cout<< "Number of clusters exceeded limit!" <<endl;cout<< "program will exit" <<endl;break;} else{cout<< "\ nthe condition is not met. Continue to cluster! " <<endl<<endl<<endl;//Reset First Center first.clear (); for (int i=0;i<centersize;i++) {First.push_back ( Second[i]);} }number++;}    while (true);  return 0; }; #endif
Openglfunc.h#ifndef opengl_kmeans_h_#define opengl_kmeans_h_#include <GL/glut.h> #include <vector># Include <iterator> #include <windows.h> #include <string> #include "Point.h" #include "functions.h"// Delay Time # define Delaytime 0.2//point size # pointsize 8//Display scale # define BILI 10//Edge # define Bian 1//x,y Edge # define Xlimit 1.5#define Y LIMIT 1.5void DrawString (const char *STR);//Draw a single point on the screen void Paintpoint (points &p) {float x=p.x*1.0/bili;float y=p.y*    1.0/bili;glpointsize (pointsize); Glbegin (gl_points); glvertex2f (x, y); Glend (); const char *NAME=P.NAME.C_STR ();    GLRASTERPOS2F (x+0.02f,y+0.0f); DrawString (name); Glflush ();};/ /Draw an array of points void Paintvectorpoint (vector<point> &vp) {int size=vp.size (); for (int i=0;i<size;i++) { Paintpoint (Vp[i]);d Elay (delaytime);}};/ /Draw center point, use red color//non-delay void Paintcenterpoint (vector<point> &vp) {int size=vp.size (); glcolor3f (1.0,0.0,0.0); for (int i=0;i<size;i++) {Paintpoint (vp[i]);}};/ /plot coordinates as grid void Paintgrid () {glcolor3f (0.0,0.0,0.0);//Vertical grid foR (int i=1;i<10*xlimit;i++) {float xx=i*1.0/10;glbegin (gl_lines); glvertex2f (xx,0.0); glvertex2f (Xx,YLIMIT); glEnd ();} Horizontal grid for (int i=1;i<10*ylimit;i++) {float yy=i*1.0/10;glbegin (gl_lines); glvertex2f (0.0,YY); glvertex2f (XLIMIT, YY); Glend ();}};/ /display Axis//ASCII characters are only 0 to 127 total.    Altogether 128 characters # define MAX_CHAR 128void drawstring (const char* str) {static int isfirstcall = 1;    static Gluint lists;         if (Isfirstcall) {//is assumed to be the first call, run Initialize//Generate a display list for each ASCII character Isfirstcall = 0;         Application Max_char A sequential display list number lists = Glgenlists (Max_char);     Each character's drawing command is loaded into the corresponding display list wglusefontbitmaps (WGLGETCURRENTDC (), 0, Max_char, lists); }//call each character corresponding display list, draw each character for (; *str!= '; ++str) glcalllist (lists + *str);};/ /Erase old center point//Make it white void Removecenterpoint (vector<point> &vp) {int size=vp.size (); glcolor3f (1.0,1.0,1.0); for (int i=0;i<size;i++) {Paintpoint (vp[i]);} Redraw grid Paintgrid ();};/ /Draw background color for white void Paintnull () {glcolor3f (1.0,1.0,1.0); Glbegin (Gl_polygon); glvertex2f (-bian,-bian); glvertex2f (-bian,bian); glvertex2f (Bian,bian); glVertex2f (BIAN,- Bian); Glend ();};/ /Draw xy axis void Paintxy () {glcolor3f (0.0,0.0,0.0);//Draw X-axis glbegin (gl_lines); glvertex2f ( -0.2,0); glvertex2f (xlimit,0); Glend ();//yglbegin (gl_lines); glvertex2f (0.0,ylimit); glvertex2f (0.0,-0.2); Glend ();//axis Digital glcolor3f (1.0f, 0.0f,    0.0f);    GLRASTERPOS2F ( -0.05f,-0.05f);    DrawString ("0"); glrasterpos2f (0.49f,-0.05f);    DrawString ("5"); glrasterpos2f (0.99f,-0.05f);    DrawString ("ten"); glrasterpos2f ( -0.05f,0.5f);    DrawString ("5"); glrasterpos2f ( -0.05f,0.99f);    DrawString ("ten"); glrasterpos2f (1.45f,-0.05f);    DrawString ("Y"); glrasterpos2f ( -0.05f,1.45f);    DrawString ("X"); Glutswapbuffers ();};/  /Set the color of each cluster//i the maximum value is 6void setcolor (int i) {switch (i) {Case 2:glcolor3f (1.0, 1.0, 0.0);  --Yellow case 1:glcolor3f (0.0, 0.0, 1.0);  --Blue Case 0:glcolor3f (0.0, 1.0, 0.0);  --Green//case 3:glcolor3f (1.0, 0.0, 0.0); --Red Case 4:glcolor3f (0.0,1.0, 1.0); break;  --Cyan Case 5:glcolor3f (1.0, 0.0, 1.0);  -Magenta Case 3:glcolor3f (0.0, 0.0, 0.0); --Black Default:break;}} #endif
Tfunc.h#ifndef tfunc_h_#define tfunc_h_#include <iostream> #include "functions.h" #include <vector># Include "OpenglFunc.h" #include "kmeans.h" #include "functions.h" #include <string>using namespace Std;void Yourchoice () {cout<< "Please enter the number of random points generated: (Recommended less than 20 points to see more clearly)" <<endl;int Num;cin>>num;eatline ();vector< Point> vp;vector<point> center;randpoint (vp,num);cout<< "randomly generated coordinate points such as the following:" <<endl;display (VP); cout<< "Please wait for the picture to choose the center point:" <<endl;paintvectorpoint (VP); Inputcenter (CENTER,VP); Kmeans (vp,center);};/ /demo Book sample void Example () {Point p[10]={point (3,4, "P1"), point (3,6, "P2"), point (7,3, "P3"), point (4,7, "P4"), point (3,8, "P5 "), point (8,5," P6 "), point (4,5," P7 "), point (4,1," P8 "), point (7,4," P9 "), point (5,5," P10 "),};vector<point> VP; vector<point> center;for (int i=0;i<10;i++) Vp.push_back (P[i]); Center.push_back (P[6]); Center.push_back (p[ 9]);p Aintvectorpoint (VP); Kmeans (vp,center);}; #endif

Main.cpp#include "openglFunc.h" #include "functions.h" #include "tFunc.h" #include "displayFunc.h" int main (int argc, Char **argv) {glutinit (&ARGC,ARGV); Init (); Glutmainloop ();}


Dos Interface +opengl Drawing
The demo sample is as follows:


Kmeans Clustering algorithm for strong calculation demonstrator

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.