-
Notifications
You must be signed in to change notification settings - Fork 0
/
train_main_regress_whole.lua
294 lines (251 loc) · 9.81 KB
/
train_main_regress_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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
-- regress training with train + validate dataset
require 'cunn'
require 'cudnn'
require 'cutorch'
local Runner = require 'runner_regressor'
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 getSaveID(modelConf)
local s = modelConf.type
if modelConf.iterCnt ~= nil then
s = s .. '_i' .. modelConf.iterCnt
end
s = s .. '_v' .. modelConf.v
s = s .. '_whole'
return s
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
s = s .. '_whole'
return s
end
local function getInitID(modelConf)
local s = modelConf.type
if modelConf.iterCnt ~= nil then
s = s .. '_i' .. modelConf.iterCnt
end
s = s .. '_v' .. modelConf.v
return s
end
local function getRegressID(modelConf)
local s = modelConf.type
if modelConf.iterCnt ~= nil then
s = s .. '_i' .. modelConf.iterCnt
end
s = s .. '_v' .. modelConf.v
return s
end
local opt = {
dataDir = dataDir,
saveDir = saveDir,
trainStyle = 'whole',
retrain = nil, -- nil, 'last' or 'best'
learningRate = 1e-3, -- old 1e-5
momentum = 0.98,
weightDecay = 0.0005, -- old 0.0005
decayRatio = 0.95,
updateIternal = 10,
-- detModelConf = {type='toolDualPoseSep', v=1, jointRadius=20, modelOutputScale=4},
-- modelConf = {type='toolPoseRegress', v=1, jointRadius = 20, modelOutputScale=4},
-- detModelConf = {type='toolPartDetFull', v='256*320_ftblr', jointRadius=10, modelOutputScale=1, inputWidth=320, inputHeight=256},
-- modelConf = {type='toolPoseRegressFull', v=2, jointRadius=10, modelOutputScale=1, inputWidth=320, inputHeight=256, normalScale=10},
-- modelConf = {type='toolPoseRegressFull', v='256*320_ftblr', jointRadius=10, modelOutputScale=1, inputWidth=320, inputHeight=256, normalScale=10, vflip=1, hflip=1},
-- detModelConf = {type='toolPartDetFull', v='256*320_ftblr_head', jointRadius=10, modelOutputScale=1, inputWidth=320, inputHeight=256},
-- modelConf = {type='toolPoseRegressFull', v='256*320_ftblr_head', jointRadius=10, modelOutputScale=1, inputWidth=320, inputHeight=256, normalScale=10, vflip=1, hflip=1},
-- larger radius for detection model
detModelConf = {type='toolPartDetFull', v='256*320_ftblr_head', jointRadius=15, modelOutputScale=1, inputWidth=320, inputHeight=256},
modelConf = {type='toolPoseRegressFull', v='256*320_ftblr_head_noConcat', jointRadius=20, modelOutputScale=1, inputWidth=320, inputHeight=256, normalScale=10, vflip=1, hflip=1},
gpus = {1},
nThreads = 6,
-- batchSize = 1,
trainBatchSize = 2,
valBatchSize = 2,
rotMaxDegree = 0,
toolJointNames = {'LeftClasperPoint', 'RightClasperPoint',
'HeadPoint', 'ShaftPoint', 'EndPoint' }, -- joint number = 5
toolCompoNames = {{'LeftClasperPoint', 'HeadPoint'},
{'RightClasperPoint', 'HeadPoint'},
{'HeadPoint', 'ShaftPoint'},
{'ShaftPoint', 'EndPoint'}
},
nEpoches = 300
}
opt.inputWidth = opt.modelConf.inputWidth or 320 -- 480 -- 720
opt.inputHeight = opt.modelConf.inputHeight or 256 -- 384 -- 576
opt.modelOutputScale = opt.modelConf.modelOutputScale or 4
opt.detJointRadius = opt.detModelConf.jointRadius or 10
opt.jointRadius = opt.modelConf.jointRadius or 20
opt.normalScale = opt.modelConf.normalScale or 1
opt.vflip = opt.modelConf.vflip or 0
opt.hflip = opt.modelConf.hflip or 0
local detID = getDetID(opt.detModelConf)
local detModelPath = paths.concat(opt.saveDir, 'model.' .. detID .. '.best.t7')
local initID = getRegressID(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 loggerPath = paths.concat(opt.saveDir, 'log.' .. saveID .. '.t7')
local logPath = paths.concat(opt.saveDir, 'log.' .. saveID .. '.txt')
local function getDetModelPath()
local modelPath
-- print(detModelPath)
if paths.filep(detModelPath) then
modelPath = detModelPath
end
print('current using detection model: ' .. modelPath)
return modelPath
end
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 detModel_path = getDetModelPath()
local model_path = getModelPath()
local model
local runningState = {valAcc=0, model = getModel(), optimState = getOptimState() }
-- The runner handles the training loop and evaluate on the val set
local runner = Runner(detModel_path, 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, valPrec = runner:val(0)
print(string.format("Val : robustness accuracy = %.3f, loss = %.5f", valAcc, valLoss))
print(string.format("Val : precision distance = %.3f", valPrec))
for epoch = 1, opt.nEpoches do
print('\nepoch # ' .. epoch)
-- train for a single epoch
local trainAcc, trainLoss, valAcc, valLoss, testAcc, testLoss = 0, 0, 0, 0, 0, 0
local trainPrec, valPrec = 1e+8, 1e+8
trainAcc, trainLoss, trainPrec = runner:train(epoch)
print(string.format("Train : robustness accuracy = %.3f, loss = %.5f", trainAcc, trainLoss))
print(string.format("Train : precision distance = %.3f", trainPrec))
-- Run model on validation set
valAcc, valLoss, valPrec = runner:val(epoch)
print(string.format("Val : robustness accuracy = %.3f, loss = %.5f", valAcc, valLoss))
print(string.format("Val : precision distance = %.3f", valPrec))
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("Train : precision distance = %.3f", trainPrec))
print(string.format("Val : robustness accuracy = %.3f, loss = %.5f", valAcc, valLoss))
print(string.format("Val : precision distance = %.3f", valPrec))
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