forked from Moodstocks/gtsrb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_kNN.lua
78 lines (68 loc) · 2.43 KB
/
test_kNN.lua
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
----------------------------------------------------------------------
-- This is another testing function, which uses a 1NN classifier
-- on features extracted from an already trained model.
--
-- Input:
-- + mdl_output_layer_idx : index of the output module you want to consider as input features
--
-- Hugo Duthil
----------------------------------------------------------------------
local script_dir = paths.dirname(paths.thisfile()).."/"
function test_kNN(mdl_output_layer_idx)
-- Classes
local classes = {}
for i = 1, 43 do classes[i] = (i-1).."" end
-- this matrix records the current confusion across classes
local confusion = optim.ConfusionMatrix(classes)
confusion:zero()
local pwd = nn.PairwiseDistance(2)
-- compute average example for each class
local res = {}
local exp_count = {}
for i=1, 43 do exp_count[i] = 0 end
print("Building reference table")
for i=1, train_set:size() do
xlua.progress(i, train_set:size())
local sample = train_set[i]
if use_3_channels then
model:forward(sample[1])
else
model:forward(sample[1][{ {1}, {}, {} }])
end
local output = model:get(mdl_output_layer_idx).output
local clas = sample[2]
if res[clas] then
res[clas]:add(torch.Tensor(output:clone()))
else
res[clas] = torch.Tensor(output:clone())
end
exp_count[clas] = exp_count[clas] + 1
end
for i=1, 43 do res[i]:div(exp_count[i]) end
print("Matching testing ...")
for t=1, test_set:size() do
xlua.progress(t, test_set:size())
local test_sample = test_set[t]
if use_3_channels then
model:forward(test_sample[1])
else
model:forward(test_sample[1][{ {1}, {}, {} }])
end
local output = model:get(mdl_output_layer_idx).output
local min_dist = 9999999
local best_class = 1
for i=1, #res do
local r_reshaped = torch.reshape(res[i], #res[i]:storage())
local o_reshaped = torch.reshape(output, #output:storage())
local dist = pwd:forward({o_reshaped,r_reshaped})[1]
if dist < min_dist then
min_dist = dist
best_class = i
end
confusion:add(best_class, test_sample[2])
end
end
print(confusion)
torch.save("saves/confusion.t7", confusion)
confusion:zero()
end