forked from ibmua/immortal-flappy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathflap.py
2025 lines (1693 loc) · 52.9 KB
/
flap.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from traceback import print_exc
import os
import shutil
import errno
from multiprocessing import Pool
import string
import random
import numpy as np
import sys
sys.path.append("game/")
import skimage
from skimage import transform, color, exposure
from skimage.color import rgb2hsv
import keras
from keras import regularizers
from keras.models import Sequential, Model
from keras.layers import Dense, Flatten, Activation, Input
from keras.layers import Conv2D, Conv2DTranspose, UpSampling2D , MaxPooling2D , MaxPooling1D , AveragePooling2D , MaxoutDense , Average , Reshape , GlobalAveragePooling1D , Activation , Add , Lambda , BatchNormalization , Conv3D
from keras.optimizers import RMSprop , Nadam , SGD
import keras.backend as K
# from keras.backend import pool2d
from keras.callbacks import LearningRateScheduler, History
import tensorflow as tf
import pygame
import wrapped_flappy_bird as game
import threading
from threading import Thread
import time
import math
from keras.callbacks import TensorBoard
import pydot
from keras.utils import plot_model
def rnd_String():
return ''.join (
random.choice (
string.ascii_uppercase
+ string.digits
) for _ in range(5)
)
shutil.copy( 'flap.py' , 'history/' + rnd_String() + '.py')
class color:
'''color class:
reset all color with color.reset
two subclasses fg for foreground and bg for background.
use as color.subclass.colorname.
i.e. color.fg.red or color.bg.green
also, the generic bold, disable, underline, reverse, strikethrough,
and invisible work with the main class
i.e. color.bold
'''
reset='\033[0m'
bold='\033[01m'
disable='\033[02m'
underline='\033[04m'
reverse='\033[07m'
strikethrough='\033[09m'
invisible='\033[08m'
class bg:
black='\033[40m'
red='\033[41m'
green='\033[42m'
orange='\033[43m'
blue='\033[44m'
purple='\033[45m'
cyan='\033[46m'
lightgrey='\033[47m'
class fg:
black='\033[30m'
red='\033[31m'
green='\033[32m'
orange='\033[33m'
blue='\033[34m'
purple='\033[35m'
cyan='\033[36m'
lightgrey='\033[37m'
darkgrey='\033[90m'
lightred='\033[91m'
lightgreen='\033[92m'
yellow='\033[93m'
lightblue='\033[94m'
pink='\033[95m'
lightcyan='\033[96m'
# from resnet import ResnetBuilder
rnd_name = ''.join (
random.choice (
string.ascii_uppercase
+ string.digits
) for _ in range(4)
)
from keras.backend.tensorflow_backend import set_session
config = tf.ConfigProto()
# config.gpu_options.per_process_gpu_memory_fraction = 0.9
config.gpu_options.per_process_gpu_memory_fraction = 0.6
set_session( tf.Session(config=config) )
game_state = game.GameState()
frame,__,__ = game_state.frame_step( [1,0] )
# frame = frame[ 58: -70 + 16 ]
# frame = frame[ 58: -70 ] # some parts of our view are irrelevant
# frame = frame[ : , 1 ] - frame[ : , 0 ] # combine into a single channel without loosing clarity on colors
# frame = np.delete(frame , [1,2] , axis=2) # we don't need blue
# frame = frame[ 57: -71 ]
# frame = frame[ 56: ]
# frame = frame[ 58: -70 ]
frame = frame[ 58: -70 -4*8 ]
STATE_CHANNELS = 4
x,y,_ = frame.shape #-> x 400
# RES_HORIZONTAL = x
# RES_VERTICAL = y
RES_HORIZONTAL = x / 4 / 1 # pipes move 4 pixels per frame
RES_VERTICAL = y / 2 / 1 # -> 200 # the bird moves vertically, 10 when jumping
# Seems like if it doesn't just stall,
# minimum movement is 2 and at least generally
# with any movement %2 == 0
# Also, everything is painted in pixel-art style
print RES_HORIZONTAL , '*' , RES_VERTICAL
# batch_size = 128
frame_mean = -100000 # if you want to compute it on the first loaded batch
frame_st_deviation = -100000 # if you want to compute it on the first loaded batch
# frame_mean = 0.571706774615 # values that my flawless net got trained with based on its first batch
# frame_st_deviation = 1.0674802648 # values that my flawless net got trained with based on its first batch
def preprocess( frame ):
global RES_HORIZONTAL
global RES_VERTICAL
global STATE_CHANNELS
global adjust_mean_and_variation
# Colors inside frame are fucked up like this:
#
# frame = frame[ 58: -70 ] # some parts of our view are irrelevant
frame = frame[ 58: -70 -4*8 ] # some parts of our view are irrelevant
frame = skimage.transform.resize(
frame
, (RES_HORIZONTAL , RES_VERTICAL)
, mode='constant'
)
# frame = np.delete(frame , [1,2] , axis=2) # red only
# frame = np.delete(frame , [0,2] , axis=2) # green only
if STATE_CHANNELS == 4:
frame = np.delete(frame , [2] , axis=2) # we don't need blue
elif STATE_CHANNELS == 2:
frame[ : , : , 0 ] -= frame[ : , : , 1 ] # combine into a single channel without loosing clarity on colors
frame = np.delete(frame , [1,2] , axis=2) # we don't need blue
frame *= 4 # This is probably unnecessary, but that's something I did for historical (of code) reasons.
# If STATE_CHANNELS == 2 then variance should get up, closer to 1, which might be good.
# Best practice known to me from supervised learning on images:
# variance -> 1, mean value -> 0.
# We're getting closer to this, I think (if STATE_CHANNELS == 2).
# But I can't say for a fact if it does make a difference for better.
frame = frame.reshape( 1 , RES_HORIZONTAL , RES_VERTICAL , STATE_CHANNELS / 2 )
if adjust_mean_and_variation:
frame -= frame_mean
frame *= 1 / frame_st_deviation
return np.float16( frame )
batch_size = 64
# batch_size = 256
# batch_size = 128
maximum_loss_threshold = 0.001
random_move_amount = 0
random_moves_till_filled_to = batch_size * 16 # Random probably gives good data,
# but the chance of passing pipes with random
minimum_frame_amount_requirement_for_inclusion = 20 # is so low that we can only afford it at the beginning.
minimum_frame_amount_requirement_for_inclusion_later_on = 30 # - Set after random batch is collected - upon first recall
number_of_trashy_last_frames_for_starters = 35 # There's around 37 frames pipe start -to- pipe start
number_of_trashy_last_frames_later_on = 37 # Set after first recall
max_frames_per_run = 1024 * 2
memory_capacity = 4096 * 10
# memory_capacity = 8192 * 1
make_alternative_net = False # sucked extremely hard for some reason
# per_exp_load_training_epochs = 1
# per_exp_load_training_epochs = 10
# training_on_files_decay_rate = .97
"""The following values are changed later in the IF code below"""
# loading memories
how_many_times_to_cycle_training_data = 1
per_exp_load_training_epochs = 1
epochs_during_first_recall_training = 10
total_recall_every_n_lives = 10
max_times_trained_since_starting_loop = 1
rnd_chance_multiplied_by = 1.
disable_exploration = False
i_demand_silence = False
dont_store_data = False
reset_n_retrain_if_failed = False
model_to_load = False
use_deterministic_action = False
do_train_on_directory = False
adjust_mean_and_variation = False
never_recall = False
LEARNING_RATE = .1
l2 = .0001
lr_decay_rate = .9995
min_rnd_chance = 0.00
preset = 'No preset chosen.'
preset = 'gather'
# preset = 'train_on_stored_data_and_gather'
# preset = 'train_on_data'
# preset = 'load_model_and_gather' # not implemented yet
# preset = 'load_model_and_test'
print bg.green , preset , color.reset
if (
preset == 'gather'
or
preset == 'train_on_stored_data_and_gather'
):
rnd_chance_multiplied_by = .3 # random will probably give the best data, so failing fast is not a problem,
min_rnd_chance = 0.02 # it's probably worth the extra diversity of data obtained
l2 = 0.0001
lr_decay_rate = .998
# recall
epochs_during_first_recall_training = 10
total_recall_every_n_lives = 500
max_times_trained_since_starting_loop = 1
# i_demand_silence = True
if preset == 'train_on_stored_data_and_gather':
# load data and explore with a bot based on that data
disable_exploration = True
do_train_on_directory = True
# never_recall = True
# lr_decay_rate = .95
lr_decay_rate = .992
epochs_during_first_recall_training = 1
how_many_times_to_cycle_training_data = 1
per_exp_load_training_epochs = 1
elif(
preset == 'train_on_data'
):
# loading memories
how_many_times_to_cycle_training_data = 2
per_exp_load_training_epochs = 1
l2 = 0.0001
# l2 = 0.00002
# lr_decay_rate = .975
lr_decay_rate = .95
# adjust_mean_and_variation = True
never_recall = True
disable_exploration = True
use_deterministic_action = True
dont_store_data = True
do_train_on_directory = True
i_demand_silence = True
reset_n_retrain_if_failed = True
elif(
preset == 'load_model_and_test'
):
# loading a network
# adjust_mean_and_variation = True
never_recall = True
disable_exploration = True
use_deterministic_action = True
dont_store_data = True
i_demand_silence = True
model_to_load = \
'immortal-models/' \
+ 'one' #flawless
data_load_folder = 'data-step-1/'
data_save_folder = 'data-step-1/'
# optimizer = Nadam(lr = LEARNING_RATE)
optimizer = SGD(lr = LEARNING_RATE)
# optimizer = SGD(lr = LEARNING_RATE , momentum = 0.9)
# optimizer = SGD(lr = LEARNING_RATE , momentum = 0.9 , nesterov = True)
# optimizer = RMSprop(lr = LEARNING_RATE)
# optimizer = RMSprop(lr = LEARNING_RATE, rho = 0.9, epsilon = 0.1)
loss_name = 'binary_crossentropy'
# loss_name = 'mean_squared_error'
kernel_init_type = 'orthogonal'
bias_initializer_type = 'zeros'
# + 'RERUNS_batch_sizeX16_' \
model_name =\
preset \
+ '_rg_x4_2_' + str(random_moves_till_filled_to) + '_' \
+ str(RES_HORIZONTAL) + 'x' + str(RES_VERTICAL) + 'x' + str(STATE_CHANNELS) \
+ 'flap_' + str(batch_size) + '_' \
+ 'rnd' + str(rnd_chance_multiplied_by) +'_' \
+ 'D128_last' \
+ str( per_exp_load_training_epochs ) \
+ '_' \
+ str( l2 ) \
+ '_' \
+ str( total_recall_every_n_lives ) \
+ '_' \
+ str( lr_decay_rate ) \
+ rnd_name \
+ str( LEARNING_RATE ) \
+ loss_name \
+ str(batch_size) \
+ str(config.gpu_options.per_process_gpu_memory_fraction)
if (
not os.path.isdir( data_load_folder )
and
do_train_on_directory
):
print data_load_folder , "doesn't exist. Mount the volume, or something else, maybe?"
sys.exit(0)
if (
not os.path.isdir( data_save_folder )
and
not dont_store_data
):
print data_save_folder , "doesn't exist. Mount the volume, or something else, maybe?"
sys.exit(0)
total_recall_last_final_times_trained = -10000
total_recall_index = 0
times_trained = 0
times_trained_experiment_net = 0
F = 0
memory_slots_filled = 0
memory_append_index = 0
sequences_in_file = 0
np.set_printoptions(precision=3)
seed_iterator = 1
def load_Exp(
states
, outs
, directory
):
global seed_iterator
start = time.time()
print bg.blue , 'Loading memories'
print fg.black, states
print outs , color.reset
# I don't want to load experiences from several processes concurrently
lock_path = directory + '/lock'
if os.path.exists( lock_path ):
print bg.red , 'Storage locked, waiting.' , color.reset
while os.path.exists( lock_path ):
time.sleep(0.1)
print bg.green , 'Storage unlocked' , color.reset
file( lock_path , 'w').close()
# print 'reading arrays'
i = np.load( states , allow_pickle=False)
o = np.load( outs , allow_pickle=False)
# o = np.delete( o , [1] , axis = 1 )
# o.shape = ( len(o) )
# i = np.delete( i , [1,2] , axis = 3 )
# print 'read arrays in' , time.time() - start
# np.random.seed( seed_iterator )
# i = np.random.permutation( i )
# np.random.seed( seed_iterator )
# o = np.random.permutation( o )
# i = np.float64( i )
# o = np.float64( o )
seed_iterator += 1
silent_Remove( lock_path )
global frame_mean
global frame_st_deviation
if (
adjust_mean_and_variation
and
frame_mean < -1000
):
frame_mean = i.mean ( dtype=np.float64 )
frame_st_deviation = i.std ( dtype=np.float64 )
print bg.purple , frame_mean , 'mean' , frame_st_deviation , 'st. deviation' , color.reset
if adjust_mean_and_variation:
i -= frame_mean
i *= 1 / frame_st_deviation
print bg.blue , 'Loaded' , len(i) , 'in' , time.time() - start , color.reset
return i , o
def silent_Remove(filename):
try:
os.remove(filename)
except OSError as e: # this would be "except OSError, e:" before Python 2.6
if e.errno != errno.ENOENT: # errno.ENOENT = no such file or directory
raise # re-raise exception if a different error occurred
class Thread_with_Return(Thread):
def __init__(self, group=None, target=None, name=None,
args=(), kwargs={}, Verbose=None):
Thread.__init__(self, group, target, name, args, kwargs, Verbose)
self._return = None
def run(self):
if self._Thread__target is not None:
self._return = self._Thread__target(*self._Thread__args,
**self._Thread__kwargs)
def join(self):
Thread.join(self)
return self._return
def lr_Decay_Function(epoch):
global lr_decay_rate
lrate = LEARNING_RATE * lr_decay_rate ** epoch
lrate = math.fabs(lrate)
return max (
lrate
, 0.0001
)
input_File_Decay = lr_Decay_Function
# def input_File_Decay( epoch ):
# global LR
# global lr_decay_rate
#
# # print LEARNING_RATE , 'LEARNING_RATE'
# # print lr_decay_rate , 'lr_decay_rate'
# # print epoch , 'epoch'
#
# lrate = LEARNING_RATE * lr_decay_rate ** epoch
# lrate = math.fabs(lrate)
# return lrate
def set_Exp (
states
, outputs
):
global positive_memories_states
global positive_memories_outputs
global memory_slots_filled
global memory_append_index
global total_recall_mode
global random_move_amount
global memory_capacity
random_move_amount = 0
positive_memories_states = states
positive_memories_outputs = outputs
memory_append_index = 0
memory_capacity = len( positive_memories_states )
memory_slots_filled = len( positive_memories_states )
total_recall_mode = True
print bg.blue , 'Set' , memory_slots_filled , 'memories' , color.reset
def train_Model (
model
, initial_epoch
, input_file_epochs
, data_states
, data_outs
, LR = 0.1
# , decay = 0.98
):
global batch_size
global lr_decay_rate
decay = lr_decay_rate
start = time.time()
how_many_samples = len (
data_states
)
how_many_samples -= how_many_samples % batch_size # we don't want to risk having a tiny batch
model.fit (
data_states [ : how_many_samples ]
, [
data_outs [ : how_many_samples ]
]
, initial_epoch = initial_epoch
, epochs = initial_epoch + input_file_epochs
, batch_size = batch_size
, callbacks = [
LearningRateScheduler( input_File_Decay )
]
)
print bg.green , time.time() - start , color.reset
def list_Files (
foldername
, suffix = ".npy"
, fulldir = True
):
file_list_tmp = os.listdir(foldername)
# print len(file_list_tmp)
# print file_list_tmp
file_list = []
if fulldir:
for item in file_list_tmp:
if item.endswith(suffix):
# print item , 'endswith'
file_list.append(os.path.join(foldername, item))
else:
for item in file_list_tmp:
if item.endswith(suffix):
file_list.append(item)
return file_list
def train_On_Files (
input_files
, output_files
, directory
, input_file_epochs = 5
, per_load_epochs = 10
, lr = 0.1
# , decay_rate = 0.995
):
global positive_memories_states
global positive_memories_outputs
global memory_slots_filled
global memory_append_index
global decision_only_model
# global decision_only_model
# global nn_model
global model_name
# print input_files
# loaded_states = False
# loaded_outputs = False
#
# loading_thread = False
first_run = True
training_epoch = 0
input_files_new = input_files [:]
output_files_new = output_files[:]
for i in range( 1 , input_file_epochs ):
input_files_new.extend ( input_files )
output_files_new.extend ( output_files )
input_files = input_files_new
output_files = output_files_new
input_file = input_files [0]
output_file = output_files[0]
loading_thread = Thread_with_Return (
target = load_Exp
, args = (
input_file
, output_file
, directory
)
)
loading_thread.start()
plot_model (
decision_only_model
,
show_shapes = True
,
to_file = (
"saved-models/decision_model-training-"
+ model_name
+ '.png'
)
)
for i in range( 0 , len(input_files) ):
loaded_states , loaded_outputs = loading_thread.join()
set_Exp (
loaded_states
, loaded_outputs
)
if ( # if not last
i
< len( input_files ) -1
):
input_file = input_files [ i + 1 ]
output_file = output_files[ i + 1 ]
loading_thread = Thread_with_Return (
target = load_Exp
, args = (
input_file
, output_file
, directory
)
)
loading_thread.start()
train_Model (
decision_only_model
, training_epoch
, per_load_epochs
, positive_memories_states [ : memory_slots_filled ]
, positive_memories_outputs [ : memory_slots_filled ]
, lr
)
training_epoch += per_load_epochs
decision_only_model.save (
"saved-models/decision_model-training-"
+ str(lr)
+ model_name
)
print 'Stored model as saved-models/training-' + str(lr) + model_name
memory_append_index = 0
def train_On_Directory (
directory
, epochs = 1
, sub_epochs = 1
):
print directory
silent_Remove( directory + '/lock')
data_states = sorted (
list_Files (
directory
, 'states.npy'
)
)
# print data_states
data_outputs= sorted (
list_Files (
directory
, 'outputs.npy'
)
)
train_On_Files (
data_states
, data_outputs
, directory
, epochs
, sub_epochs
)
def load_Model( path ):
model = keras.models.load_model(path)
plot_model (
model
,
show_shapes = True
,
to_file = (
'loaded-model.png'
)
)
print 'Saved visualization in loaded-model.png'
return model
def BN( x ):
return BatchNormalization( momentum=0.91 ) (x)
def CONV(
x
, y = (3,3)
, pad = True
):
return Conv2D (
x
# * 2
, kernel_size = y
, strides = (1,1)
, activation = 'relu'
, bias_initializer = bias_initializer_type
, kernel_initializer = kernel_init_type
, kernel_regularizer = regularizers.l2( l2 )
, padding = 'same' if pad else 'valid'
)
def CONV3(
x
, y = (3,3,1)
, z = (1,1,1)
, pad = True
):
return Conv3D (
x
, kernel_size = y
, strides = z
, activation = 'relu'
, bias_initializer = bias_initializer_type
, kernel_initializer = kernel_init_type
, kernel_regularizer = regularizers.l2( l2 )
, padding = 'same' if pad else 'valid'
)
def MAX_POOL( x ):
return MaxPooling2D(
pool_size = (2 , 2)
, strides = (2 , 2)
, padding = 'same'
# , data_format = None
) (x)
def build_Model():
print("Model buliding begins")
# keras.initializers.RandomUniform(minval=-0.1, maxval=0.1, seed=None)
S = Input(shape = (RES_HORIZONTAL, RES_VERTICAL, STATE_CHANNELS, ), name = 'Input')
# S1 = MaxPooling2D(
#
# pool_size=(2, 2), strides=(2,2)
# # pool_size=(4, 4), strides=(4,4)
# , padding='same', data_format=None
# ) (S)
# h0 = AveragePooling2D(
# h0 = MaxPooling2D(
#
# pool_size=(2, 2), strides=(2,2)
# # pool_size=(4, 4), strides=(4,4)
# , padding='same', data_format=None
# ) (S)
# flat = ResnetBuilder.build_resnet_18( (STATE_CHANNELS, RES_HORIZONTAL, RES_VERTICAL, ), S)
global make_alternative_net
global l2
if make_alternative_net:
# flat = ResnetBuilder.build(
# (STATE_CHANNELS, RES_HORIZONTAL, RES_VERTICAL, )
# , S
# , 'basic_block'
# , [1, 2, 2]
# )
pass # your model here
else:
# (input_shape, input_layer, basic_block, [2, 2, 2, 2])
#
# 40 x 200
# PC = BN ( S )
PC = CONV (
8
) ( S )
# ) ( PC )
# PC = Reshape (
# (
# RES_HORIZONTAL
# , RES_VERTICAL
# , 2
# , STATE_CHANNELS/2
# )
# ) ( S )
# # ) ( PC )
# PC = CONV3 (
# 8
# , (3,3,1)
# , (1,1,1)
# ) ( PC )
#
# PC = Reshape (
# (
# RES_HORIZONTAL
# , RES_VERTICAL
# , 16#-1
# )
# ) ( PC )
PC = MAX_POOL ( PC )
PC = BN ( PC )
# /2
PC = CONV (
16
) ( PC )
PC = MAX_POOL ( PC )
PC = BN ( PC )
# /4
PC = CONV (
16
) ( PC )
PC = MAX_POOL ( PC )
PC = BN ( PC )
# /8
PC = CONV (
32
) ( PC )
PC = MAX_POOL ( PC )
PC = BN ( PC )
# /16
PC = CONV (
64
, (2,3)
# , pad = False
) ( PC )
PC = MAX_POOL ( PC )
# /32
PC = BN ( PC )
PC = CONV (
128
, (1,3)
) ( PC )
PC = MAX_POOL ( PC )
# /64
# 1 x 5 -> 1 x 3 -> 1x1
P = Flatten() ( PC )
P = BN ( P )
P = Dense (
128
, activation = 'relu'
, kernel_initializer = kernel_init_type
, kernel_regularizer = regularizers.l2( l2 )
, bias_initializer = bias_initializer_type
) (P)
P = BN ( P )
P = Dense (
1
, name = 'models_decision'
, activation = 'sigmoid'
, kernel_initializer = kernel_init_type
, kernel_regularizer = regularizers.l2( l2 )
, bias_initializer = bias_initializer_type
) (P)
SE = Input(shape = (RES_HORIZONTAL, RES_VERTICAL, STATE_CHANNELS, ), name = 'Input')
# probability that we should explore random instead of relying on our answer/prediction
E = AveragePooling2D(
pool_size=(2, 1), strides=(2,1)
, padding='same', data_format=None
# ) (S1)
) (SE)
# E = BN ( E )
# /2
E = CONV (
8
) ( E )
E = MAX_POOL ( E )
E = BN ( E )
E = CONV (
8
) ( E )
E = MAX_POOL ( E )
E = BN ( E )
E = CONV (
16
) ( E )
E = MAX_POOL ( E )
E = BN ( E )
# E = CONV (
# 16
# , (2,3)
# ) ( E )
# E = MAX_POOL ( E )
# E = BN ( E )
E = Flatten() (E)
# E = MaxoutDense( 32, nb_feature=2, init=kernel_init_type, bias=True ) (E)
E = Dense (
16
, activation = 'relu'
, kernel_initializer = kernel_init_type
, bias_initializer = bias_initializer_type
) (E)
E = BN ( E )
E = Dense (
1
, name = 'exploration_neuron'
, activation = 'sigmoid'
, kernel_initializer = kernel_init_type
, bias_initializer = bias_initializer_type
) (E)
decision_only_model = Model (
inputs = S
, outputs = [
P
]
)
experiment_only_model = Model (
inputs = SE
, outputs = [
E
]
)
global optimizer
decision_only_model.compile (
loss = {
'models_decision' : loss_name
}
, optimizer = optimizer
)