minibatch_adam.lua 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. require 'optim'
  2. require 'cutorch'
  3. require 'xlua'
  4. local function minibatch_adam(model, criterion,
  5. train_x,
  6. config, transformer,
  7. input_size, target_size)
  8. local parameters, gradParameters = model:getParameters()
  9. config = config or {}
  10. local sum_loss = 0
  11. local count_loss = 0
  12. local batch_size = config.xBatchSize or 32
  13. local shuffle = torch.randperm(#train_x)
  14. local c = 1
  15. local inputs = torch.Tensor(batch_size,
  16. input_size[1], input_size[2], input_size[3]):cuda()
  17. local targets = torch.Tensor(batch_size,
  18. target_size[1] * target_size[2] * target_size[3]):cuda()
  19. local inputs_tmp = torch.Tensor(batch_size,
  20. input_size[1], input_size[2], input_size[3])
  21. local targets_tmp = torch.Tensor(batch_size,
  22. target_size[1] * target_size[2] * target_size[3])
  23. for t = 1, #train_x do
  24. xlua.progress(t, #train_x)
  25. local xy = transformer(train_x[shuffle[t]], false, batch_size)
  26. for i = 1, #xy do
  27. inputs_tmp[i]:copy(xy[i][1])
  28. targets_tmp[i]:copy(xy[i][2])
  29. end
  30. inputs:copy(inputs_tmp)
  31. targets:copy(targets_tmp)
  32. local feval = function(x)
  33. if x ~= parameters then
  34. parameters:copy(x)
  35. end
  36. gradParameters:zero()
  37. local output = model:forward(inputs)
  38. local f = criterion:forward(output, targets)
  39. sum_loss = sum_loss + f
  40. count_loss = count_loss + 1
  41. model:backward(inputs, criterion:backward(output, targets))
  42. return f, gradParameters
  43. end
  44. optim.adam(feval, parameters, config)
  45. c = c + 1
  46. if c % 10 == 0 then
  47. collectgarbage()
  48. end
  49. end
  50. xlua.progress(#train_x, #train_x)
  51. return { loss = sum_loss / count_loss}
  52. end
  53. return minibatch_adam