%线性可分支持向量机
clear;
clc;
%load data
n=50;
x1=randn(2,n);
y1=ones(1,n);
x2=4+randn(2,n);
y2=-ones(1,n);
y3=zeros(1,n);
X=[x1,x2];
Y=[y1,y2];
plot(x1(1,:),x1(2,:),'g*',x2(1,:),x2(2,:),'mp');
hold on;
%二次规划求解
Q=length(Y);
%for i=1:Q
% for j=1:Q
% H(i,j)=dot(X(:,i),X(:,j));
% end
%end
K = X'*X;
T = Y'*Y;
H = K.*T;
f=-ones(Q,1);
A=[];
b=[];
Aeq=Y;
beq=0;
lb=zeros(Q,1);
ub=1*ones(Q,1);
aerfa=quadprog(H,f,A,b,Aeq,beq,lb,ub);
epsilon=1e-6;
J=find(aerfa>epsilon);
plot(X(1,J),X(2,J),'ro');
%求解w,b
w=[0;0];
for i=1:Q
w=w+Y(i)*aerfa(i)*X(:,i);
end
BQ=0;
for i=1:Q
BQ=BQ+Y(i)*aerfa(i)*dot(X(:,i),X(:,J(1)));
end
B=Y(J(1))-BQ;
plotpc(w',B);
grid on;
xlabel('x1');
ylabel('x2');
hold off;
SVM实现(二次规划求解)
最新推荐文章于 2024-08-21 14:52:13 发布