net.jl 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. """
  2. Author: Sebastian Vendt, University of Ulm
  3. """
  4. using ArgParse
  5. s = ArgParseSettings()
  6. @add_arg_table s begin
  7. "--gpu"
  8. help = "set, if you want to train on the GPU"
  9. action = :store_true
  10. "--eval"
  11. help = "set, if you want to validate instead of test after training"
  12. action = :store_true
  13. "--epochs"
  14. help = "Number of epochs"
  15. arg_type = Int64
  16. default = 30
  17. "--logmsg"
  18. help = "additional message describing the training log"
  19. arg_type = String
  20. default = ""
  21. "--csv"
  22. help = "set, if you additionally want a csv output of the learning process"
  23. action = :store_true
  24. "--runD"
  25. help = "set, if you want to run the default config"
  26. action = :store_true
  27. end
  28. parsed_args = parse_args(ARGS, s)
  29. using Flux, Statistics
  30. using Flux: onecold
  31. using BSON
  32. using Dates
  33. using Printf
  34. using NNlib
  35. using FeedbackNets
  36. include("./dataManager.jl")
  37. include("./verbose.jl")
  38. using .dataManager: make_batch
  39. using .verbose
  40. using Logging
  41. using Random
  42. import LinearAlgebra: norm
  43. norm(x::TrackedArray{T}) where T = sqrt(sum(abs2.(x)) + eps(T))
  44. ######################
  45. # PARAMETERS
  46. ######################
  47. const batch_size = 100
  48. momentum = 0.9f0
  49. const lambda = 0.0005f0
  50. const delta = 0.00001
  51. learning_rate = 0.1f0
  52. validate = parsed_args["eval"]
  53. const epochs = parsed_args["epochs"]
  54. const decay_rate = 0.1f0
  55. const decay_step = 40
  56. const usegpu = parsed_args["gpu"]
  57. const printout_interval = 2
  58. const time_format = "HH:MM:SS"
  59. const date_format = "dd_mm_yyyy"
  60. data_size = (60, 6) # resulting in a 300ms frame
  61. # DEFAULT ARCHITECTURE
  62. channels = 1
  63. features = [32, 64, 128] # needs to find the relation between the axis which represents the screen position
  64. kernel = [(3,1), (3,1), (3,6)] # convolute only horizontally, last should convolute all 6 rows together to map relations between the channels
  65. pooldims = [(2,1), (2,1)]# (30,6) -> (15,6)
  66. inputDense = [1664, 600, 300] # prod(data_size .÷ pooldims1 .÷ pooldims2 .÷ kernel3) * features3
  67. dropout_rate = 0.3f0
  68. # random search values
  69. rs_momentum = [0.9, 0.92, 0.94, 0.96, 0.98]
  70. rs_features = [[32, 64, 128], [64, 64, 64], [32, 32, 32], [96, 192, 192]]
  71. rs_dropout_rate = [0.1, 0.3, 0.4, 0.6, 0.8]
  72. rs_kernel = [[(3,1), (3,1), (3,6)], [(5,1), (5,1), (3,6)], [(7,1), (7,1), (3,6)], [(3,1), (3,1), (2,6)], [(5,1), (5,1), (2,6)], [(7,1), (7,1), (2,6)],
  73. [(7,1), (5,1), (2,6)], [(7,1), (5,1), (3,6)], [(5,1), (3,1), (2,6)], [(5,1), (3,1), (3,6)]]
  74. rs_pooldims = [[(2,1), (2,1)], [(3,1), (3,1)]]
  75. rs_learning_rate = [1, 0.3, 0.1, 0.03, 0.01, 0.003, 0.001]
  76. dataset_folderpath = "../MATLAB/TrainingData/"
  77. dataset_name = "2019_09_09_1658"
  78. const model_save_location = "../trainedModels/"
  79. const log_save_location = "./logs/"
  80. if usegpu
  81. using CuArrays
  82. end
  83. debug_str = ""
  84. log_msg = parsed_args["logmsg"]
  85. csv_out = parsed_args["csv"]
  86. runD = parsed_args["runD"]
  87. @debug begin
  88. global debug_str
  89. debug_str = "DEBUG_"
  90. "------DEBUGGING ACTIVATED------"
  91. end
  92. io = nothing
  93. io_csv = nothing
  94. function adapt_learnrate(epoch_idx)
  95. return learning_rate * decay_rate^(epoch_idx / decay_step)
  96. end
  97. function loss(model, x, y)
  98. # quadratic euclidean distance + parameternorm
  99. return Flux.mse(model(x), y) + lambda * sum(norm, params(model))
  100. end
  101. function loss(model, dataset)
  102. loss_val = 0.0f0
  103. for (data, labels) in dataset
  104. loss_val += Tracker.data(loss(model, data, labels))
  105. end
  106. return loss_val / length(dataset)
  107. end
  108. function load_dataset()
  109. train = make_batch(dataset_folderpath, "$(dataset_name)_TRAIN.mat", normalize_data=false, truncate_data=false)
  110. val = make_batch(dataset_folderpath, "$(dataset_name)_VAL.mat", normalize_data=false, truncate_data=false)
  111. test = make_batch(dataset_folderpath, "$(dataset_name)_TEST.mat", normalize_data=false, truncate_data=false)
  112. return (train, val, test)
  113. end
  114. function create_model()
  115. return Chain(
  116. Conv(kernel[1], channels=>features[1], relu, pad=map(x -> x ÷ 2, kernel[1])),
  117. MaxPool(pooldims[1], stride=pooldims[1]),
  118. Conv(kernel[2], features[1]=>features[2], relu, pad=map(x -> x ÷ 2, kernel[2])),
  119. MaxPool(pooldims[2], stride=pooldims[2]),
  120. Conv(kernel[3], features[2]=>features[3], relu),
  121. # MaxPool(),
  122. flatten,
  123. Dense(inputDense[1], inputDense[2], relu),
  124. Dropout(dropout_rate),
  125. Dense(inputDense[2], inputDense[3], relu),
  126. Dropout(dropout_rate),
  127. Dense(inputDense[3], 2, σ), # coordinates between 0 and 1
  128. )
  129. end
  130. function log(model, epoch, use_testset)
  131. Flux.testmode!(model, true)
  132. if(epoch == 0) # evalutation phase
  133. if(use_testset) @printf(io, "[%s] INIT Loss(test): %f\n", Dates.format(now(), time_format), loss(model, test_set))
  134. else @printf(io, "[%s] INIT Loss(val): %f\n", Dates.format(now(), time_format), loss(model, validation_set)) end
  135. elseif(epoch == epochs)
  136. @printf(io, "[%s] Epoch %3d: Loss(train): %f Loss(val): %f\n", Dates.format(now(), time_format), epoch, loss(model, train_set), loss(model, validation_set))
  137. if(use_testset)
  138. @printf(io, "[%s] FINAL(%d) Loss(test): %f\n", Dates.format(now(), time_format), epoch, loss(model, test_set))
  139. else
  140. @printf(io, "[%s] FINAL(%d) Loss(val): %f\n", Dates.format(now(), time_format), epoch, loss(model, validation_set))
  141. end
  142. else # learning phase
  143. if (rem(epoch, printout_interval) == 0)
  144. @printf(io, "[%s] Epoch %3d: Loss(train): %f Loss(val): %f\n", Dates.format(now(), time_format), epoch, loss(model, train_set), loss(model, validation_set))
  145. end
  146. end
  147. Flux.testmode!(model, false)
  148. end
  149. function log_csv(model, epoch)
  150. Flux.testmode!(model, true)
  151. if(csv_out) @printf(io_csv, "%d, %f, %f\n", epoch, loss(model, train_set), loss(model, validation_set)) end
  152. Flux.testmode!(model, false)
  153. end
  154. function eval_model(model)
  155. Flux.testmode!(model, true)
  156. if (validate) return loss(model, validation_set)
  157. else return loss(model, test_set) end
  158. end
  159. function train_model()
  160. model = create_model()
  161. if (usegpu) model = gpu(model) end
  162. opt = Momentum(learning_rate, momentum)
  163. log(model, 0, !validate)
  164. Flux.testmode!(model, false) # bring model in training mode
  165. last_loss = loss(model, train_set)
  166. for i in 1:epochs
  167. flush(io)
  168. Flux.train!((x, y) -> loss(model, x, y), params(model), train_set, opt)
  169. opt.eta = adapt_learnrate(i)
  170. log_csv(model, i)
  171. log(model, i, !validate)
  172. # early stopping
  173. curr_loss = loss(model, train_set)
  174. if(abs(last_loss - curr_loss) < delta)
  175. @printf(io, "Early stopping with %f at %d", curr_loss, i)
  176. return eval_model(model)
  177. end
  178. last_loss = curr_loss
  179. end
  180. return eval_model(model)
  181. end
  182. function random_search()
  183. rng = MersenneTwister()
  184. results = []
  185. for search in 1:500
  186. # create random set
  187. momentum = rand(rng, rs_momentum)
  188. features = rand(rng, rs_features)
  189. dropout_rate = rand(rng, rs_dropout_rate)
  190. kernel = rand(rng, rs_kernel)
  191. pooldims = rand(rng, rs_pooldims)
  192. learning_rate = rand(rng, rs_learning_rate)
  193. # printf configuration
  194. config1 = "momentum$(momentum), features=$(features), dropout_rate=$(dropout_rate)"
  195. config2 = "kernel=$(kernel), pooldims=$(pooldims), learning_rate=$(learning_rate)"
  196. @printf(io, "\nSearch %d of %d\n", search, 500)
  197. @printf(io, "%s\n", config1)
  198. @printf(io, "%s\n\n", config2)
  199. loss = train_model()
  200. push!(results, (search, loss))
  201. end
  202. return results
  203. end
  204. # logging framework
  205. fp = "$(log_save_location)$(debug_str)log_$(Dates.format(now(), date_format)).log"
  206. io = open(fp, "a+")
  207. global_logger(SimpleLogger(io)) # for debug outputs
  208. @printf(Base.stdout, "Logging to File: %s\n", fp)
  209. @printf(io, "\n--------[%s %s]--------\n", Dates.format(now(), date_format), Dates.format(now(), time_format))
  210. @printf(io, "%s\n", log_msg)
  211. # csv handling
  212. if (csv_out)
  213. fp_csv = "$(log_save_location)$(debug_str)csv_$(Dates.format(now(), date_format)).csv"
  214. io_csv = open(fp_csv, "w+") # read, write, create, truncate
  215. @printf(io_csv, "epoch, loss(train), loss(val)\n")
  216. end
  217. # dump configuration
  218. @debug begin
  219. for symbol in names(Main)
  220. var = "$(symbol) = $(eval(symbol))"
  221. @printf(io, "%s\n", var)
  222. end
  223. "--------End of VAR DUMP--------"
  224. end
  225. flush(io)
  226. flush(Base.stdout)
  227. train, validation, test = load_dataset()
  228. if (usegpu)
  229. const train_set = gpu.(train)
  230. const validation_set = gpu.(validation)
  231. const test_set = gpu.(test)
  232. end
  233. if(!runD)
  234. results = random_search()
  235. BSON.@save "results.bson" results
  236. #TODO sort and print best 5-10 results
  237. else train_model() end