train.lua 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697
  1. require 'pl'
  2. local __FILE__ = (function() return string.gsub(debug.getinfo(2, 'S').source, "^@", "") end)()
  3. package.path = path.join(path.dirname(__FILE__), "lib", "?.lua;") .. package.path
  4. require 'optim'
  5. require 'xlua'
  6. require 'image'
  7. require 'w2nn'
  8. local threads = require 'threads'
  9. local settings = require 'settings'
  10. local srcnn = require 'srcnn'
  11. local minibatch_adam = require 'minibatch_adam'
  12. local iproc = require 'iproc'
  13. local reconstruct = require 'reconstruct'
  14. local image_loader = require 'image_loader'
  15. local function save_test_scale(model, rgb, file)
  16. local up = reconstruct.scale(model, settings.scale, rgb)
  17. image.save(file, up)
  18. end
  19. local function save_test_jpeg(model, rgb, file)
  20. local im, count = reconstruct.image(model, rgb)
  21. image.save(file, im)
  22. end
  23. local function save_test_user(model, rgb, file)
  24. if settings.scale == 1 then
  25. save_test_jpeg(model, rgb, file)
  26. else
  27. save_test_scale(model, rgb, file)
  28. end
  29. end
  30. local function split_data(x, test_size)
  31. if settings.validation_filename_split then
  32. if not (x[1][2].data and x[1][2].data.basename) then
  33. error("`images.t` does not have basename info. You need to re-run `convert_data.lua`.")
  34. end
  35. local basename_db = {}
  36. for i = 1, #x do
  37. local meta = x[i][2].data
  38. if basename_db[meta.basename] then
  39. table.insert(basename_db[meta.basename], x[i])
  40. else
  41. basename_db[meta.basename] = {x[i]}
  42. end
  43. end
  44. local basename_list = {}
  45. for k, v in pairs(basename_db) do
  46. table.insert(basename_list, v)
  47. end
  48. local index = torch.randperm(#basename_list)
  49. local train_x = {}
  50. local valid_x = {}
  51. local pos = 1
  52. for i = 1, #basename_list do
  53. if #valid_x >= test_size then
  54. break
  55. end
  56. local xs = basename_list[index[pos]]
  57. for j = 1, #xs do
  58. table.insert(valid_x, xs[j])
  59. end
  60. pos = pos + 1
  61. end
  62. for i = pos, #basename_list do
  63. local xs = basename_list[index[i]]
  64. for j = 1, #xs do
  65. table.insert(train_x, xs[j])
  66. end
  67. end
  68. return train_x, valid_x
  69. else
  70. local index = torch.randperm(#x)
  71. local train_size = #x - test_size
  72. local train_x = {}
  73. local valid_x = {}
  74. for i = 1, train_size do
  75. train_x[i] = x[index[i]]
  76. end
  77. for i = 1, test_size do
  78. valid_x[i] = x[index[train_size + i]]
  79. end
  80. return train_x, valid_x
  81. end
  82. end
  83. local g_transform_pool = nil
  84. local g_mutex = nil
  85. local g_mutex_id = nil
  86. local function transform_pool_init(has_resize, offset)
  87. local nthread = torch.getnumthreads()
  88. if (settings.thread > 0) then
  89. nthread = settings.thread
  90. end
  91. g_mutex = threads.Mutex()
  92. g_mutex_id = g_mutex:id()
  93. g_transform_pool = threads.Threads(
  94. nthread,
  95. threads.safe(
  96. function(threadid)
  97. require 'pl'
  98. local __FILE__ = (function() return string.gsub(debug.getinfo(2, 'S').source, "^@", "") end)()
  99. package.path = path.join(path.dirname(__FILE__), "lib", "?.lua;") .. package.path
  100. require 'torch'
  101. require 'nn'
  102. require 'cunn'
  103. torch.setnumthreads(1)
  104. torch.setdefaulttensortype("torch.FloatTensor")
  105. local threads = require 'threads'
  106. local compression = require 'compression'
  107. local pairwise_transform = require 'pairwise_transform'
  108. function transformer(x, is_validation, n)
  109. local mutex = threads.Mutex(g_mutex_id)
  110. local meta = {data = {}}
  111. local y = nil
  112. if type(x) == "table" and type(x[2]) == "table" then
  113. meta = x[2]
  114. if x[1].x and x[1].y then
  115. y = compression.decompress(x[1].y)
  116. x = compression.decompress(x[1].x)
  117. else
  118. x = compression.decompress(x[1])
  119. end
  120. else
  121. x = compression.decompress(x)
  122. end
  123. n = n or settings.patches
  124. if is_validation == nil then is_validation = false end
  125. local random_color_noise_rate = nil
  126. local random_overlay_rate = nil
  127. local active_cropping_rate = nil
  128. local active_cropping_tries = nil
  129. if is_validation then
  130. active_cropping_rate = settings.active_cropping_rate
  131. active_cropping_tries = settings.active_cropping_tries
  132. random_color_noise_rate = 0.0
  133. random_overlay_rate = 0.0
  134. else
  135. active_cropping_rate = settings.active_cropping_rate
  136. active_cropping_tries = settings.active_cropping_tries
  137. random_color_noise_rate = settings.random_color_noise_rate
  138. random_overlay_rate = settings.random_overlay_rate
  139. end
  140. if settings.method == "scale" then
  141. local conf = tablex.update({
  142. mutex = mutex,
  143. downsampling_filters = settings.downsampling_filters,
  144. random_half_rate = settings.random_half_rate,
  145. random_color_noise_rate = random_color_noise_rate,
  146. random_overlay_rate = random_overlay_rate,
  147. random_unsharp_mask_rate = settings.random_unsharp_mask_rate,
  148. random_blur_rate = settings.random_blur_rate,
  149. random_blur_size = settings.random_blur_size,
  150. random_blur_sigma_min = settings.random_blur_sigma_min,
  151. random_blur_sigma_max = settings.random_blur_sigma_max,
  152. max_size = settings.max_size,
  153. active_cropping_rate = active_cropping_rate,
  154. active_cropping_tries = active_cropping_tries,
  155. rgb = (settings.color == "rgb"),
  156. x_upsampling = not has_resize,
  157. resize_blur_min = settings.resize_blur_min,
  158. resize_blur_max = settings.resize_blur_max}, meta)
  159. return pairwise_transform.scale(x,
  160. settings.scale,
  161. settings.crop_size, offset,
  162. n, conf)
  163. elseif settings.method == "noise" then
  164. local conf = tablex.update({
  165. mutex = mutex,
  166. random_half_rate = settings.random_half_rate,
  167. random_color_noise_rate = random_color_noise_rate,
  168. random_overlay_rate = random_overlay_rate,
  169. random_unsharp_mask_rate = settings.random_unsharp_mask_rate,
  170. random_blur_rate = settings.random_blur_rate,
  171. random_blur_size = settings.random_blur_size,
  172. random_blur_sigma_min = settings.random_blur_sigma_min,
  173. random_blur_sigma_max = settings.random_blur_sigma_max,
  174. max_size = settings.max_size,
  175. jpeg_chroma_subsampling_rate = settings.jpeg_chroma_subsampling_rate,
  176. active_cropping_rate = active_cropping_rate,
  177. active_cropping_tries = active_cropping_tries,
  178. nr_rate = settings.nr_rate,
  179. rgb = (settings.color == "rgb")}, meta)
  180. return pairwise_transform.jpeg(x,
  181. settings.style,
  182. settings.noise_level,
  183. settings.crop_size, offset,
  184. n, conf)
  185. elseif settings.method == "noise_scale" then
  186. local conf = tablex.update({
  187. mutex = mutex,
  188. downsampling_filters = settings.downsampling_filters,
  189. random_half_rate = settings.random_half_rate,
  190. random_color_noise_rate = random_color_noise_rate,
  191. random_overlay_rate = random_overlay_rate,
  192. random_unsharp_mask_rate = settings.random_unsharp_mask_rate,
  193. random_blur_rate = settings.random_blur_rate,
  194. random_blur_size = settings.random_blur_size,
  195. random_blur_sigma_min = settings.random_blur_sigma_min,
  196. random_blur_sigma_max = settings.random_blur_sigma_max,
  197. max_size = settings.max_size,
  198. jpeg_chroma_subsampling_rate = settings.jpeg_chroma_subsampling_rate,
  199. nr_rate = settings.nr_rate,
  200. active_cropping_rate = active_cropping_rate,
  201. active_cropping_tries = active_cropping_tries,
  202. rgb = (settings.color == "rgb"),
  203. x_upsampling = not has_resize,
  204. resize_blur_min = settings.resize_blur_min,
  205. resize_blur_max = settings.resize_blur_max}, meta)
  206. return pairwise_transform.jpeg_scale(x,
  207. settings.scale,
  208. settings.style,
  209. settings.noise_level,
  210. settings.crop_size, offset,
  211. n, conf)
  212. elseif settings.method == "user" then
  213. local random_erasing_rate = 0
  214. local random_erasing_n = 0
  215. local random_erasing_rect_min = 0
  216. local random_erasing_rect_max = 0
  217. if is_validation then
  218. else
  219. random_erasing_rate = settings.random_erasing_rate
  220. random_erasing_n = settings.random_erasing_n
  221. random_erasing_rect_min = settings.random_erasing_rect_min
  222. random_erasing_rect_max = settings.random_erasing_rect_max
  223. end
  224. local conf = tablex.update({
  225. gcn = settings.gcn,
  226. max_size = settings.max_size,
  227. active_cropping_rate = active_cropping_rate,
  228. active_cropping_tries = active_cropping_tries,
  229. random_pairwise_rotate_rate = settings.random_pairwise_rotate_rate,
  230. random_pairwise_rotate_min = settings.random_pairwise_rotate_min,
  231. random_pairwise_rotate_max = settings.random_pairwise_rotate_max,
  232. random_pairwise_scale_rate = settings.random_pairwise_scale_rate,
  233. random_pairwise_scale_min = settings.random_pairwise_scale_min,
  234. random_pairwise_scale_max = settings.random_pairwise_scale_max,
  235. random_pairwise_negate_rate = settings.random_pairwise_negate_rate,
  236. random_pairwise_negate_x_rate = settings.random_pairwise_negate_x_rate,
  237. pairwise_y_binary = settings.pairwise_y_binary,
  238. pairwise_flip = settings.pairwise_flip,
  239. random_erasing_rate = random_erasing_rate,
  240. random_erasing_n = random_erasing_n,
  241. random_erasing_rect_min = random_erasing_rect_min,
  242. random_erasing_rect_max = random_erasing_rect_max,
  243. rgb = (settings.color == "rgb")}, meta)
  244. return pairwise_transform.user(x, y,
  245. settings.crop_size, offset,
  246. n, conf)
  247. end
  248. end
  249. end)
  250. )
  251. g_transform_pool:synchronize()
  252. end
  253. local function make_validation_set(x, n, patches)
  254. local nthread = torch.getnumthreads()
  255. if (settings.thread > 0) then
  256. nthread = settings.thread
  257. end
  258. n = n or 4
  259. local validation_patches = math.min(16, patches or 16)
  260. local data = {}
  261. g_transform_pool:synchronize()
  262. torch.setnumthreads(1) -- 1
  263. for i = 1, #x do
  264. for k = 1, math.max(n / validation_patches, 1) do
  265. local input = x[i]
  266. g_transform_pool:addjob(
  267. function()
  268. local xy = transformer(input, true, validation_patches)
  269. return xy
  270. end,
  271. function(xy)
  272. for j = 1, #xy do
  273. table.insert(data, {x = xy[j][1], y = xy[j][2]})
  274. end
  275. end
  276. )
  277. end
  278. if i % 20 == 0 then
  279. collectgarbage()
  280. g_transform_pool:synchronize()
  281. xlua.progress(i, #x)
  282. end
  283. end
  284. g_transform_pool:synchronize()
  285. torch.setnumthreads(nthread) -- revert
  286. local new_data = {}
  287. local perm = torch.randperm(#data)
  288. for i = 1, perm:size(1) do
  289. new_data[i] = data[perm[i]]
  290. end
  291. data = new_data
  292. return data
  293. end
  294. local function validate(model, criterion, eval_metric, data, batch_size)
  295. local psnr = 0
  296. local loss = 0
  297. local mse = 0
  298. local loss_count = 0
  299. local inputs_tmp = torch.Tensor(batch_size,
  300. data[1].x:size(1),
  301. data[1].x:size(2),
  302. data[1].x:size(3)):zero()
  303. local targets_tmp = torch.Tensor(batch_size,
  304. data[1].y:size(1),
  305. data[1].y:size(2),
  306. data[1].y:size(3)):zero()
  307. local inputs = inputs_tmp:clone():cuda()
  308. local targets = targets_tmp:clone():cuda()
  309. for t = 1, #data, batch_size do
  310. if t + batch_size -1 > #data then
  311. break
  312. end
  313. for i = 1, batch_size do
  314. inputs_tmp[i]:copy(data[t + i - 1].x)
  315. targets_tmp[i]:copy(data[t + i - 1].y)
  316. end
  317. inputs:copy(inputs_tmp)
  318. targets:copy(targets_tmp)
  319. local z = model:forward(inputs)
  320. local batch_mse = eval_metric:forward(z, targets)
  321. loss = loss + criterion:forward(z, targets)
  322. mse = mse + batch_mse
  323. psnr = psnr + (10 * math.log10(1 / (batch_mse + 1.0e-6)))
  324. loss_count = loss_count + 1
  325. if loss_count % 10 == 0 then
  326. xlua.progress(t, #data)
  327. collectgarbage()
  328. end
  329. end
  330. xlua.progress(#data, #data)
  331. return {loss = loss / loss_count, MSE = mse / loss_count, PSNR = psnr / loss_count}
  332. end
  333. local function create_criterion(model)
  334. if settings.loss == "huber" then
  335. if reconstruct.is_rgb(model) then
  336. local offset = reconstruct.offset_size(model)
  337. local output_w = settings.crop_size - offset * 2
  338. local weight = torch.Tensor(3, output_w * output_w)
  339. weight[1]:fill(0.29891 * 3) -- R
  340. weight[2]:fill(0.58661 * 3) -- G
  341. weight[3]:fill(0.11448 * 3) -- B
  342. return w2nn.ClippedWeightedHuberCriterion(weight, 0.1, {0.0, 1.0}):cuda()
  343. else
  344. local offset = reconstruct.offset_size(model)
  345. local output_w = settings.crop_size - offset * 2
  346. local weight = torch.Tensor(1, output_w * output_w)
  347. weight[1]:fill(1.0)
  348. return w2nn.ClippedWeightedHuberCriterion(weight, 0.1, {0.0, 1.0}):cuda()
  349. end
  350. elseif settings.loss == "l1" then
  351. return w2nn.L1Criterion():cuda()
  352. elseif settings.loss == "mse" then
  353. return w2nn.ClippedMSECriterion(0, 1.0):cuda()
  354. elseif settings.loss == "bce" then
  355. local bce = nn.BCECriterion()
  356. bce.sizeAverage = true
  357. return bce:cuda()
  358. elseif settings.loss == "aux_bce" then
  359. local aux = w2nn.AuxiliaryLossCriterion(nn.BCECriterion)
  360. aux.sizeAverage = true
  361. return aux:cuda()
  362. elseif settings.loss == "aux_huber" then
  363. local args = {}
  364. if reconstruct.is_rgb(model) then
  365. local offset = reconstruct.offset_size(model)
  366. local output_w = settings.crop_size - offset * 2
  367. local weight = torch.Tensor(3, output_w * output_w)
  368. weight[1]:fill(0.29891 * 3) -- R
  369. weight[2]:fill(0.58661 * 3) -- G
  370. weight[3]:fill(0.11448 * 3) -- B
  371. args = {weight, 0.1, {0.0, 1.0}}
  372. else
  373. local offset = reconstruct.offset_size(model)
  374. local output_w = settings.crop_size - offset * 2
  375. local weight = torch.Tensor(1, output_w * output_w)
  376. weight[1]:fill(1.0)
  377. args = {weight, 0.1, {0.0, 1.0}}
  378. end
  379. local aux = w2nn.AuxiliaryLossCriterion(w2nn.ClippedWeightedHuberCriterion, args)
  380. return aux:cuda()
  381. elseif settings.loss == "lbp" then
  382. if reconstruct.is_rgb(model) then
  383. return w2nn.RandomBinaryCriterion(3, 128):cuda()
  384. else
  385. return w2nn.RandomBinaryCriterion(1, 128):cuda()
  386. end
  387. elseif settings.loss == "aux_lbp" then
  388. if reconstruct.is_rgb(model) then
  389. return w2nn.AuxiliaryLossCriterion(w2nn.RandomBinaryCriterion, {3, 128}):cuda()
  390. else
  391. return w2nn.AuxiliaryLossCriterion(w2nn.RandomBinaryCriterion, {1, 128}):cuda()
  392. end
  393. else
  394. error("unsupported loss .." .. settings.loss)
  395. end
  396. end
  397. local function resampling(x, y, train_x)
  398. local c = 1
  399. local shuffle = torch.randperm(#train_x)
  400. local nthread = torch.getnumthreads()
  401. if (settings.thread > 0) then
  402. nthread = settings.thread
  403. end
  404. torch.setnumthreads(1) -- 1
  405. for t = 1, #train_x do
  406. local input = train_x[shuffle[t]]
  407. g_transform_pool:addjob(
  408. function()
  409. local xy = transformer(input, false, settings.patches)
  410. return xy
  411. end,
  412. function(xy)
  413. for i = 1, #xy do
  414. if c <= x:size(1) then
  415. x[c]:copy(xy[i][1])
  416. y[c]:copy(xy[i][2])
  417. c = c + 1
  418. else
  419. break
  420. end
  421. end
  422. end
  423. )
  424. if t % 50 == 0 then
  425. collectgarbage()
  426. g_transform_pool:synchronize()
  427. xlua.progress(t, #train_x)
  428. end
  429. if c > x:size(1) then
  430. break
  431. end
  432. end
  433. g_transform_pool:synchronize()
  434. xlua.progress(#train_x, #train_x)
  435. torch.setnumthreads(nthread) -- revert
  436. end
  437. local function get_oracle_data(x, y, instance_loss, k, samples)
  438. local index = torch.LongTensor(instance_loss:size(1))
  439. local dummy = torch.Tensor(instance_loss:size(1))
  440. torch.topk(dummy, index, instance_loss, k, 1, true)
  441. print("MSE of all data: " ..instance_loss:mean() .. ", MSE of oracle data: " .. dummy:mean())
  442. local shuffle = torch.randperm(k)
  443. local x_s = x:size()
  444. local y_s = y:size()
  445. x_s[1] = samples
  446. y_s[1] = samples
  447. local oracle_x = torch.Tensor(table.unpack(torch.totable(x_s)))
  448. local oracle_y = torch.Tensor(table.unpack(torch.totable(y_s)))
  449. for i = 1, samples do
  450. oracle_x[i]:copy(x[index[shuffle[i]]])
  451. oracle_y[i]:copy(y[index[shuffle[i]]])
  452. end
  453. return oracle_x, oracle_y
  454. end
  455. local function remove_small_image(x)
  456. local compression = require 'compression'
  457. local new_x = {}
  458. for i = 1, #x do
  459. local xe, meta, x_s
  460. xe = x[i]
  461. if type(x) == "table" and type(x[2]) == "table" then
  462. if xe[1].x and xe[1].y then
  463. x_s = compression.size(xe[1].y) -- y size
  464. else
  465. x_s = compression.size(xe[1])
  466. end
  467. else
  468. x_s = compression.size(xe)
  469. end
  470. if x_s[2] / settings.scale > settings.crop_size + 32 and
  471. x_s[3] / settings.scale > settings.crop_size + 32 then
  472. table.insert(new_x, x[i])
  473. end
  474. if i % 100 == 0 then
  475. collectgarbage()
  476. end
  477. end
  478. print(string.format("%d small images are removed", #x - #new_x))
  479. return new_x
  480. end
  481. local function plot(train, valid)
  482. gnuplot.plot({
  483. {'training', torch.Tensor(train), '-'},
  484. {'validation', torch.Tensor(valid), '-'}})
  485. end
  486. local function train()
  487. local x = torch.load(settings.images)
  488. if settings.method ~= "user" then
  489. x = remove_small_image(x)
  490. end
  491. local train_x, valid_x = split_data(x, math.max(math.floor(settings.validation_rate * #x), 1))
  492. local hist_train = {}
  493. local hist_valid = {}
  494. local model
  495. if settings.resume:len() > 0 then
  496. model = torch.load(settings.resume, "ascii")
  497. else
  498. if stringx.endswith(settings.model, ".lua") then
  499. local create_model = dofile(settings.model)
  500. model = create_model(srcnn, settings)
  501. else
  502. model = srcnn.create(settings.model, settings.backend, settings.color)
  503. end
  504. end
  505. if model.w2nn_input_size then
  506. if settings.crop_size ~= model.w2nn_input_size then
  507. io.stderr:write(string.format("warning: crop_size is replaced with %d\n",
  508. model.w2nn_input_size))
  509. settings.crop_size = model.w2nn_input_size
  510. end
  511. end
  512. if model.w2nn_gcn then
  513. settings.gcn = true
  514. else
  515. settings.gcn = false
  516. end
  517. dir.makepath(settings.model_dir)
  518. local offset = reconstruct.offset_size(model)
  519. transform_pool_init(reconstruct.has_resize(model), offset)
  520. local criterion = create_criterion(model)
  521. local eval_metric = nil
  522. if settings.loss:find("aux_") ~= nil then
  523. eval_metric = w2nn.AuxiliaryLossCriterion(w2nn.ClippedMSECriterion):cuda()
  524. else
  525. eval_metric = w2nn.ClippedMSECriterion():cuda()
  526. end
  527. local adam_config = {
  528. xLearningRate = settings.learning_rate,
  529. xBatchSize = settings.batch_size,
  530. xLearningRateDecay = settings.learning_rate_decay,
  531. xInstanceLoss = (settings.oracle_rate > 0)
  532. }
  533. local ch = nil
  534. if settings.color == "y" then
  535. ch = 1
  536. elseif settings.color == "rgb" then
  537. ch = 3
  538. end
  539. local best_score = 1000.0
  540. print("# make validation-set")
  541. local valid_xy = make_validation_set(valid_x,
  542. settings.validation_crops,
  543. settings.patches)
  544. valid_x = nil
  545. collectgarbage()
  546. model:cuda()
  547. print("load .. " .. #train_x)
  548. local x = nil
  549. local y = torch.Tensor(settings.patches * #train_x,
  550. ch * (settings.crop_size - offset * 2) * (settings.crop_size - offset * 2)):zero()
  551. if reconstruct.has_resize(model) then
  552. x = torch.Tensor(settings.patches * #train_x,
  553. ch, settings.crop_size / settings.scale, settings.crop_size / settings.scale)
  554. else
  555. x = torch.Tensor(settings.patches * #train_x,
  556. ch, settings.crop_size, settings.crop_size)
  557. end
  558. local instance_loss = nil
  559. local pmodel = w2nn.data_parallel(model, settings.gpu)
  560. for epoch = 1, settings.epoch do
  561. pmodel:training()
  562. print("# " .. epoch)
  563. if adam_config.learningRate then
  564. print("learning rate: " .. adam_config.learningRate)
  565. end
  566. print("## resampling")
  567. if instance_loss then
  568. -- active learning
  569. local oracle_k = math.min(x:size(1) * (settings.oracle_rate * (1 / (1 - settings.oracle_drop_rate))), x:size(1))
  570. local oracle_n = math.min(x:size(1) * settings.oracle_rate, x:size(1))
  571. if oracle_n > 0 then
  572. local oracle_x, oracle_y = get_oracle_data(x, y, instance_loss, oracle_k, oracle_n)
  573. resampling(x:narrow(1, oracle_x:size(1) + 1, x:size(1)-oracle_x:size(1)),
  574. y:narrow(1, oracle_x:size(1) + 1, x:size(1) - oracle_x:size(1)), train_x)
  575. x:narrow(1, 1, oracle_x:size(1)):copy(oracle_x)
  576. y:narrow(1, 1, oracle_y:size(1)):copy(oracle_y)
  577. local draw_n = math.floor(math.sqrt(oracle_x:size(1), 0.5))
  578. if draw_n > 100 then
  579. draw_n = 100
  580. end
  581. image.save(path.join(settings.model_dir, "oracle_x.png"),
  582. image.toDisplayTensor({
  583. input = oracle_x:narrow(1, 1, draw_n * draw_n),
  584. padding = 2,
  585. nrow = draw_n,
  586. min = 0,
  587. max = 1}))
  588. else
  589. resampling(x, y, train_x)
  590. end
  591. else
  592. resampling(x, y, train_x, pairwise_func)
  593. end
  594. collectgarbage()
  595. instance_loss = torch.Tensor(x:size(1)):zero()
  596. for i = 1, settings.inner_epoch do
  597. pmodel:training()
  598. local train_score, il = minibatch_adam(pmodel, criterion, eval_metric, x, y, adam_config)
  599. instance_loss:copy(il)
  600. print(train_score)
  601. pmodel:evaluate()
  602. print("# validation")
  603. local score = validate(pmodel, criterion, eval_metric, valid_xy, adam_config.xBatchSize)
  604. table.insert(hist_train, train_score.loss)
  605. table.insert(hist_valid, score.loss)
  606. if settings.plot then
  607. plot(hist_train, hist_valid)
  608. end
  609. local score_for_update
  610. if settings.update_criterion == "mse" then
  611. score_for_update = score.MSE
  612. else
  613. score_for_update = score.loss
  614. end
  615. if score_for_update < best_score then
  616. local test_image = image_loader.load_float(settings.test) -- reload
  617. best_score = score_for_update
  618. print("* model has updated")
  619. if settings.save_history then
  620. pmodel:clearState()
  621. torch.save(settings.model_file_best, model, "ascii")
  622. torch.save(string.format(settings.model_file, epoch, i), model, "ascii")
  623. if settings.method == "noise" then
  624. local log = path.join(settings.model_dir,
  625. ("noise%d_best.%d-%d.png"):format(settings.noise_level,
  626. epoch, i))
  627. save_test_jpeg(model, test_image, log)
  628. elseif settings.method == "scale" then
  629. local log = path.join(settings.model_dir,
  630. ("scale%.1f_best.%d-%d.png"):format(settings.scale,
  631. epoch, i))
  632. save_test_scale(model, test_image, log)
  633. elseif settings.method == "noise_scale" then
  634. local log = path.join(settings.model_dir,
  635. ("noise%d_scale%.1f_best.%d-%d.png"):format(settings.noise_level,
  636. settings.scale,
  637. epoch, i))
  638. save_test_scale(model, test_image, log)
  639. elseif settings.method == "user" then
  640. local log = path.join(settings.model_dir,
  641. ("%s_best.%d-%d.png"):format(settings.name,
  642. epoch, i))
  643. save_test_user(model, test_image, log)
  644. end
  645. else
  646. pmodel:clearState()
  647. torch.save(settings.model_file, model, "ascii")
  648. if settings.method == "noise" then
  649. local log = path.join(settings.model_dir,
  650. ("noise%d_best.png"):format(settings.noise_level))
  651. save_test_jpeg(model, test_image, log)
  652. elseif settings.method == "scale" then
  653. local log = path.join(settings.model_dir,
  654. ("scale%.1f_best.png"):format(settings.scale))
  655. save_test_scale(model, test_image, log)
  656. elseif settings.method == "noise_scale" then
  657. local log = path.join(settings.model_dir,
  658. ("noise%d_scale%.1f_best.png"):format(settings.noise_level,
  659. settings.scale))
  660. save_test_scale(model, test_image, log)
  661. elseif settings.method == "user" then
  662. local log = path.join(settings.model_dir,
  663. ("%s_best.png"):format(settings.name))
  664. save_test_user(model, test_image, log)
  665. end
  666. end
  667. end
  668. print("Batch-wise PSNR: " .. score.PSNR .. ", loss: " .. score.loss .. ", MSE: " .. score.MSE .. ", best: " .. best_score)
  669. collectgarbage()
  670. end
  671. end
  672. end
  673. torch.manualSeed(settings.seed)
  674. cutorch.manualSeed(settings.seed)
  675. print(settings)
  676. train()