net_2stage.jl 9.7 KB

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