train.lua 6.9 KB

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