Matlab下一个SVM例子

这是用matlab和cvx编写的很简单的svm程序,data.mat中两个变量,X是51个坐标点,y是51个1或-1,标记对应X中坐标点类别。
这里写图片描述

clear;
load('data.mat');
pos = find(y == 1); 
neg = find(y == -1);
plot(X(pos, 1), X(pos, 2), 'k+');
hold on;
plot(X(neg, 1), X(neg, 2), 'ko');
hold on; 

C = 1;m = size(X,1);
%%kernel
K=X*X';
%%
one = ones(m,1);
alpha = zeros(m,1);
cvx_begin;
    variables alpha(m);
    maximize(one'*alpha - 1/2*(alpha.*y)'*K*(alpha.*y) );
    subject to;
    0 <= alpha <= C;
    alpha'*y == 0;
cvx_end;

ind = find(alpha>=C*0.999999);
ind = ind(1);

%KKT conditions
b = y(ind) - alpha'*(y.*K(:,ind));
w = ((alpha.*y)'*X)';

x1 = linspace(min(X(:,1)), max(X(:,1)), 100);
%w(1)*x1+w(2)*x2+b=0
x2 = - (w(1)*x1 + b)/w(2);
plot(x1, x2, '-r'); 

ind = find(alpha>=C*0.999999 & alpha<=C & y == 1);
ind = ind(1);
b = -alpha'*(y.*K(:,ind));
x2 = - (w(1)*x1 + b)/w(2);
plot(x1, x2, '-b'); 

ind = 
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值