Example #1
0
def main(*args, **kwargs):
    inputs = Inputs()
    config = Config()
    with tf.variable_scope("inference") as scope:
        m = TextCNN(config, inputs)
        scope.reuse_variables()
        mvalid = TextCNN(Config, inputs)

    init = tf.group(tf.initialize_all_variables(),
                    tf.initialize_local_variables())
    sess = tf.Session()
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(sess=sess, coord=coord)
    sess.run(init)
    try:
        index = 0
        while not coord.should_stop():
            _, loss_value = sess.run([m.train_op, m.cost])
            index += 1
            print("step: %d, loss: %f" % (index, loss_value))
            if index % 5 == 0:
                accuracy = sess.run(mvalid.validation_op)
                print("accuracy on validation is:" + str(accuracy))
    except tf.errors.OutOfRangeError:
        print("Done traing:-------Epoch limit reached")
    except KeyboardInterrupt:
        print("keyboard interrput detected, stop training")
    finally:
        coord.request_stop()
    coord.join(threads)
    sess.close()
    del sess
Example #2
0
def main(*args, **kwargs):
    inputs = Inputs()
    print ('inputs shape: %s'%str(inputs.inputs.shape))
    config = Config()
    with tf.variable_scope('inference') as scope:
        m = TextCNN(config, inputs)
        scope.reuse_variables()

    init = tf.group(tf.global_variables_initializer(),
                    tf.local_variables_initializer())
    sess = tf.Session()
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(sess=sess, coord=coord)
    sess.run(init)

    try:
        index = 0
        while not coord.should_stop() and index<1:
            _, loss_value = sess.run([m.train_op, m.cost])
            index += 1
            print ('step: %d, loss: %f'%(index,loss_value))
    except tf.errors.OutOfRangeError:
        print ('Done trainingļ¼š -----Epoch limit reached')
    except KeyboardInterrupt:
        print ('keyboard interrput detected, stop training')
    finally:
        coord.request_stop()
    coord.join(threads)
    sess.close()
    del sess
Example #3
0
    def __init__(self, init_state='menu'):
        # Init pygame
        pygame.init()

        # Get clock
        self.clock = pygame.time.Clock()

        # Create screen
        self.__screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))

        # Main app font
        self.font = pygame.font.SysFont("Arial", 16, False, False)

        # Input pipeline (instance gets replaced by each state init())
        self.inputs = Inputs()

        # Persistent data dictionary, for data to persist across state change
        self.__data = {}

        # Current state
        self.__state = None
        # Next state name
        self.__next_state = init_state

        # Main game loop escape bool
        self.running = True
Example #4
0
	def __init__(self, heading, position, load_image=True):

		self.heading = copy.deepcopy(heading) # angle in radians
		self.position = copy.deepcopy(position) # metres worlds coords
		self.velocity = Vector2() # m/s world coords
		self.velocity_c = Vector2() # m/s local coords, x is forward, y is sideways
		self.accel = Vector2() # acceleration in world coords
		self.accel_c = Vector2() # acceleration in local coords
		self.absVel = 0. # absolute velocity m/s
		self.yawRate = 0. # angular velocity in m/s
		self.steer = 0. # amount of steering input (-1.0 .. 1.0)
		self.steerAngle = 0. # actual front whell steer angle (-maxSteer .. maxSteer)

		self.inertia = 0.
		self.wheelBase = 0. # set from axle to CG lengths
		self.axleWeightRatioFront = 0. # % car weight on the front axle
		self.axleWeightRatioRear = 0. # % car weight on the read axle

		self.config = Config()
		self.setConfig()

		self.inputs = Inputs(init_pygame=load_image)
		if load_image:
			self.image = pygame.image.load(self.config.image_path).convert_alpha()
			self.image = pygame.transform.scale(self.image, (32, 16))
 def setup(self):
     for i in range(self.settings.numberOfSnakes):
         self.FoodArr.append(Food(self.settings))
         self.SnakeArr.append(Snake(self.settings, self.FoodArr[i]))
         self.InputArr.append(
             Inputs(self.settings, self.SnakeArr[i], self.FoodArr[i]))
         self.NNArr.append(NeuralNetwork(self.settings, self.InputArr[i]))
     self.SnakeArr[0].hasBestBrain = True
     self.FoodArr[0].isFoodForBestSnake = True
