net_2stage.jl 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  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 = 100
  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.99f0
  49. const lambda = 0.0005f0
  50. const delta = 6e-8
  51. learning_rate = 0.003f0
  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 = 1
  58. const time_format = "HH:MM:SS"
  59. const time_print_format = "HH_MM_SS"
  60. const date_format = "dd_mm_yyyy"
  61. data_size = (60, 6) # resulting in a 300ms frame
  62. # ARCHITECTURE
  63. channels = 1
  64. features = [32, 64, 128] # needs to find the relation between the axis which represents the screen position
  65. kernel = [(5,1), (5,1), (2,6)] # convolute only horizontally, last should convolute all 6 rows together to map relations between the channels
  66. pooldims = [(3,1), (3,1)]# (30,6) -> (15,6)
  67. # formula for calculating output dimensions of convolution:
  68. # dim1 = ((dim1 - Filtersize + 2 * padding) / stride) + 1
  69. inputDense = [0, 600, 300]
  70. dropout_rate = 0.3f0
  71. rs_learning_rate = [0.03, 0.01, 0.003] # [1, 0.3, 0.1, 0.03, 0.01, 0.003, 0.001]
  72. rs_decay_step = [20, 40, 60]
  73. dataset_folderpath = "../MATLAB/TrainingData/"
  74. dataset_name = "2019_09_09_1658"
  75. const model_save_location = "../trainedModels/"
  76. const log_save_location = "./logs/"
  77. if usegpu
  78. using CuArrays
  79. end
  80. debug_str = ""
  81. log_msg = parsed_args["logmsg"]
  82. csv_out = parsed_args["csv"]
  83. runD = parsed_args["runD"]
  84. io = nothing
  85. io_csv = nothing
  86. @debug begin
  87. global debug_str
  88. debug_str = "DEBUG_"
  89. "------DEBUGGING ACTIVATED------"
  90. end
  91. function adapt_learnrate(epoch_idx)
  92. return learning_rate * decay_rate^(epoch_idx / decay_step)
  93. end
  94. # TODO different idea for the accuracy: draw circle around ground truth and if prediction lays within the circle count this as a hit
  95. # TODO calculate the mean distance in pixel without normalizantion
  96. function accuracy(model, x, y)
  97. y_hat = Tracker.data(model(x))
  98. return mean(mapslices(button_number, y_hat, dims=1) .== mapslices(button_number, y, dims=1))
  99. end
  100. function accuracy(model, dataset)
  101. acc = 0.0f0
  102. for (data, labels) in dataset
  103. acc += accuracy(model, data, labels)
  104. end
  105. return acc / length(dataset)
  106. end
  107. function button_number(X)
  108. return (X[1] * 1080) ÷ 360 + 3 * ((X[2] * 980) ÷ 245)
  109. end
  110. function loss(model, x, y)
  111. # quadratic euclidean distance + parameternorm
  112. return Flux.mse(model(x), y) + lambda * sum(norm, params(model))
  113. end
  114. function loss(model, dataset)
  115. loss_val = 0.0f0
  116. for (data, labels) in dataset
  117. loss_val += Tracker.data(loss(model, data, labels))
  118. end
  119. return loss_val / length(dataset)
  120. end
  121. function load_dataset()
  122. train = make_batch(dataset_folderpath, "$(dataset_name)_TRAIN.mat", normalize_data=false, truncate_data=false)
  123. val = make_batch(dataset_folderpath, "$(dataset_name)_VAL.mat", normalize_data=false, truncate_data=false)
  124. test = make_batch(dataset_folderpath, "$(dataset_name)_TEST.mat", normalize_data=false, truncate_data=false)
  125. return (train, val, test)
  126. end
  127. function create_model()
  128. return Chain(
  129. Conv(kernel[1], channels=>features[1], relu, pad=map(x -> x ÷ 2, kernel[1])),
  130. MaxPool(pooldims[1], stride=pooldims[1]),
  131. Conv(kernel[2], features[1]=>features[2], relu, pad=map(x -> x ÷ 2, kernel[2])),
  132. MaxPool(pooldims[2], stride=pooldims[2]),
  133. Conv(kernel[3], features[2]=>features[3], relu),
  134. # MaxPool(),
  135. flatten,
  136. Dense(prod((data_size .÷ pooldims[1] .÷ pooldims[2]) .- kernel[3] .+ 1) * features[3], inputDense[2], relu),
  137. Dropout(dropout_rate),
  138. Dense(inputDense[2], inputDense[3], relu),
  139. Dropout(dropout_rate),
  140. Dense(inputDense[3], 2, σ), # coordinates between 0 and 1
  141. )
  142. end
  143. function log(model, epoch, use_testset)
  144. Flux.testmode!(model, true)
  145. if(epoch == 0) # evalutation phase
  146. if(use_testset) @printf(io, "[%s] INIT Loss(test): %f Accuarcy: %f\n", Dates.format(now(), time_format), loss(model, test_set), accuracy(model, test_set))
  147. else @printf(io, "[%s] INIT Loss(val): %f Accuarcy: %f\n", Dates.format(now(), time_format), loss(model, validation_set), accuracy(model, validation_set)) end
  148. elseif(epoch == epochs)
  149. @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))
  150. if(use_testset)
  151. @printf(io, "[%s] FINAL(%d) Loss(test): %f Accuarcy: %f\n", Dates.format(now(), time_format), epoch, loss(model, test_set), accuracy(model, test_set))
  152. else
  153. @printf(io, "[%s] FINAL(%d) Loss(val): %f Accuarcy: %f\n", Dates.format(now(), time_format), epoch, loss(model, validation_set), accuracy(model, validation_set))
  154. end
  155. else # learning phase
  156. if (rem(epoch, printout_interval) == 0)
  157. @printf(io, "[%s] Epoch %3d: Loss(train): %f Loss(val): %f acc(val): %f\n", Dates.format(now(), time_format), epoch, loss(model, train_set), loss(model, validation_set), accuracy(model, validation_set))
  158. end
  159. end
  160. Flux.testmode!(model, false)
  161. end
  162. function log_csv(model, epoch)
  163. Flux.testmode!(model, true)
  164. if(csv_out) @printf(io_csv, "%d, %f, %f\n", epoch, loss(model, train_set), loss(model, validation_set)) end
  165. Flux.testmode!(model, false)
  166. end
  167. function eval_model(model)
  168. Flux.testmode!(model, true)
  169. if (validate) return (loss(model, validation_set), accuracy(model, validation_set))
  170. else return (loss(model, test_set), accuracy(model, test_set)) end
  171. end
  172. function train_model()
  173. model = create_model()
  174. if (usegpu) model = gpu(model) end
  175. opt = Momentum(learning_rate, momentum)
  176. log(model, 0, !validate)
  177. Flux.testmode!(model, false) # bring model in training mode
  178. last_loss_train = loss(model, train_set)
  179. last_loss_val = loss(model, validation_set)
  180. overfitting_epochs = 0
  181. converged_epochs = 0
  182. for i in 1:epochs
  183. flush(io)
  184. Flux.train!((x, y) -> loss(model, x, y), params(model), train_set, opt)
  185. opt.eta = adapt_learnrate(i)
  186. log_csv(model, i)
  187. log(model, i, !validate)
  188. # stop if network converged or is showing signs of overfitting
  189. #curr_loss_train = Tracker.data(loss(model, train_set))
  190. #curr_loss_val = Tracker.data(loss(model, validation_set))
  191. #if(abs(last_loss_train - curr_loss_train) < delta)
  192. # converged_epochs += 1
  193. # # @show converged_epochs
  194. # if(converged_epochs == 8)
  195. # @printf(io, "Converged at Loss(train): %f, Loss(val): %f in epoch %d with accuracy(val): %f\n", curr_loss_train, curr_loss_val, i, accuracy(model, validation_set))
  196. # return eval_model(model)
  197. # end
  198. #else
  199. # # @show "reset convereged $(abs(last_loss_train - curr_loss_train)) $(abs(last_loss_train - curr_loss_train) < delta)"
  200. # converged_epochs = 0
  201. #end
  202. #
  203. #if((curr_loss_val - last_loss_val) > 0 )
  204. # overfitting_epochs += 1
  205. # if(overfitting_epochs == 10)
  206. # @printf(io, "Stopping before overfitting at Loss(train): %f, Loss(val): %f in epoch %d with accuracy(val): %f\n", curr_loss_train, curr_loss_val, i, accuracy(model, validation_set))
  207. # return eval(model)
  208. # end
  209. #else
  210. # overfitting_epochs = 0
  211. #end
  212. #last_loss_train = curr_loss_train
  213. #last_loss_val = curr_loss_val
  214. end
  215. return eval_model(model)
  216. end
  217. # logging framework
  218. fp = "$(log_save_location)$(debug_str)log_$(Dates.format(now(), date_format)).log"
  219. io = open(fp, "a+")
  220. global_logger(SimpleLogger(io)) # for debug outputs
  221. @printf(Base.stdout, "Logging to File: %s\n", fp)
  222. @printf(io, "\n--------[%s %s]--------\n", Dates.format(now(), date_format), Dates.format(now(), time_format))
  223. @printf(io, "%s\n", log_msg)
  224. # csv handling
  225. if (csv_out)
  226. fp_csv = "$(log_save_location)$(debug_str)csv_$(Dates.format(now(), date_format))_$(Dates.format(now(), time_print_format)).csv"
  227. io_csv = open(fp_csv, "w+") # read, write, create, truncate
  228. @printf(io_csv, "epoch, loss(train), loss(val)\n")
  229. end
  230. # dump configuration
  231. @debug begin
  232. for symbol in names(Main)
  233. var = "$(symbol) = $(eval(symbol))"
  234. @printf(io, "%s\n", var)
  235. end
  236. "--------End of VAR DUMP--------"
  237. end
  238. flush(io)
  239. flush(Base.stdout)
  240. train, validation, test = load_dataset()
  241. if (usegpu)
  242. const train_set = gpu.(train)
  243. const validation_set = gpu.(validation)
  244. const test_set = gpu.(test)
  245. end
  246. for rate in rs_learning_rate
  247. learning_rate = rate
  248. for decay in rs_decay_step
  249. decay_step = decay
  250. config = "learning_rate=$(learning_rate), decay_step=$(decay_step)"
  251. @printf(io, "\nConfiguration %s\n", config)
  252. train_model()
  253. end
  254. end