k均值算法用processing实现

时间:2022-03-06 22:06:27
代码仅供参考,请勿抄袭。转载请注明出处。
class
Point{ float x , y; int k; Point(float x1,float y1){ x=x1;y=y1; } } class Type{ int k; int num=0; float x_old , y_old; float x_new , y_new; int r = 0 , g = 0 , b = 0; } int num = 500; float dx = 1, dy = 1;// int k = 3; int k_max = 5; int len = 0; int iritation = 10000; boolean flag=true; Point [] Points = new Point [num]; Type [] Types = new Type [k_max]; void nearK(){ for(int i = 0 ; i < len ; i++){ float min = width * height; int index = -1; for(int j = 0 ; j < k ; j++){ float r = dist(Points[i].x,Points[i].y,Types[j].x_old,Types[j].y_old); if(r < min){ min = r; index = j; } } if(index == -1) print("what??"); else{ Points[i].k=index; Types[index].num++; } } } void renew(){ for(int i = 0 ; i < len ; i++){ int u=Points[i].k; println("now"+u); Types[u].x_new += Points[i].x; Types[u].y_new += Points[i].y; } for(int i = 0 ; i < k ; i++){ println(i+"num"+Types[i].num); Types[i].x_new=Types[i].x_new/Types[i].num; Types[i].y_new=Types[i].y_new/Types[i].num; println("xnew"+Types[i].x_new,"ynew"+Types[i].y_new); Types[i].num=1; if(abs(Types[i].x_new-Types[i].x_old)>dx){ flag = true; Types[i].x_old=Types[i].x_new; } if(abs(Types[i].y_new-Types[i].y_old)>dy){ flag = true; Types[i].y_old=Types[i].y_new; } } } void origin(){ for(int i = 0 ; i < k; i++){ int u = int(random(0,len-1)); int v = int(random(0,255)); Type T = new Type(); T.x_old = Points[u].x; T.y_old = Points[u].y; T.r =v; v = int(random(0,255)); T.g =v; v = int(random(0,255)); T.b =v; Types[i] = T; } // print(Types.length); } void mousePressed(){ Point p = new Point(mouseX, mouseY); Points[len]=p; // print(Points[len].x); rect(mouseX,mouseY,5,5); len++; } void setup(){ size(500,500); background(255,255,255); } void draw(){ if(keyPressed){ if(key == 'S' || key == 's'){ int ire=0; background(255,255,255); origin(); nearK(); renew(); for(int i = 0; i <iritation; i++){ ire++; if(flag){ flag=false; nearK(); renew(); } else break; } for(int i = 0; i < len; i++){ int u=Points[i].k; fill(Types[u].r,Types[u].g,Types[u].b); rect(Points[i].x,Points[i].y,7,7); textSize(20); text(u,Points[i].x+9,Points[i].y+10); } print("ire"+ire); } } } void keyPressed(){ int p=0; if((key == 'l' || key == 'L')&&flag == true && p<iritation){ // boolean flag=false; int ire=0; background(255,255,255); p++; flag=false; origin(); nearK(); renew(); for(int j=0; j<k;j++){ fill(255); rect(Types[j].x_old,Types[j].y_old,10,10); } for(int i = 0; i < len; i++){ int u=Points[i].k; fill(Types[u].r,Types[u].g,Types[u].b); rect(Points[i].x,Points[i].y,7,7); textSize(20); text(u,Points[i].x+9,Points[i].y+10); } for(int i=0; i<k;i++){ fill(255); rect(Types[i].x_old,Types[i].y_old,10,10); } print("ire"+ire); } }

本代码用的语言是processing:官网链接https://processing.org/reference/

由于是beta版本,所以很有潜力。

实现的是k-mean算法。初始的质心是随机生成的。个数是定好的,节点想多少自己点。

k均值算法用processing实现

运转算法:

k均值算法用processing实现