Example #6
0
def createDataSet(intWidth, intHeight, intPoints):
    listDataSet = []
    for i in range(intPoints):
        x = random.uniform(-intWidth, intWidth)
        y = random.uniform(-intHeight, intHeight)
        # 2 giriş işleme girdiği zaman beklenen cevabın rastgele Ć¼retilmesi
        answer = 0 if y < f(x) else 1

        listDataSet.append(Inputs(x, y, answer))

    return listDataSet
Example #7
0
    def __init__(self, parent=None):
        list = ('ę—§å£ä»¤', 'ę–°å£ä»¤', 'é‡å¤ę–°å£ä»¤')
        Frame.__init__(self, parent)
        self.pack()
        Label(self, font=('Roman', 18), text='重ē½®å£ä»¤').pack()
        setfont = ('Roman', 16, 'normal')
        for e in list:
            passwd = Inputs(e, self)
            self.vars.append(passwd)
            passwd.pack()

        Button(self, text='ē”®å®š', command=self.quit).pack()
Example #8
0
 def __init__(self):
     self.screen = None
     self.inputs = Inputs()
     # The list of components in the scene. Components are drawn in order in
     # the list
     self.background = []
     self.foreground = []
     self.midground = []
     # The scene manager that this scene sits in.
     self.manager = None
     # The settings for the game.
     self.settings = None
Example #9
0
def net_to_input(net):

    inp = Inputs()
    if net[0] < 0:
        inp.brake = -net[0]
    else:
        inp.throttle = net[0]

    if net[1] < 0:
        inp.left = -net[1]
    else:
        inp.right = net[1]
    return inp
Example #10
0
def main():
    # Initializes pygame, window
    pygame.init()
    window = pygame.display.set_mode(
        (globals.SCREEN_WIDTH, globals.SCREEN_HEIGHT))
    input_params = Inputs()
    clock = pygame.time.Clock()
    app = QApplication(sys.argv)
    param_win = Window()
    param_win.show()

    # Polygon to be controlled by arrows
    polygon = Polygon(np.array([800, 500]), 30, 3, 10, (255, 255, 255))
    space = Space(polygon)
    while globals.RUN:
        # Drawing shapes
        space.draw(window)
        # Adding force to main polygon
        if input_params.is_left():
            polygon.add_force(np.array([-globals.KEY_FORCE, 0.]))
        elif input_params.is_right():
            polygon.add_force(np.array([globals.KEY_FORCE, 0.]))
        if input_params.is_up():
            polygon.add_force(np.array([0., -globals.KEY_FORCE]))
        elif input_params.is_down():
            polygon.add_force(np.array([0., globals.KEY_FORCE]))

        # Add shape on left click
        if input_params.mouse_left_click():
            space.add_shape(globals.NEW_SHAPE_TYPE, input_params.mouse_pos,
                            globals.NEW_SHAPE_RADIUS, globals.NEW_SHAPE_MASS,
                            globals.NEW_SHAPE_DEGREE)
        # Remove shape on right click
        if input_params.mouse_right_click():
            space.remove_shape(input_params.mouse_pos)

        if input_params.is_clear():
            space.shapes = []

        clock.tick(globals.FPS)
        elapsed_time = clock.get_time()
        # Update shapes in space class for movement, rotarion...
        space.update(window, elapsed_time)
        # Check for mouse of keyboard click
        input_params.update()
        pygame.display.update()
        pygame.display.set_caption(str(clock.get_fps()))

    sys.exit(app.exec_())
