/
solve_ksvm.m
60 lines (45 loc) · 1.34 KB
/
solve_ksvm.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
function [ alph, k ] = solve_ksvm( X, Y, Kmat, L, B, d, Sig, mu )
%SOLVE_KSVM Compute the kernel SVM solution
%% Set default inputs and initialize variables
[n, p] = size(X);
%% Solve the SVM optimization problem
cvx_begin quiet
variable alph(n)
minimize( (alph.*Y)'*Kmat*(alph.*Y)/n - sum(alph)/n )
sum(alph.*Y) == 0
0 <= alph <= L
if (nargin >= 6)
-d <= B*alph <= d
end
cvx_end
if (nargin == 8)
Sig = Sig/max(max(abs(Sig)));
[V, D] = eig(Sig);
pD = D; pD(D <= 0) = 0;
nD = D; nD(D >= 0) = 0;
pSig = V*pD*V';
nSig = V*nD*V';
bp = alph.*Y;
maxiters = 500;
while (maxiters > 0)
cvx_begin quiet
variable alph(n)
variable t
minimize( (alph.*Y)'*Kmat*(alph.*Y)/n - sum(alph)/n + mu*t )
sum(alph.*Y) == 0
0 <= alph <= L
-d <= B*alph <= d
(alph.*Y)'*pSig*(alph.*Y) + bp'*nSig*bp + 2*bp'*nSig'*(alph.*Y - bp) <= t
-(alph.*Y)'*nSig*(alph.*Y) - bp'*pSig*bp - 2*bp'*pSig'*(alph.*Y - bp) <= t
cvx_end
if (norm(alph.*Y - bp)/norm(bp) < 1e-3)
break;
else
bp = alph.*Y;
maxiters = maxiters - 1;
end
end
end
%% Identify an unconstrained coefficient
k = find(0 < alph & alph < L);
end