train.lua 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. local __FILE__ = (function() return string.gsub(debug.getinfo(2, 'S').source, "^@", "") end)()
  2. package.path = path.join(path.dirname(__FILE__), "lib", "?.lua;") .. package.path
  3. require 'optim'
  4. require 'xlua'
  5. require 'pl'
  6. require 'w2nn'
  7. local settings = require 'settings'
  8. local srcnn = require 'srcnn'
  9. local minibatch_adam = require 'minibatch_adam'
  10. local iproc = require 'iproc'
  11. local reconstruct = require 'reconstruct'
  12. local compression = require 'compression'
  13. local pairwise_transform = require 'pairwise_transform'
  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 split_data(x, test_size)
  24. local index = torch.randperm(#x)
  25. local train_size = #x - test_size
  26. local train_x = {}
  27. local valid_x = {}
  28. for i = 1, train_size do
  29. train_x[i] = x[index[i]]
  30. end
  31. for i = 1, test_size do
  32. valid_x[i] = x[index[train_size + i]]
  33. end
  34. return train_x, valid_x
  35. end
  36. local function make_validation_set(x, transformer, n)
  37. n = n or 4
  38. local data = {}
  39. for i = 1, #x do
  40. for k = 1, math.max(n / 8, 1) do
  41. local xy = transformer(x[i], true, 8)
  42. for j = 1, #xy do
  43. local x = xy[j][1]
  44. local y = xy[j][2]
  45. table.insert(data, {x = x:reshape(1, x:size(1), x:size(2), x:size(3)),
  46. y = y:reshape(1, y:size(1), y:size(2), y:size(3))})
  47. end
  48. end
  49. xlua.progress(i, #x)
  50. collectgarbage()
  51. end
  52. return data
  53. end
  54. local function validate(model, criterion, data)
  55. local loss = 0
  56. for i = 1, #data do
  57. local z = model:forward(data[i].x:cuda())
  58. loss = loss + criterion:forward(z, data[i].y:cuda())
  59. xlua.progress(i, #data)
  60. if i % 10 == 0 then
  61. collectgarbage()
  62. end
  63. end
  64. return loss / #data
  65. end
  66. local function create_criterion(model)
  67. if reconstruct.is_rgb(model) then
  68. local offset = reconstruct.offset_size(model)
  69. local output_w = settings.crop_size - offset * 2
  70. local weight = torch.Tensor(3, output_w * output_w)
  71. weight[1]:fill(0.299 * 3) -- R
  72. weight[2]:fill(0.587 * 3) -- G
  73. weight[3]:fill(0.114 * 3) -- B
  74. return w2nn.WeightedMSECriterion(weight):cuda()
  75. else
  76. return nn.MSECriterion():cuda()
  77. end
  78. end
  79. local function transformer(x, is_validation, n, offset)
  80. x = compression.decompress(x)
  81. n = n or settings.batch_size;
  82. if is_validation == nil then is_validation = false end
  83. local color_noise = nil
  84. local overlay = nil
  85. local active_cropping_ratio = nil
  86. local active_cropping_tries = nil
  87. if is_validation then
  88. active_cropping_rate = 0.0
  89. active_cropping_tries = 0
  90. color_noise = false
  91. overlay = false
  92. else
  93. active_cropping_rate = settings.active_cropping_rate
  94. active_cropping_tries = settings.active_cropping_tries
  95. color_noise = settings.color_noise
  96. overlay = settings.overlay
  97. end
  98. if settings.method == "scale" then
  99. return pairwise_transform.scale(x,
  100. settings.scale,
  101. settings.crop_size, offset,
  102. n,
  103. { color_noise = color_noise,
  104. overlay = overlay,
  105. random_half = settings.random_half,
  106. active_cropping_rate = active_cropping_rate,
  107. active_cropping_tries = active_cropping_tries,
  108. rgb = (settings.color == "rgb")
  109. })
  110. elseif settings.method == "noise" then
  111. return pairwise_transform.jpeg(x,
  112. settings.category,
  113. settings.noise_level,
  114. settings.crop_size, offset,
  115. n,
  116. { color_noise = color_noise,
  117. overlay = overlay,
  118. active_cropping_rate = active_cropping_rate,
  119. active_cropping_tries = active_cropping_tries,
  120. random_half = settings.random_half,
  121. jpeg_sampling_factors = settings.jpeg_sampling_factors,
  122. rgb = (settings.color == "rgb")
  123. })
  124. elseif settings.method == "noise_scale" then
  125. return pairwise_transform.jpeg_scale(x,
  126. settings.scale,
  127. settings.category,
  128. settings.noise_level,
  129. settings.crop_size, offset,
  130. n,
  131. { color_noise = color_noise,
  132. overlay = overlay,
  133. jpeg_sampling_factors = settings.jpeg_sampling_factors,
  134. random_half = settings.random_half,
  135. rgb = (settings.color == "rgb")
  136. })
  137. end
  138. end
  139. local function train()
  140. local model = srcnn.create(settings.method, settings.backend, settings.color)
  141. local offset = reconstruct.offset_size(model)
  142. local pairwise_func = function(x, is_validation, n)
  143. return transformer(x, is_validation, n, offset)
  144. end
  145. local criterion = create_criterion(model)
  146. local x = torch.load(settings.images)
  147. local lrd_count = 0
  148. local train_x, valid_x = split_data(x, math.floor(settings.validation_ratio * #x))
  149. local adam_config = {
  150. learningRate = settings.learning_rate,
  151. xBatchSize = settings.batch_size,
  152. }
  153. local ch = nil
  154. if settings.color == "y" then
  155. ch = 1
  156. elseif settings.color == "rgb" then
  157. ch = 3
  158. end
  159. local best_score = 100000.0
  160. print("# make validation-set")
  161. local valid_xy = make_validation_set(valid_x, pairwise_func, settings.validation_crops)
  162. valid_x = nil
  163. collectgarbage()
  164. model:cuda()
  165. print("load .. " .. #train_x)
  166. for epoch = 1, settings.epoch do
  167. model:training()
  168. print("# " .. epoch)
  169. print(minibatch_adam(model, criterion, train_x, adam_config,
  170. pairwise_func,
  171. {ch, settings.crop_size, settings.crop_size},
  172. {ch, settings.crop_size - offset * 2, settings.crop_size - offset * 2}
  173. ))
  174. model:evaluate()
  175. print("# validation")
  176. local score = validate(model, criterion, valid_xy)
  177. if score < best_score then
  178. local test_image = image_loader.load_float(settings.test) -- reload
  179. lrd_count = 0
  180. best_score = score
  181. print("* update best model")
  182. torch.save(settings.model_file, model)
  183. if settings.method == "noise" then
  184. local log = path.join(settings.model_dir,
  185. ("noise%d_best.png"):format(settings.noise_level))
  186. save_test_jpeg(model, test_image, log)
  187. elseif settings.method == "scale" then
  188. local log = path.join(settings.model_dir,
  189. ("scale%.1f_best.png"):format(settings.scale))
  190. save_test_scale(model, test_image, log)
  191. elseif settings.method == "noise_scale" then
  192. local log = path.join(settings.model_dir,
  193. ("noise%d_scale%.1f_best.png"):format(settings.noise_level,
  194. settings.scale))
  195. save_test_scale(model, test_image, log)
  196. end
  197. else
  198. lrd_count = lrd_count + 1
  199. if lrd_count > 5 then
  200. lrd_count = 0
  201. adam_config.learningRate = adam_config.learningRate * 0.9
  202. print("* learning rate decay: " .. adam_config.learningRate)
  203. end
  204. end
  205. print("current: " .. score .. ", best: " .. best_score)
  206. collectgarbage()
  207. end
  208. end
  209. torch.manualSeed(settings.seed)
  210. cutorch.manualSeed(settings.seed)
  211. print(settings)
  212. train()