Example #11
0
 def __init__(self, stdscr):
     self.blocks = []
     self.stdscr = stdscr
     self.focus_idx = 0
     self.inputs = Inputs()
     self.inputs.add(0, self.handle_input)
     self.escape_pressed = False
     self.keybinds = {
         'n': self.action_block_up,
         'p': self.action_block_down,
         'O': self.action_block_create_above,
         'o': self.action_block_create_below,
         't': self.action_create_term,
         'e': self.action_create_python,
         'd': self.action_delete
     }
    def imu_callback(self, imu):
        if self.firstImu:
            self.imuPrevTime = imu.time
            self.firstImu = False
            return
        dt = imu.time - self.imuPrevTime
        self.imuPrevTime = imu.time

        ut = Inputs(comp_filter.run(self.baseStates, imu, dt, self.params.kp))
        self.baseStates.update_w_lpf(ut.gyros)
        ft = DynamicModel(ekf.update_dynamic_model(self.belief, ut))
        At = ekf.update_jacobian_A(self.belief, ut)
        Bt = ekf.update_jacobian_B(self.belief, ut)

        ekf.propagate(self.belief, self.params.RProcess, self.params.RInputs,
                      ft, At, Bt, dt)
        self.update_full_state(ut.phi, ut.theta)
Example #13
0
    def inicializar_jogo(self):

        self.ambiente = pygame
        self.ambiente.init()
        self.sprites = Sprites(pygame)
        self.inputs = Inputs(self.ambiente)
        self.clock_soldados_atiradores = self.ambiente.time.get_ticks()
        self.clock_soldados_espada = self.ambiente.time.get_ticks()
        self.clock_corvo = self.ambiente.time.get_ticks()
        self.paused = False
        self.cont_background = 0
        self.width = 1280
        self.height = 768
        self.device_screen = self.ambiente.display.Info()
        print(self.device_screen.current_w)
        self.screen = self.ambiente.display.set_mode([self.width, self.height],
                                                     self.ambiente.FULLSCREEN
                                                     | self.ambiente.DOUBLEBUF)

        self.background_imgs = [self.ambiente.image.load('imagens/mapa/mapa_1.png').convert(), self.ambiente.image.load('imagens/mapa/mapa_2.png').convert(),\
                self.ambiente.image.load('imagens/mapa/mapa_3.png').convert(), self.ambiente.image.load('imagens/mapa/mapa_4.png').convert()]
        self.background_image = self.background_imgs[0]
        self.torre = self.ambiente.image.load(
            'imagens/torre.png').convert_alpha()
        self.indio = Indio(self.ambiente, 3, 1000, 0, 510)
        self.cd = Cooldown(self.ambiente, 20, 490)
        self.barra = Barra(self.ambiente, 10, 650)
        self.lanca = Lanca(self.ambiente, 1, 0, 0, 20, 510, 0, 90)
        self.barreira1 = Barreira(self.ambiente, 2, 400, 300, 'top')
        self.barreira2 = Barreira(self.ambiente, 3, 400, 500, 'bot')
        self.sprites.barreiras.add(self.barreira1, self.barreira2)
        self.sprites.indio.add(self.indio)
        self.sprites.todos_objetos.add(self.sprites.indio, self.barra,
                                       self.sprites.barreiras)
        self.clock_mapa = self.ambiente.time.get_ticks()
        self.time = self.ambiente.time.get_ticks()
        self.seta_menu = Seta(self.ambiente, 350, 200)
        self.menu_background = self.ambiente.image.load(
            'imagens/menu_background.png')
        self.ambiente.font.init()
        self.fonte = self.ambiente.font.SysFont('Comic Sans MS', 30)
        self.screen.blit(self.background_image, [0, 0])
