forked from mtanveer1/SPTWSVM
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Sparse_Pin_SVM.m
84 lines (61 loc) · 1.93 KB
/
Sparse_Pin_SVM.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
%% Authors: Rahul Choudhary & Sanchit Jalan
%--------------Description--------------------
% Function to calculate accuracy, non-zero
% dual variables and training time for
% Sparse Pin SVM for linear case.
%---------------------------------------------
function [accuracy, non_zero_dual_variables, training_time, lambda] = Sparse_Pin_SVM(X1_Train, X2_Train, Y_Train, X_Test, Y_Test, c, epsilon, tau)
%Here c1 = c2 = c
% epsilon1 = epsilon2 = epsilon
% tau1 = tau2 = tau
training_time = 0;
non_zero_dual_variables = 0;
m1 = size(X1_Train, 1); %Number of samples in 1st class
m2 = size(X2_Train, 1); %Number of samples in 2nd class
m = m1 + m2;
n = size(X1_Train, 2);
X_Train = [X1_Train; X2_Train];
%-------Sparse Pinball loss SVM classifier--------
H = diag(Y_Train)*X_Train*X_Train'*diag(Y_Train);
Q = [H zeros(m, m); zeros(m, m) zeros(m, m)];
f = [-ones(m, 1); -ones(m, 1)*epsilon];
Aeq = [Y_Train' zeros(1, m)];
Beq = 0;
A = [eye(m) eye(m)];
B = [ones(m, 1)*c];
lb = [ones(m, 1)*(-tau*c); zeros(m, 1)]; %Here gamma belongs to [0, c] and lambda belongs to [-tau*c, c]
ub = [ones(m, 1)*c; ones(m, 1)*c];
tic;
[U, fval] = quadprog(Q, f, A, B, Aeq, Beq, lb, ub);
toc;
training_time = training_time + toc;
lambda = U(1:m, :);
b = 0;
count = 0;
for i = 1:size(lambda, 1)
if -tau*c < lambda(i) && lambda(i) < c
b = b + Y_Train(i) - (lambda.*Y_Train)'*(X_Train*X_Train(i, :)');
count = count + 1;
end
end
b = b/count;
%--------Evaluating accuracy of obtained SVM model---------
accuracy = 0;
for i = 1: size(X_Test, 1)
if (lambda.*Y_Train)'*(X_Train*X_Test(i, :)') + b > 0
if Y_Test(i) == 1
accuracy = accuracy + 1;
end
else
if Y_Test(i) == -1
accuracy = accuracy + 1;
end
end
end
accuracy = accuracy/(size(X_Test, 1));
for i = 1: size(lambda, 1)
if abs(lambda(i)) > 0.0000001
non_zero_dual_variables = non_zero_dual_variables + 1;
end
end
end