-
Notifications
You must be signed in to change notification settings - Fork 6
/
mKNearestNeighbor.m
90 lines (83 loc) · 2.5 KB
/
mKNearestNeighbor.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
85
86
87
88
89
90
% K-nearest neighbor (10/12/2020)
function KNN = mKNearestNeighbor(feat,label,opts)
% Default
tf = 2;
k = 5;
kfold = 10;
if isfield(opts,'kfold'), kfold = opts.kfold; end
if isfield(opts,'ho'), ho = opts.ho; end
if isfield(opts,'tf'), tf = opts.tf; end
if isfield(opts,'k'), k = opts.k; end
% Hold-out
if tf == 1
fold = cvpartition(label,'HoldOut',ho);
% Call train & test data
xtrain = feat(fold.training,:); ytrain = label(fold.training);
xtest = feat(fold.test,:); ytest2 = label(fold.test);
% Train model
My_Model = fitcknn(xtrain,ytrain,'NumNeighbors',k);
% Test
pred2 = predict(My_Model,xtest);
% Accuracy
Afold = sum(pred2 == ytest2) / length(ytest2);
% Cross-validation
elseif tf == 2
% [Cross-validation]
fold = cvpartition(label,'KFold',kfold);
Afold = zeros(kfold,1);
pred2 = [];
ytest2 = [];
for i = 1:kfold
% Call train & test data
trainIdx = fold.training(i); testIdx = fold.test(i);
xtrain = feat(trainIdx,:); ytrain = label(trainIdx);
xtest = feat(testIdx,:); ytest = label(testIdx);
% Train model
My_Model = fitcknn(xtrain,ytrain,'NumNeighbors',k);
% Test
pred = predict(My_Model,xtest); clear My_Model
% Accuracy
Afold(i) = sum(pred == ytest) / length(ytest);
% Store temporary
pred2 = [pred2(1:end); pred];
ytest2 = [ytest2(1:end); ytest];
end
% Leave-one-out
elseif tf == 3
fold = cvpartition(label,'LeaveOut');
% Size of data
num_data = length(label);
Afold = zeros(num_data,1);
pred2 = [];
ytest2 = [];
for i = 1:num_data
% Call train & test data
trainIdx = fold.training(i); testIdx = fold.test(i);
xtrain = feat(trainIdx,:); ytrain = label(trainIdx);
xtest = feat(testIdx,:); ytest = label(testIdx);
% Train model
My_Model = fitcknn(xtrain,ytrain,'NumNeighbors',k);
% Test
pred = predict(My_Model,xtest); clear My_Model
% Accuracy
Afold(i) = sum(pred == ytest) / length(ytest);
% Store temporary
pred2 = [pred2(1:end); pred];
ytest2 = [ytest2(1:end); ytest];
end
end
% Confusion matrix
confmat = confusionmat(ytest2,pred2);
% Overall accuracy
acc = mean(Afold);
% Store
KNN.acc = acc;
KNN.con = confmat;
if tf == 1
fprintf('\n Accuracy (KNN-HO): %g %%',100 * acc);
elseif tf == 2
fprintf('\n Accuracy (KNN-CV): %g %%',100 * acc);
elseif tf == 3
fprintf('\n Accuracy (KNN-LOO): %g %%',100 * acc);
end
end