Example #14
0
    def testForModel(self):
        # path_to_tfrecords_file = '/notebooks/dataVolume/workspace/data'
        path_to_tfrecords_file = '/home/amax/Documents/wit/data/train.tfrecords'
        input_ops = Inputs(path_to_tfrecords_file=path_to_tfrecords_file,
                           batch_size=32,
                           shuffle=True,
                           min_queue_examples=5000,
                           num_preprocess_threads=4,
                           num_reader_threads=1)

        images, input_seqs, target_seqs, mask = input_ops.build_batch()

        mymodel = Model(vocab_size=11,
                        mode='train',
                        embedding_size=512,
                        num_lstm_units=128,
                        lstm_dropout_keep_prob=0.7,
                        cnn_drop_rate=0.2,
                        initializer_scale=0.08)

        logits = mymodel.inference(images, input_seqs, mask, state=None)

        total_loss = mymodel.loss(logits, target_seqs)

        Tensors_output = [images, input_seqs, target_seqs, mask, logits]
        Tensors_name = [
            'images', 'input_seqs', 'target_seqs', 'mask', 'logits'
        ]

        expected_shapes = [
            (32, 54, 54, 3),  # [batch_size, image_height, image_width, 3]
            (32, ),  # [batch_size, sequence_length]
            (32, ),  # [batch_size, sequence_length]
            (32, ),  # [batch_size, sequence_length]
            ()
        ]

        self._checkOutputs(Tensors_output, Tensors_name, expected_shapes)
Example #15
0
    def testForBatch_not_shuffle(self):
        # path_to_tfrecords_file = '/notebooks/dataVolume/workspace/data'
        path_to_tfrecords_file = '/home/amax/Documents/wit/data/val.tfrecords'
        input_ops = Inputs(path_to_tfrecords_file=path_to_tfrecords_file,
                           batch_size=128,
                           shuffle=False,
                           min_queue_examples=5000,
                           num_preprocess_threads=4,
                           num_reader_threads=1)

        images, input_seqs, target_seqs, mask = input_ops.build_batch()

        Tensors_output = [images, input_seqs, target_seqs, mask]
        Tensors_name = ['images', 'input_seqs', 'target_seqs', 'mask']

        expected_shapes = [
            (128, 54, 54, 3),  # [batch_size, image_height, image_width, 3]
            (128, ),  # [batch_size, sequence_length]
            (128, ),  # [batch_size, sequence_length]
            (128, )
        ]  # [batch_size, sequence_length]

        self._checkOutputs(Tensors_output, Tensors_name, expected_shapes)
def main():

    pygame.init()
    globals.pygame = pygame  # assign global pygame for other modules to reference
    globals.inputs = Inputs(
        pygame)  # assign global inputs for other modules to reference
    update_display_mode(
    )  # now that the global display properties have been set up, update the display
    clock = pygame.time.Clock()  # clock to tick / manage delta

    entities = []  # contains every object that will be drawn in the game

    entities.append(Entity())  # our testing entity will be the default entity

    loop = True  # for controlling the game loop

    while (loop):
        clock.tick(60)  # tick the clock with a target 60 fps
        globals.window.fill((255, 255, 255))

        globals.inputs.update()  # refresh inputs

        update(entities)  # update all entities
        render(entities)  # draw all entities

        if (globals.inputs.isKeyDown("space")):
            toggle_fullscreen()  # space bar toggles fullscreen
        if (globals.inputs.isKeyDown("escape")):
            loop = False  # escape key exits game
        if (globals.inputs.isQuitPressed()):
            loop = False  # red 'x' button exits game

        pygame.display.flip(
        )  # flip the display, which finally shows our render

    pygame.quit()  # unload pygame modules
