-
Notifications
You must be signed in to change notification settings - Fork 4
/
svm.m
42 lines (32 loc) · 897 Bytes
/
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
function [fitness,acc,nfeat]=svm(X,Y,pop)
FeatIndex = find(pop==1);
ntotal_feat=size(X,2);
nfeat=numel(FeatIndex);
X = X(:,[FeatIndex]);
if size(Y,1)<1000
k=2;
else
k=5;
end
c = cvpartition(Y,'KFold',k);
acc=[];
pstart=1;
pend=0;
for i =1:k
pend=pend+c.TestSize(i);
testset=X([pstart:pend],:);
trainset=X;
trainset([pstart:pend],:)=[];
testlabel=Y(pstart:pend);
trainlabel=Y;
trainlabel(pstart:pend)=[];
model=svmtrain(trainset,trainlabel,'kernel_function','linear','kktviolationlevel',0.1);
prdct_label= svmclassify(model,testset);
acc =[acc, sum(testlabel == prdct_label) / numel(testlabel)];
pstart=pstart+c.TestSize(i);
end
acc=mean(acc);
%to optimize both nfeat and acc use activate this
% fitness=(0.2*(nfeat/ntotal_feat))-0.8*acc;
%to optimize accuracy only activate this
fitness=-acc;