Beispiel #1
0
    def testForwardPropagationWithHiddenLayerAndRecurrence(self):
        inputs = [1., 1.]
        weights = [
            np.array([[1., 2.], [1., 2.], [1., 1.], [1., 1.]]),
            np.array([[1., 1.], [1., 1.]])
        ]
        weights_flat = nn.flatten_weights(weights)
        net = nn.NeuralNet(weights=weights_flat,
                           nr_of_input_nodes=len(inputs),
                           hidden_layers=1,
                           hidden_layer_nodes=2,
                           nr_of_outputs=2,
                           recurrence=True)
        expected_output_iteration_1 = nn.flatten_weights(
            np.tanh([
                1.9633568798148839277386570684426,
                1.9633568798148839277386570684426
            ]))
        # on the first iteration the memory nodes are initialized with 0
        output_iteration_1 = nn.flatten_weights(net.forward_prop(inputs))
        self.assertAlmostEqual(expected_output_iteration_1, output_iteration_1)

        # on the second round the memory nodes the value from the previous iteration
        expected_output_iteration_2 = nn.flatten_weights(
            np.tanh([
                1.99920285031581971304150882377,
                1.99920285031581971304150882377
            ]))
        output_iteration_2 = nn.flatten_weights(net.forward_prop(inputs))
        print(expected_output_iteration_2)
        print(output_iteration_2)
        self.assertAlmostEqual(expected_output_iteration_2, output_iteration_2)
Beispiel #2
0
    def testTranslation(self):
        array = [0., 1., 2., 3., 4., 5., 6., 7.]
        mat1 = [np.array([[0., 1.], [2., 3.], [4., 5.], [6., 7.]])]

        net = nn.NeuralNet(weights=array,
                           nr_of_input_nodes=4,
                           hidden_layers=0,
                           nr_of_outputs=2,
                           recurrence=False)
        mat2 = net.weights_as_mat()
        for i in range(0, len(mat1)):
            npt.assert_almost_equal(mat1[i], mat2[i])
Beispiel #3
0
 def testForwardPropagation(self):
     inputs = [1., 1.]
     weights = [np.array([[1., 2.], [1., 2.]])]
     weights_flat = nn.flatten_weights(weights)
     expected_output = nn.flatten_weights(np.tanh([2., 4.]))
     net = nn.NeuralNet(weights=weights_flat,
                        nr_of_input_nodes=len(inputs),
                        hidden_layers=0,
                        hidden_layer_nodes=0,
                        nr_of_outputs=2,
                        recurrence=False)
     output = nn.flatten_weights(net.forward_prop(inputs))
     self.assertAlmostEqual(expected_output, output)
Beispiel #4
0
 def testForwardPropagationWithHiddenLayer(self):
     inputs = [1., 1.]
     weights = [
         np.array([[1., 2.], [1., 2.]]),
         np.array([[1., 1.], [1., 1.]])
     ]
     expected_output = nn.flatten_weights(
         np.tanh([
             1.9633568798148839277386570684426,
             1.9633568798148839277386570684426
         ]))
     weights_flat = nn.flatten_weights(weights)
     net = nn.NeuralNet(weights=weights_flat,
                        nr_of_input_nodes=len(inputs),
                        hidden_layers=1,
                        hidden_layer_nodes=2,
                        nr_of_outputs=2,
                        recurrence=False)
     output = nn.flatten_weights(net.forward_prop(inputs))
     self.assertAlmostEqual(expected_output, output)
Beispiel #5
0
    def simulate(self,
                 graphics_enabled=True,
                 time_dilation=1,
                 timeout=0,
                 weights=[],
                 static_delta_t=None,
                 recurrence=False,
                 start_x=0,
                 start_y=0,
                 start_angle=0,
                 fitness_id=1):
        """
            Start a simulation
            graphics_enabled: boolean; If set to false, graphics rendering is skipped
            time_dilation: integer; All time interactions are multiplied  by this factor. 1 = realtime
                Set time_dilation to 0 to use a static delta_t for updating (simulation will run as fast as hardware allows)
            timeout: integer; Timeout of simulation in seconds. 0 = no timeout

            Returns the fitness evaluation of the simulation (float) when the simulation is finished
        """
        try:
            self.reset()
            # Apply configuration parameters and check their validity
            self.graphics_enabled = graphics_enabled
            self.fitness_id = fitness_id
            if len(weights) > 0:
                self.neural_net = ann.NeuralNet(weights, recurrence=recurrence)
            else:
                # Just use some sample velocity in case weights are missing (demo mode)
                self.robot.set_velocity(0.65,
                                        0.5)  # 0.65,0.5 = circle movement
                # self.robot.set_velocity(1, 1)
            self.time_dilation = time_dilation
            if time_dilation == 0:
                self.static_time_mode = True
            if static_delta_t is not None:
                # Static delta_t can not exceed the robots radius or else it will shoot trough environment limits!
                if static_delta_t > 200:
                    raise ValueError(
                        'delta_t exceeds the limit of 200ms. Requested delta_t: '
                        + str(static_delta_t))
                self.delta_t = static_delta_t
            else:
                if time_dilation == 0:
                    self.delta_t = 200

            if start_x != 0 and start_y != 0:
                self.robot.set_robot_initial_position(start_x, start_y,
                                                      start_angle)

            if self.on_init() == False:
                # Has no return value but will return False if pygame library encounters an internal error
                raise ValueError('Error during pygame initialization')

            # Reset simulation time
            self.time = 0
            self.simulation_start_time = datetime.now()

            while self._running:
                if graphics_enabled:
                    for event in pygame.event.get():
                        self.on_event(event)
                if not self._paused:
                    self.on_loop()
                    self.on_render()

                if timeout > 0:
                    if (self.get_elapsed_time() > (timeout * 1000)):
                        self._running = False

            # pygame.quit()

            return self.fitness()
        except IndexError as inst:
            print('\033[91m' +
                  "=== INDEX ERROR === Simulation failed with message: ")
            print(inst)
            if self.static_time_mode:
                print(
                    "This error is likely caused by the robot going off screen. Try lowering the static delta_time"
                )
            else:
                print(
                    "This error is likely caused by the robot going off screen. Try lowering the time dilation"
                )
            print('\033[0m' + "\n")
            return 0