Example #17
0
    def __build_inputs(self):
        """
        Private function to bind inputs to functions
        """
        inputs = Inputs()
        
        inputs.register("new_object", Button(MOUSEBUTTONDOWN, 1))
        inputs.register("update", Button(MOUSEMOTION, 0))
        inputs.register("kill_all_objects", Button(KEYDOWN, K_SPACE))

        inputs.register("mleft", Button(KEYDOWN, K_LEFT))
        inputs.register("mright", Button(KEYDOWN, K_RIGHT))
        inputs.register("mup", Button(KEYDOWN, K_UP))
        inputs.register("mdown", Button(KEYDOWN, K_DOWN))
        inputs.register("zoomin", Button(MOUSEBUTTONDOWN, 4))
        inputs.register("zoomout", Button(MOUSEBUTTONDOWN, 5))

        self.app.inputs = inputs

        # Store functions to maintain weakrefs
        self.__dynamic_input_funcs["temp"] = self.app.inputs.inputs["new_object"].on_press(self.__new_object_stage1)

        # Add all the inputs that do not change
        #
        #
        # TODO: Needs a restructure so not referring down to scene
        #
        #
        self.__static_input_funcs.append(self.app.inputs.inputs["kill_all_objects"].on_press(self.scene.kill_all_objects))
        # self.__static_input_funcs.append(self.app.inputs.inputs["kill_all_objects"].on_press(self.__reset_new_object_stage))
        self.__static_input_funcs.append(self.app.inputs.inputs["mleft"].on_press_repeat(self.scene.move_cam_left, 0))
        self.__static_input_funcs.append(self.app.inputs.inputs["mright"].on_press_repeat(self.scene.move_cam_right, 0))
        self.__static_input_funcs.append(self.app.inputs.inputs["mup"].on_press_repeat(self.scene.move_cam_up, 0))
        self.__static_input_funcs.append(self.app.inputs.inputs["mdown"].on_press_repeat(self.scene.move_cam_down, 0))
        self.__static_input_funcs.append(self.app.inputs.inputs["zoomout"].on_press(self.scene.move_cam_out))
        self.__static_input_funcs.append(self.app.inputs.inputs["zoomin"].on_press(self.scene.move_cam_in))
Example #18
0
    def evaluate(self, path_to_checkpoint, path_to_tfrecords_file,
                 num_examples, global_step):
        batch_size = 128
        num_batches = int(num_examples / batch_size)

        with tf.Graph().as_default():
            input_ops = Inputs(path_to_tfrecords_file=path_to_tfrecords_file,
                               batch_size=batch_size,
                               shuffle=False,
                               min_queue_examples=5000,
                               num_preprocess_threads=4,
                               num_reader_threads=1)
            images, input_seqs, target_seqs, mask = input_ops.build_batch()

            mymodel = Model(vocab_size=12,
                            mode='evaluate',
                            embedding_size=512,
                            num_lstm_units=64,
                            lstm_dropout_keep_prob=0.7,
                            cnn_drop_rate=0.2,
                            initializer_scale=0.08)

            logits = mymodel.inference(images, input_seqs, mask)
            digit_predictions = tf.argmax(logits, axis=1)

            labels = tf.reshape(target_seqs, [-1])
            weights = tf.to_float(tf.reshape(mask, [-1]))
            predictions = tf.reshape(digit_predictions, [-1])

            accuracy, update_accuracy = tf.metrics.accuracy(
                labels=labels, predictions=predictions, weights=weights)

            tf.summary.image('image', images)
            tf.summary.scalar('accuracy', accuracy)
            tf.summary.histogram(
                'variables',
                tf.concat([
                    tf.reshape(var, [-1]) for var in tf.trainable_variables()
                ],
                          axis=0))
            summary = tf.summary.merge_all()

            with tf.Session() as sess:
                sess.run([
                    tf.global_variables_initializer(),
                    tf.local_variables_initializer()
                ])
                coord = tf.train.Coordinator()
                threads = tf.train.start_queue_runners(sess=sess, coord=coord)

                restorer = tf.train.Saver()
                restorer.restore(sess, path_to_checkpoint)

                for _ in range(num_batches):
                    sess.run(update_accuracy)

                accuracy_val, summary_val = sess.run([accuracy, summary])
                self.summary_writer.add_summary(summary_val,
                                                global_step=global_step)

                coord.request_stop()
                coord.join(threads)

        return accuracy_val
