用CVX实现SVM

% get SVM data
load fisheriris
classKeep = ~strcmp(species,'virginica');

X = meas(classKeep,3:4);
y = species(classKeep);
gscatter(X(:,1),X(:,2),y,'mc','.x',[15,10]);

classKeep = strcmp(y , 'setosa');
y = double(classKeep);
ind = find(y == 0);
y(ind) = -1;
% train SVM 
n = size(X,2);
cvx_begin
    variable w(n);
    variable b;
    minimize( 1/2*norm(w) );
    subject to
        y.*( X * w + b) -1 >= 0;
cvx_end
% find support vector
out = y.*( X * w + b);
out=round(out*100)/100;
ind = find( out == 1);

% draw support vector
figure,gscatter(X(:,1),X(:,2),y,'mc','.x',[15,10]);
hold on
plot([0 -b/(w(1))],[-b/(w(2)) 0],'b')
hold on
for i = 1:length(ind)
    gscatter(X(ind(i),1),X(ind(i),2),'xo');
end


用CVX实现SVM_第1张图片

你可能感兴趣的:(cvx)