-
Notifications
You must be signed in to change notification settings - Fork 0
/
train_main_whole.lua
256 lines (215 loc) · 8.47 KB
/
train_main_whole.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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
-- det training with train + validate dataset
require 'cunn'
require 'cudnn'
require 'cutorch'
local Runner = require 'runner_dual'
torch.setdefaulttensortype('torch.FloatTensor')
local save_parameters = {'weight', 'bias', 'running_mean', 'running_var', 'running_std' }
local function copyModel(src, dst)
assert(torch.type(src) == torch.type(dst), 'torch.type(src) ~= torch.type(dst)')
for i,k in ipairs(save_parameters) do
local v = src[k]
if v ~= nil then
dst[k]:copy(v)
end
end
if src.modules ~= nil then
assert(#dst.modules == #src.modules, '#dst.modules ~= #src.modules')
local nModule = #src.modules
if nModule > 0 then
for i=1,nModule do
copyModel(src.modules[i], dst.modules[i])
end
end
end
end
local dataDir = '/home/xiaofei/public_datasets/MICCAI_tool/Tracking_Robotic_Training/tool_label'
if not paths.dirp(dataDir) then
error("Can't find directory : " .. dataDir)
end
local saveDir = '/home/xiaofei/workspace/toolPose/models'
if not paths.dirp(saveDir) then
os.execute('mkdir -p ' .. saveDir)
end
local function getDetID(modelConf)
local s = modelConf.type
if modelConf.iterCnt ~= nil then
s = s .. '_i' .. modelConf.iterCnt
end
s = s .. '_v' .. modelConf.v
if modelConf.jointRadius ~= nil then
s = s .. '_r' .. modelConf.jointRadius
end
return s
end
local function getSaveID(modelConf)
local s = modelConf.type
if modelConf.iterCnt ~= nil then
s = s .. '_i' .. modelConf.iterCnt
end
s = s .. '_v' .. modelConf.v
if modelConf.jointRadius ~= nil then
s = s .. '_r' .. modelConf.jointRadius
end
s = s .. '_whole'
return s
end
local opt = {
dataDir = dataDir,
saveDir = saveDir,
trainStyle = 'whole',
retrain = 'last', -- nil, 'last' or 'best'
learningRate = 1e-4, -- old 1e-5
momentum = 0.95,
weightDecay = 0.0005, -- old 0.0005
decayRatio = 0.95,
updateIternal = 10,
-- modelConf = {type='toolDualPoseSep', v=1, jointRadius=20, modelOutputScale=4, inputWidth=480, inputHeight=384},
-- modelConf = {type='toolPartDet', v=1, jointRadius=10, modelOutputScale=4, inputWidth=480, inputHeight=384},
-- modelConf = {type='toolPartDetFull', v=1, jointRadius=10, modelOutputScale=1, inputWidth=320, inputHeight=256},
-- modelConf = {type='toolPartDetFull', v='192*240', jointRadius=5, modelOutputScale=1, inputWidth=240, inputHeight=192},
-- modelConf = {type='toolPartDetFull', v='256*320_ftblr', jointRadius=10, modelOutputScale=1, inputWidth=320, inputHeight=256, vflip=1, hflip=1},
-- modelConf = {type='toolPartDetFull', v='256*320_ftblr_head', jointRadius=10, modelOutputScale=1, inputWidth=320, inputHeight=256, vflip=1, hflip=1},
modelConf = {type='toolPartDetFull', v='256*320_ftblr_head', jointRadius=15, modelOutputScale=1, inputWidth=320, inputHeight=256, vflip=1, hflip=1},
-- modelConf = {type='toolPartDetFull', v='256*320_head', jointRadius=15, modelOutputScale=1, inputWidth=320, inputHeight=256, vflip=0, hflip=0},
gpus = {1},
nThreads = 6,
-- batchSize = 1, -- examples seems to be the maximum setting for one GPU
trainBatchSize = 5,
valBatchSize = 5,
rotMaxDegree = 0,
toolJointNames = {'LeftClasperPoint', 'RightClasperPoint',
'HeadPoint', 'ShaftPoint', 'EndPoint' }, -- joint number = 5
toolCompoNames = {{'LeftClasperPoint', 'HeadPoint'},
{'RightClasperPoint', 'HeadPoint'},
{'HeadPoint', 'ShaftPoint'},
{'ShaftPoint', 'EndPoint'}
},
nEpoches = 300
}
opt.jointRadius = opt.modelConf.jointRadius or 20
opt.modelOutputScale = opt.modelConf.modelOutputScale or 4
opt.inputWidth = opt.modelConf.inputWidth or 480 -- 720
opt.inputHeight = opt.modelConf.inputHeight or 384 -- 576
opt.vflip = opt.modelConf.vflip or 0
opt.hflip = opt.modelConf.hflip or 0
local initID = getDetID(opt.modelConf)
local saveID = getSaveID(opt.modelConf)
local initModelPath = paths.concat(opt.saveDir, 'model.' .. initID .. '.best.t7')
local lastModelPath = paths.concat(opt.saveDir, 'model.' .. saveID .. '.last.t7')
local lastOptimStatePath = paths.concat(opt.saveDir, 'optim.' .. saveID .. '.last.t7')
local bestModelPath = paths.concat(opt.saveDir, 'model.' .. saveID .. '.best.t7')
local bestOptimStatePath = paths.concat(opt.saveDir, 'optim.' .. saveID .. '.best.t7')
local function getModelPath()
local modelPath
if opt.retrain == 'last' and paths.filep(lastModelPath) then
modelPath = lastModelPath
elseif opt.retrain == 'best' and paths.filep(bestModelPath) then
modelPath = bestModelPath
else
modelPath = initModelPath
end
print('current using model: ' .. modelPath)
return modelPath
end
local function getModel()
local model = torch.load(getModelPath())
return model
end
local function getOptimState()
local optimState
if opt.retrain == 'last' and paths.filep(lastOptimStatePath) then
optimState = torch.load(lastOptimStatePath)
-- optimState.learningRate = 1e-5
elseif opt.retrain == 'best' and paths.filep(bestOptimStatePath) then
optimState = torch.load(bestOptimStatePath)
else
optimState = {
learningRate = opt.learningRate,
weightDecay = opt.weightDecay,
momentum = opt.momentum,
dampening = 0.0,
nesterov = true,
epoch = 0
}
end
return optimState
end
-- when saving, clear the potential tensors in the optim state
local function saveOptimState(save_path, optim_state)
local optimState = {}
for key, value in pairs(optim_state) do
if not torch.isTensor(value) then
optimState[key] = value
end
end
torch.save(save_path, optimState)
end
local model_path = getModelPath()
local model
local runningState = {valAcc=0, model = getModel(), optimState = getOptimState() }
local loggerPath = paths.concat(opt.saveDir, 'log.' .. saveID .. '_epoch' .. runningState.optimState.epoch .. '.t7')
local logPath = paths.concat(opt.saveDir, 'log.' .. saveID .. '_epoch' .. runningState.optimState.epoch .. '.txt')
-- The runner handles the training loop and evaluate on the val set
local runner = Runner(model_path, opt, runningState.optimState)
model = runner:getModel()
print('optim State: ')
print(runningState.optimState)
local best_epoch = runningState.optimState.epoch
local logFile = io.open(logPath, 'w')
local logger = torch.FloatTensor(opt.nEpoches, 5)
-- Run model on validation set
local valAcc, valLoss = runner:val(0)
print(string.format("Val : robustness accuracy = %.3f, loss = %.5f", valAcc, valLoss))
for epoch = 1, opt.nEpoches do
print('\nepoch # ' .. epoch)
-- train for a single epoch
local trainAcc, trainLoss = 0, 0
trainAcc, trainLoss = runner:train(epoch)
print(string.format("Train : robustness accuracy = %.3f, loss = %.5f", trainAcc, trainLoss))
-- Run model on validation set
local valAcc, valLoss = runner:val(epoch)
print(string.format("Val : robustness accuracy = %.3f, loss = %.5f", valAcc, valLoss))
local testAcc, testLoss = runner:test(epoch)
print(string.format("Test : test random Sample."))
-- copyModel(model, runningState.model)
-- torch.save(lastModelPath, runningState.model)
torch.save(lastModelPath, model:clearState())
saveOptimState(lastOptimStatePath, runningState.optimState)
logger[epoch][1] = runningState.optimState.epoch
logger[epoch][2] = trainAcc
logger[epoch][3] = valAcc
logger[epoch][4] = trainLoss
logger[epoch][5] = valLoss
logFile:write(string.format('%d %.3f %.3f %.5f %.5f\n',
logger[epoch][1], logger[epoch][2], logger[epoch][3], logger[epoch][4], logger[epoch][5]))
logFile:flush()
torch.save(loggerPath, logger)
print('optim State for this epoch: ')
print(runningState.optimState)
print(string.format("Train : robustness accuracy = %.3f, loss = %.5f", trainAcc, trainLoss))
print(string.format("Val : robustness accuracy = %.3f, loss = %.5f", valAcc, valLoss))
if valAcc > runningState.valAcc then
print('Saving the best! ')
best_epoch = runningState.optimState.epoch
runningState.valAcc = valAcc
-- torch.save(bestModelPath, runningState.model)
torch.save(bestModelPath, model:clearState())
saveOptimState(bestOptimStatePath, runningState.optimState)
end
end
logFile:write(string.format('bestModel.epoch = %d, bestModel.valAcc = %.3f', best_epoch, runningState.valAcc))
logFile:flush()
logFile:close()
-- copy the log file
local logFinalPath = paths.concat(opt.saveDir, 'log.' .. saveID .. '_ep' .. runningState.optimState.epoch .. '.txt')
local inlogFile = io.open(logPath, 'r')
local instr = inlogFile:read('*a')
inlogFile:close()
local outlogFile = io.open(logFinalPath, 'w')
outlogFile:write(instr)
outlogFile:close()
logger = nil
runningState.model = nil
runningState.optimState = nil
model = nil