Example #19
0
    def __init__(self, config=None):
        # keep track of velocity, this allows me to counteract joystick with keyboard
        self.velocity = LVector3(0)
        if config is None:
            self.config = {}
            execfile('config.py', self.config)
        else:
            self.config = config
        self.reward = None
        if pydaq:
            self.reward = pydaq.GiveReward()
        self.reward_count = 0
        # self.color_map always corresponds to (r, g, b)
        # does not change during game, each game uses a particular color space
        self.color_dict = square.make_color_map(self.config['colors'])
        # sets the range of colors for this map
        self.c_range = self.config['c_range']
        # color variables (make dictionary?)
        # color_list is set in beginning, and then after that this is only
        # called again for non-random (training)
        self.color_list = square.set_start_position_colors(self.config)
        self.color_match = [0, 0, 0]
        self.color_tolerance = []
        self.last_avt, self.avt_factor = square.translate_color_map(
            self.config, self.color_dict, self.color_list)
        print 'starting avt position', self.last_avt
        print 'map avatar factor', self.avt_factor
        self.random = True
        if self.config.get('match_direction'):
            self.random = False
        # adjustment to speed so corresponds to gobananas task
        # 7 seconds to cross original environment
        # speed needs to be adjusted to both speed in original
        # environment and c_range of colors
        # self.speed = 0.05 * (self.c_range[1] - self.c_range[0])
        # speed is own variable, so can be changed during training.
        self.speed = self.config['speed']
        # map avatar variables
        self.render2d = None
        self.match_square = None
        self.map_avt_node = []

        # need a multiplier to the joystick output to tolerable speed
        self.vel_base = 3
        self.max_vel = [500, 500, 0]

        self.card = None

        self.base = ShowBase()
        self.base.disableMouse()
        # assume we are showing windows unless proven otherwise
        if self.config.get('win', True):
            # only need inputs if we have a window
            self.inputs = Inputs(self.base)
            props = WindowProperties()
            props.setCursorHidden(True)
            props.setForeground(True)
            print self.config.get('resolution')
            if self.config.get('resolution'):
                props.set_size(int(self.config['resolution'][0]),
                               int(self.config['resolution'][1]))
                props.set_origin(0, 0)
            else:
                props.set_size(600, 600)
                props.set_origin(400, 50)
            self.base.win.requestProperties(props)
            # print self.base.win.get_size()
            # setup color map on second window
            sq_node = square.setup_square(self.config)
            self.setup_display2(sq_node)
        # print 'background color', self.base.getBackgroundColor()
        # create the avatar
        self.avatar = NodePath(ActorNode("avatar"))
        self.avatar.reparentTo(self.base.render)
        self.avatar.setH(self.base.camera.getH())
        self.base.camera.reparentTo(self.avatar)
        self.base.camera.setPos(0, 0, 0)

        # initialize task variables
        self.frame_task = None
        self.started_game = None
        self.showed_match = None
        self.gave_reward = None

        # initialize and start the game
        self.set_next_trial()
Example #20
0
 def __init__(self, team, num_player=1, num_player_image_name="data/1.png"):
     Player_non_GK.__init__(self, team)
     self.inputs = Inputs(num_player)  #key config: player num_player
     self.num_player_image = pygame.image.load(num_player_image_name)
     self.number_human_player = num_player
Example #21
0
 def __init__(self, team):
     Player.__init__(self, team)
     self.inputs = Inputs(0)
Example #22
0
from flask import Flask, request, jsonify
from flask_cors import CORS
from controller import *
from client import get_node_data
from modes import Modes
from inputs import Inputs
import os
from fan_control import FanControl

inputs = Inputs()
modes = Modes()
Database.initialize()
load_nodes()
fanControl = FanControl()
fanControl.start()

app = Flask(__name__)
cors = CORS(app, resources={r"/*": {"origins": "*"}})


@app.route('/', methods=['POST'])
def update_node():
    data = request.get_json()
    insert_node(_id=data['id'],
                name=data['name'],
                node_type=data['type'],
                ports=data['ports'])
    return "OK"


