This repository has been archived by the owner on May 17, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
test_single.lua
68 lines (50 loc) · 1.82 KB
/
test_single.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
require 'nn'
require 'image'
local topk=5
local test_image_file=arg[1]
torch.setdefaulttensortype('torch.FloatTensor')
-- load pre-trained model
local prefix=os.getenv("HOME")..'/'
local t = torch.Timer()
local m=torch.load(prefix..'nin_bn_final_arm.t7')
print(string.format("loading model: %.2fsec",t:time().real))
local model=m:unpack()
local classes=model.classes
local mean_std=model.transform
-- add soft max layer, to ouput pseudo-probabilities
model:add(nn.LogSoftMax())
model:evaluate()
local words=torch.load(prefix..'words_1000_ascii.t7','ascii')
-- load test image
test_image_file=test_image_file or prefix.."n07579787_ILSVRC2012_val_00049211.JPEG"
print("Using test image: "..test_image_file)
local input=image.load(test_image_file)
-- model input size
local oW=224
local oH=224
-- find the smaller dimension, and resize it to loadSize (while keeping aspect ratio)
if input:size(3) < input:size(2) then
input = image.scale(input, oW, oH * input:size(2) / input:size(3))
else
input = image.scale(input, oW * input:size(3) / input:size(2), oH)
end
local w1 = math.ceil((input:size(3)-oW)/2)
local h1 = math.ceil((input:size(2)-oH)/2)
local cropped = image.crop(input, w1, h1, w1+oW, h1+oH) -- center patch
-- perform normalization (remove pre-trained mean and std)
for i=1,3 do
cropped[{{i},{},{}}]:add(-mean_std.mean[i])
cropped[{{i},{},{}}]:div(mean_std.std[i])
end
-- add a fake dimension of size 1
cropped=cropped:view(1,3,oH,oW)
t = torch.Timer()
local output=model:forward(cropped)
print(string.format("Running neural net: %.2fsec",t:time().real))
-- extract topK classes:
output=output:view(1000)
local output_x, output_sorted = output:sort(1,true)
probs=torch.exp(output_x)
for i=1,topk do
print(string.format(" %0.1f%%: %s: %s ",probs[i]*100,classes[ output_sorted[i] ], words[ classes[ output_sorted[i] ] ]) )
end