1 clear all; 2 clc; 3 %% 4 %算法 5 %输入:训练数据集T = {(x1,y1),(x2,y2),...,(xn,yn)};学习率η 6 %输出:w,b;感知机模型f(x) = sign(w*x+b) 7 %(1)选取初值w0,b0 8 %(2)在训练集中选取数据(xi,yi) 9 %(3)如果yi(w*xi+b)<=0 10 % w = w+η*yi*xi 11 % b = b+ηyi 12 %(4)转至(2),直至训练集中没有误分类点 13 %% 14 15 %初始化 16 X = [3 3 1;4 3 1;1 1 -1];%训练集 17 [sn,fn] = size(X); 18 y = X(:,fn);%标签 19 X(:,fn) = []; 20 fn = fn-1; 21 w = zeros(2,1); 22 b = 0; 23 yta = 1;%参数η 24 ok = 0; 25 %% 26 %循环体 27 while(ok==0)%%%不断的扫描直到所有的实例都满足无误分类点才结束 28 for i = 1:sn 29 if (y(i)*(w‘*X(i,:)‘+b)<=0) 30 31 w = w + yta*y(i)*X(i,:)‘ 32 b = b + yta*y(i) 33 else 34 if(i == sn) ok=1; 35 break 36 end 37 end 38 end 39 end 40 41 %% 42 %图示 43 figure(1) 44 plot(X(1,:),X(2,:),‘r.‘) 45 hold on 46 plot(X(3,:),‘*‘) %样本 47 xmin=min(X(:,1)); 48 xmax=max(X(:,1)); 49 % ymin=min(X(:,2)); 50 % ymax=max(X(:,2)); 51 xindex=xmin-1:(xmax-xmin)/100:xmax+1; 52 yindex=w(1)*xindex+w(2)*xindex+b; 53 plot(xindex,yindex)%分类面
时间: 2024-11-05 09:35:48