-
Notifications
You must be signed in to change notification settings - Fork 5
/
kmeansclf.m
103 lines (83 loc) · 2.08 KB
/
kmeansclf.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
91
92
93
94
95
96
97
98
99
100
101
102
103
% Author: Baihan Lin ([email protected])
% Date: Jan 2020
function result = kmeansclf(data,opts)
if opts.oracle == 1
nArms = opts.nOptions;
labls = [];
labln = [];
else
nArms = 1; % 1 for the new arm
labls = ['new'];
labln = [1];
end
y = data.y;
y_true = data.full_y;
x = data.rec;
rew = 0;
r = [];
a = [];
% kms = zeros(nArms,data.dim);
kms = x(:,1:nArms)';
kmn = zeros(nArms,1);
idx = 1:nArms;
hbk = cell(nArms,1);
for i = 1:nArms
hbk{i} = [];
end
for t = 1:data.t
disp(strcat('kmeans - ',num2str(t)))
feat = x(:,t)';
labl = y(t);
labl_true = y_true(t);
stillWrong = 0;
stillCorrect = 0;
pred = mode(idx(knnsearch(kms,feat)));
if opts.oracle == 1
if ~any(labln == pred)
if labl ~= "-1" && (isempty(labls) || ~any(labls == labl))
labls = [labls;labl];
labln = [labln;length(labls)];
pred = length(labls);
else
stillWrong = 1;
end
else
if labl ~= "-1" && (isempty(labls) || ~any(labls == labl))
labls = [labls;labl];
labln = [labln;length(labls)];
end
end
else
if ~any(labls == labl) && labl ~= "-1"
nArms = nArms + 1;
labls = [labls;labl];
labln = [labln;nArms];
kms = [kms;feat];
kmn = [kmn; 0];
idx = 1:nArms;
hbk{nArms} = [];
if pred == 1
stillCorrect = 1;
end
end
end
if ~stillWrong && (stillCorrect || labls(labln == pred) == labl_true)
rew = rew + 1;
end
r = [r;rew];
acc = rew / t;
a = [a;acc];
if labl ~= "-1"
assignment = labln(labls == labl);
kmn(assignment) = kmn(assignment) + 1;
hbk{assignment} = [hbk{assignment};feat];
idx = 1:nArms;
kms(assignment,:) = mean(hbk{assignment},1);
end
end
acc = rew / data.t;
result.acc = acc;
result.rew = rew;
result.a = a;
result.r = r;
end