机器学习——感知器算法实现
本次也是用processing3.0+写的,其官方网站https://processing.org/,建议直接看reference的例子进行学习。
感知器算法用的是我们老师给的ppt,实现的是二维的感知器,为了方便看,实际上多维的也是一样的:
运行效果是:
为了试验方便,我这是用了点击取点,键盘按一下t,大小写均可,下一个点的就是正例,按一下f,大小写均可,下一个点就是负例。
按s是开始进行学习度为1的迭代。结束会直接出直线,按2会出学习率为2的直线,迭代次数会打在程序底下,值是2.
代码仅供参考,请勿抄袭。转载请注明出处。
//blog:http://www.cnblogs.com/SweetBeens/p/8176764.html class Point{ float x, y; int k; Point(float x1,float y1){ x = x1; y = y1; } } int num = 500; int len = 0; float h=1; float r=0; Point [] points = new Point[num]; int irit = 1000; float w1 = 0, w2 = 0, b = 0; //false=-1,true=1 boolean type = true; //if one point wrong,then ,you need another irretate boolean flag = true; //one irretate void rewrite(){ for(int i = 0; i < len; i++){ //if points[i] wrong side float result=points[i].k*(points[i].x*w1+points[i].y*w2+b); if(result<=0){ w1 = w1+h*points[i].k*points[i].x; w2 = w2+h*points[i].k*points[i].y; b = b + h * points[i].k*r*r ; print(b," "); //w1=w1/w2; // w2=1; //b=b/w2; flag=true; } } } //calculate R,check out in ppt void R(){ float max=0; for(int i=0;i<len;i++){ if(abs(points[i].x)>max) max=abs(points[i].x); if(abs(points[i].y)>max) max=abs(points[i].y); } r=max; println("max ",max); } void mousePressed(){ Point p = new Point(mouseX,mouseY); if(type){ p.k = 1; fill(255); } else{ p.k = -1; fill(0); } rect(mouseX,mouseY,5,5); points[len] = p; len++; } void keyPressed(){ int i=0; float y1=0,y2=0; if(key == 'T' || key == 't') type = true; else if(key == 'F' || key == 'f') type = false; else if(key == 's' || key == 'S') { R(); while(i<irit&&flag==true){ i++; flag=false; rewrite(); // println("w",w1," ",w2,"b",b); y1 = -b/w2; y2 = (-b-w1*width) / w2; //line(0,10,width,480); } println(y1," ",y2); println("w1,w2,b "+w1,w2,b); line(0,y1,width,y2); } else if(key == '2'){ h = 0.2; w1 = 0; w2 = 0; b = 0; flag=true; i=0; while(i<irit&&flag==true){ i++; flag=false; rewrite(); // println("w",w1," ",w2,"b",b); y1 = -b/w2; y2 = (-b-w1*width) / w2; //line(0,10,width,480); } println(y1," ",y2); println("w1,w2,b "+w1,w2,b); line(0,y1,width,y2); } println("i ",i); } void setup(){ size(500,500); background(255); } void draw(){ }
本博客专注于错误锦集,在作死的边缘试探