-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathimageTofeature.lua
executable file
·108 lines (76 loc) · 2.32 KB
/
imageTofeature.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
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
104
105
106
107
108
require 'image'
require 'cudnn'
require 'cunn'
require 'xlua'
require 'optim'
require 'nn'
dofile './provider.lua'
local c = require 'trepl.colorize'
local tablex = require 'pl.tablex'
opt = lapp[[
--model (default "logs/vgg/trainedModel.net") model address
]]
print(opt.model)
if #arg < 1 then
io.stderr:write('Usage: th imageTofeature.lua [MODEL]...\n')
os.exit(1)
end
model_path = opt.model
-- loads the training data
provider = torch.load 'provider.t7'
print(c.blue '==>' ..' loading data')
provider = torch.load 'provider.t7'
provider.trainData.data = provider.trainData.data:float()
-- provider.trainData.data is a floatTensor
indices = torch.randperm(provider.trainData.data:size(1)):long():split(1)
model = torch.load(model_path)
model:add(nn.SoftMax():cuda())
model:evaluate()
-- model definition should set numInputDims
-- hacking around it for the moment
view = model:findModules('nn.View')
if #view > 0 then
view[1].numInputDims = 3
end
print(c.blue '==>' ..' calculating feature vectors ')
model1 = torch.load(model_path)
model1:add(nn.SoftMax():cuda())
view = model1:findModules('nn.View')
if #view > 0 then
view[1].numInputDims = 3
end
for j = 1, 2 do
model1:remove()
end
model1:evaluate()
train_featureTable = {}
num = 1
for t,v in ipairs(indices) do
local input = provider.trainData.data:index(1,v)
-- floatTensor of size 1*3*32*32
local hardLabel = provider.trainData.labels:index(1,v)
-- DoubleTensor of size 1
local softLabels = model:forward(input:cuda()):squeeze()
-- CudaTensor of size 10
softLabels = torch.reshape(softLabels, 10, 1)
local max = torch.max(softLabels, 1)
-- local hardLabel = 1
-- Saving hardLabels generated by model
--for i = 1, 10 do
-- if torch.all(torch.eq(softLabels[i], max)) then
-- hardLabel = i
-- end
--end
local featureTensor = model1:forward(input:cuda()):squeeze()
-- cudaTensor of size 512
local tmp = {}
table.insert(tmp, featureTensor:clone())
table.insert(tmp, softLabels:clone())
table.insert(tmp, hardLabel)
-- save this information in an array. Each row is the feature vector + the label for it
table.insert(train_featureTable, tmp)
num = num + 1
end
print(c.blue '==>' ..' saving feature vectors ')
torch.save ('trainFeature_originalLabels.dat', train_featureTable)
print('finish saving')