Exemplo n.º 1
0
    def run(self):

        if not self.intitialized:
            self.initialize()
        while True:

            self.selection()
            self.reproduction()

            # Save self.best_child
            self.best_child = self.current_pop[np.argmax(
                self.current_pop_fitness)]
            self.generation_list.append(self.best_child)

            # Get fitness of best child
            gen = len(self.generation_list)
            # Gen is used to determine bag for sampling
            random.seed(gen)
            bag_index = random.choice(range(len(self.bags)))
            selected_bag = self.bags[bag_index]
            f = Fitness(self.best_child,
                        json_data=self.json_data,
                        gen=gen,
                        data=selected_bag,
                        y_classes=self.y_classes,
                        fitness_func=self.fitness_func)
            f.run()
            best_child_fitness = round(f.fitness_value, 2)
            self.generation_fitness.append(best_child_fitness)

            if len(self.generation_list) % 1 == 0:
                if not self.silent:
                    print('Generation: {} Fitness: {}'.format(
                        len(self.generation_list), best_child_fitness))

                if self.auto_plot:
                    # Plays through data in a pygame window

                    Viewer.Playback(f.fitness_data_array,
                        text='Generation: {}  Fitness: {}'.\
                        format(len(self.generation_list),best_child_fitness),
                        dna=f.world.world).run()

            # Update to the next generation
            self.update_pop()

            # If the max_epochs is met, then stop.
            if self.max_epochs != -1:
                if len(self.generation_list) > self.max_epochs:
                    break
        return self
Exemplo n.º 2
0
    def predict(self, X, plot=False):
        '''
        Predicts the y class of X

        Expects:
            X np.ndarray            Target of class prediction
        '''

        assert isinstance(X, np.ndarray),\
            'X is expected to be of type: np.ndarray'
        assert X.shape[0] >= 1,\
            'X must be a minimum of 1 sample'
        assert self.isFit, \
            'Run .fit(X,y) prior to .predict(X)'

        # Apply scaling
        X, y = self.preprocess(X, training=False)
        p = ProbSpace(X, quantize_size=(15, 15), training=False)
        self.bags = p.stratified_training_bags(X)
        assert isinstance(self.bags, list)
        data = self.bags[0]

        # Init empty y_pred
        y_pred_array = np.empty((len(data), 1)).astype(int)

        for m in range(len(data)):

            # Run data in the Cellular Automata env
            res = CellularA(data=copy.deepcopy(data[m]['space']),
                            dna=self.selected_model_dna,
                            json_data=self.json_data).run()

            # Determine estimate with percentage of class-associate cells
            cTypes = self.json_data.color_types
            class_colors = [cTypes[key]['value'] for key in sorted(cTypes.keys()) \
                            if cTypes[key]['type'] == 'class_reserved']

            y_pred_proba = np.empty((len(self.y_classes)))
            y_pred_sums = np.empty((len(self.y_classes)))

            for i in range(len(self.y_classes)):
                y_pred_sums[i] = np.sum([np.sum((res['data_array'][-1][ii].reshape(-1, 3).astype(int) \
                                 == np.array(class_colors[i]).astype(int)).all(axis=1)) for ii in range(4)])

                # Determine the percentage of guess density for each possible y class
                y_pred_proba = y_pred_sums.astype(float) / y_pred_sums.astype(
                    float).sum()
                y_pred_proba = np.array(
                    [x if str(x) != 'nan' else 0.01 for x in y_pred_proba])

            y_pred = self.y_classes[np.argmax(y_pred_proba)]

            if plot:
                Viewer.Playback(res['data_array'],
                text='Predict class: '. \
                format(y_pred),
                dna=self.selected_model_dna).run()

            # Temporary rule
            y_pred = int((y_pred / 10) + 1)
            y_pred_array[m][0] = y_pred

        return y_pred_array