@app.route('/get_node_names', methods=['GET'])
Example #23
0
def _train(path_to_train_tfrecords_file, num_train_examples,
           path_to_val_tfrecords_file, num_val_examples,
           path_to_train_log_dir, path_to_restore_checkpoint_file,
           training_options):

    batch_size = training_options['batch_size']  # 32
    initial_patience = training_options['patience']  # 100
    # output information setting
    num_steps_to_show_loss = 100
    num_steps_to_check = 1000

    with tf.Graph().as_default():
        input_ops = Inputs(path_to_tfrecords_file=path_to_train_tfrecords_file,
                           batch_size=32,
                           shuffle=True,
                           # int(0.4 * num_train_examples)
                           min_queue_examples=5000,
                           num_preprocess_threads=4,
                           num_reader_threads=1)
        images, input_seqs, target_seqs, mask = input_ops.build_batch()

        mymodel = Model(vocab_size=12,
                        mode='train',
                        embedding_size=512,
                        num_lstm_units=64,
                        lstm_dropout_keep_prob=0.7,
                        cnn_drop_rate=0.2,
                        initializer_scale=0.08)

        logits = mymodel.inference(images, input_seqs, mask)

        total_loss = mymodel.loss(logits, target_seqs)

        global_step = tf.Variable(initial_value=0,
                                  name="global_step",
                                  trainable=False,
                                  collections=[tf.GraphKeys.GLOBAL_STEP, tf.GraphKeys.GLOBAL_VARIABLES])

        initial_learning_rate = training_options['learning_rate']  # 1e-2
        decay_steps = training_options['decay_steps']  # 10000
        decay_rate = training_options['decay_rate']  # 0.9

        learning_rate = tf.train.exponential_decay(initial_learning_rate,
                                                   global_step=global_step,
                                                   decay_steps=decay_steps,
                                                   decay_rate=decay_rate,
                                                   staircase=True)
        optimizer = tf.train.GradientDescentOptimizer(learning_rate)
        train_op = optimizer.minimize(total_loss, global_step=global_step)

        tf.summary.image('image', images)
        tf.summary.scalar('loss', total_loss)
        tf.summary.scalar('learning_rate', learning_rate)
        summary = tf.summary.merge_all()

        with tf.Session() as sess:
            summary_writer = tf.summary.FileWriter(
                path_to_train_log_dir, sess.graph)
            evaluator = Evaluator(os.path.join(
                path_to_train_log_dir, 'eval/val'))

            sess.run(tf.global_variables_initializer())
            sess.run(tf.local_variables_initializer())

            coord = tf.train.Coordinator()
            threads = tf.train.start_queue_runners(sess=sess, coord=coord)

            saver = tf.train.Saver()
            if path_to_restore_checkpoint_file is not None:
                assert tf.train.checkpoint_exists(path_to_restore_checkpoint_file), \
                    '%s not found' % path_to_restore_checkpoint_file
                saver.restore(sess, path_to_restore_checkpoint_file)
                print('Model restored from file: %s' %
                      path_to_restore_checkpoint_file)

            print('Start training')
            patience = initial_patience
            best_accuracy = 0.0
            duration = 0.0

            while True:
                start_time = time.time()
                _, loss_val, summary_val, global_step_val, learning_rate_val = sess.run(
                    [train_op, total_loss, summary, global_step, learning_rate])
                duration += time.time() - start_time

                if global_step_val % num_steps_to_show_loss == 0:
                    examples_per_sec = batch_size * num_steps_to_show_loss / duration
                    duration = 0.0
                    print('=> %s: step %d, loss = %f (%.1f examples/sec)' %
                          (datetime.now(), global_step_val, loss_val, examples_per_sec))

                if global_step_val % num_steps_to_check != 0:
                    continue

                summary_writer.add_summary(
                    summary_val, global_step=global_step_val)

                print('=> Evaluating on validation dataset...')
                path_to_latest_checkpoint_file = saver.save(
                    sess, os.path.join(path_to_train_log_dir, 'latest.ckpt'))
                accuracy = evaluator.evaluate(path_to_latest_checkpoint_file, path_to_val_tfrecords_file,
                                              num_val_examples,  # 23508
                                              global_step_val)
                print('==> accuracy = %f, best accuracy %f' %
                      (accuracy, best_accuracy))

                if accuracy > best_accuracy:
                    path_to_checkpoint_file = saver.save(sess, os.path.join(path_to_train_log_dir, 'model.ckpt'),
                                                         global_step=global_step_val)
                    print('=> Model saved to file: %s' %
                          path_to_checkpoint_file)
                    patience = initial_patience
                    best_accuracy = accuracy
                else:
                    patience -= 1

                print('=> patience = %d' % patience)
                if patience == 0:
                    break

            coord.request_stop()
            coord.join(threads)
            print('Finished')
