-
Notifications
You must be signed in to change notification settings - Fork 37
/
jFitnessFunction.m
57 lines (39 loc) · 1.24 KB
/
jFitnessFunction.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
% Fitness Function KNN (9/12/2020)
function cost = jFitnessFunction(feat,label,X,opts)
% Default of [alpha; beta]
ws = [0.99; 0.01];
if isfield(opts,'ws'), ws = opts.ws; end
% Check if any feature exist
if sum(X == 1) == 0
cost = 1;
else
% Error rate
error = jwrapper_KNN(feat(:,X == 1),label,opts);
% Number of selected features
num_feat = sum(X == 1);
% Total number of features
max_feat = length(X);
% Set alpha & beta
alpha = ws(1);
beta = ws(2);
% Cost function
cost = alpha * error + beta * (num_feat / max_feat);
end
end
%---Call Functions-----------------------------------------------------
function error = jwrapper_KNN(sFeat,label,opts)
if isfield(opts,'k'), k = opts.k; end
if isfield(opts,'Model'), Model = opts.Model; end
% Define training & validation sets
trainIdx = Model.training; testIdx = Model.test;
xtrain = sFeat(trainIdx,:); ytrain = label(trainIdx);
xvalid = sFeat(testIdx,:); yvalid = label(testIdx);
% Training model
My_Model = fitcknn(xtrain,ytrain,'NumNeighbors',k);
% Prediction
pred = predict(My_Model,xvalid);
% Accuracy
Acc = sum(pred == yvalid) / length(yvalid);
% Error rate
error = 1 - Acc;
end