Example #24
0
    def __init__(self, config=None):
        if config is None:
            self.config = {}
            execfile('play_config.py', self.config)
        else:
            self.config = config
        self.reward = None
        print self.config['pydaq']
        if pydaq and self.config.setdefault('pydaq', True) is not None:
            self.reward = pydaq.GiveReward()
        self.reward_count = 0
        # adjustment to speed so corresponds to gobananas task
        # 7 seconds to cross original environment
        # speed needs to be adjusted to both speed in original
        # environment and c_range of colors
        # self.speed = 0.05 * (self.c_range[1] - self.c_range[0])
        # speed is own variable, so can be changed during training.
        self.speed = self.config['speed']

        # need a multiplier to the joystick output to tolerable speed
        self.vel_base = 4
        self.max_vel = [500, 500, 0]

        self.base = ShowBase()
        self.base.disableMouse()
        # self.base.setFrameRateMeter(True)
        # assume we are showing windows unless proven otherwise
        if self.config.get('win', True):
            # only need inputs if we have a window
            self.inputs = Inputs(self.base)
            props = WindowProperties()
            props.setCursorHidden(True)
            props.setForeground(True)
            print self.config.get('resolution')
            if self.config.get('resolution'):
                # main window
                props.set_size(int(self.config['resolution'][0]),
                               int(self.config['resolution'][1]))
                # props.set_origin(1920, 0)
                props.set_origin(500, 0)
            else:
                props.set_size(600, 600)
                props.set_origin(400, 50)
            self.base.win.requestProperties(props)
        # print 'background color', self.base.getBackgroundColor()
        # field = self.base.loader.loadModel("../goBananas/models/play_space/field.bam")
        field = self.base.loader.loadModel(
            "../goBananas/models/play_space/round_courtyard.bam")
        field.setPos(0, 0, 0)
        field.reparent_to(self.base.render)
        field_node_path = field.find('**/+CollisionNode')
        field_node_path.node().setIntoCollideMask(0)
        sky = self.base.loader.loadModel(
            "../goBananas/models/sky/sky_kahana2.bam")
        sky.setPos(0, 0, 0)
        sky.setScale(1.6)
        sky.reparentTo(self.base.render)
        windmill = self.base.loader.loadModel(
            "../goBananas/models/windmill/windmill.bam")
        windmill.setPos(-10, 30, -1)
        windmill.setScale(0.03)
        windmill.reparentTo(self.base.render)
        # mountain = self.base.loader.loadModel("../goBananas/models/mountain/mountain.bam")
        # mountain.setScale(0.0005)
        # mountain.setPos(10, 30, -0.5)

        # create the avatar
        self.avatar = NodePath(ActorNode("avatar"))
        self.avatar.reparentTo(self.base.render)
        self.avatar.setPos(0, 0, 1)
        self.avatar.setScale(0.5)
        pl = self.base.cam.node().getLens()
        pl.setFov(60)
        self.base.cam.node().setLens(pl)
        self.base.camera.reparentTo(self.avatar)

        # initialize task variables
        self.frame_task = None
        self.started_game = None
        self.showed_match = None
        self.gave_reward = None

        # initialize and start the game
        self.set_next_trial()