Esempio n. 1
0
class TestSimplePushGPEvolverMethods(unittest.TestCase):
    def setUp(self):
        self.evo = SimplePushGPEvolver(max_generations=3,
                                       population_size=5,
                                       simplification_steps=50)
        self.ef = lambda s: [np.random.random(), np.random.random()]

    def test_fit(self):
        self.evo.fit(self.ef, 1, ['_float'])
        self.assertTrue(hasattr(self.evo, 'best_'))

    def test_predict(self):
        self.evo.fit(self.ef, 1, ['_float'])
        X = [[1.1], [2.2]]
        predictions = self.evo.predict(X)
        self.assertIsInstance(predictions, np.ndarray)
Esempio n. 2
0
testing_set = generate_cases(50)


def error_function(program, debug=False):
    errors = []
    for case in training_set:
        interpreter = PushInterpreter()
        result = interpreter.run(program, [case[0]], ['_vector_integer'],
                                 debug)[0]
        if result is None:
            errors.append(1e5)
        else:
            errors.append(levenshtein_distance(case[1], result))
    return errors


atom_generators = list(
    merge_sets(get_instructions_by_pysh_type("_integer"),
               get_instructions_by_pysh_type("_boolean"),
               get_instructions_by_pysh_type("_vector_integer"),
               get_instructions_by_pysh_type("_exec"),
               [lambda: 0, lambda: PushVector([], int)]))

if __name__ == "__main__":
    evo = SimplePushGPEvolver(n_jobs=-1,
                              verbose=1,
                              atom_generators=atom_generators,
                              initial_max_genome_size=400,
                              selection_method='lexicase')
    evo.fit(error_function, 1, ['_vector_integer'])
Esempio n. 3
0
def error_function(program, debug=False):
    errors = []
    for case in training_set:
        interpreter = PushInterpreter()
        interpreter.run(program, [case[0]], [], debug)
        result = interpreter.state.stdout
        if result is None:
            errors.append(1e5)
        else:
            errors.append(levenshtein_distance(case[1], result))
    return errors


atom_generators = list(merge_sets(
    get_instructions_by_pysh_type("_integer"),
    get_instructions_by_pysh_type("_boolean"),
    get_instructions_by_pysh_type("_string"),
    get_instructions_by_pysh_type("_char"),
    get_instructions_by_pysh_type("_exec"),
    get_instructions_by_pysh_type("_print"),
    [lambda: Character('!')]
))

if __name__ == "__main__":
    evo = SimplePushGPEvolver(n_jobs=-1, verbose=1,
                              atom_generators=atom_generators,
                              initial_max_genome_size=400,
                              max_generations=300)
    evo.fit(error_function, 1, [])
Esempio n. 4
0

atom_generators = list(merge_sets(
    get_instructions_by_pysh_type("_integer"),
    get_instructions_by_pysh_type("_boolean"),
    get_instructions_by_pysh_type("_print"),
    get_instructions_by_pysh_type("_exec"),
    [lambda: random.randint(-100, 100)]
))


alternation = Alternation(rate=0.01, alignment_deviation=5)
mutation = UniformMutation(rate=0.01)
genetic_operators = [
    (alternation, 0.2),
    (mutation, 0.2),
    (PerturbCloseMutation(rate=0.1), 0.1),
    (VariationOperatorPipeline((alternation, mutation)), 0.5)
]


if __name__ == "__main__":
    evo = SimplePushGPEvolver(n_jobs=-1, verbose=2,
                              atom_generators=atom_generators,
                              initial_max_genome_size=400,
                              operators=genetic_operators,
                              population_size=1000,
                              max_generations=200,
                              selection_method='lexicase')
    evo.fit(error_function, 4, [])
Esempio n. 5
0
    errors = []
    for x in range(10):
        # Create the push interpreter and run program
        interpreter = PushInterpreter()
        y_hat = interpreter.run(program, inputs=[x],
                                output_types=['_integer'])[0]
        # Get output
        if y_hat is not None:
            # compare to target output
            target_int = target_function(x)
            # calculate error
            errors.append((y_hat - target_int)**2)
        else:
            errors.append(1e5)
    return errors


# Genetic operators
mut = UniformMutation()
alt = Alternation()
ops = [(Alternation(), 0.6), (UniformMutation(), 0.2),
       (VariationOperatorPipeline((alt, mut)), 0.2)]

if __name__ == "__main__":
    evo = SimplePushGPEvolver(n_jobs=-1,
                              verbose=1,
                              operators=ops,
                              selection_method='epsilon_lexicase',
                              atom_generators=list(all_instructions))
    evo.fit(error_func, 1, ['_integer'])
Esempio n. 6
0
X_train, X_test, y_train, y_test = train_test_split(iris.data,
                                                    iris.target,
                                                    test_size=0.3)


def iris_error_func(program):
    error_vec = []
    for i in range(X_train.shape[0]):
        interpreter = PushInterpreter()
        outputs = interpreter.run(program, X_train[i],
                                  ['_float', '_float', '_float'])
        not_none = [x for x in outputs if x is not None]
        if len(not_none) == 0:
            error_vec.append(1000000)
        else:
            y_hat = outputs.index(max(not_none))
            if y_hat == y_train[i]:
                error_vec.append(0)
            else:
                error_vec.append(1)
    return error_vec


if __name__ == "__main__":
    evo = SimplePushGPEvolver(n_jobs=-1,
                              verbose=2,
                              atom_generators=CLASSIFICATION_ATOM_GENERATORS,
                              max_generations=50,
                              population_size=300)
    evo.fit(iris_error_func, 4, ['_class', '_class', '_class'])
Esempio n. 7
0
        e = 0

        if output[0] is None:
            e += 1000
        elif output[0] != targets[0]:
            e += 1

        if output[1] is None:
            e += 1000
        elif output[1] != targets[1]:
            e += 1

        errors.append(e)
    return errors


atom_generators = list(merge_sets(get_instructions_by_pysh_type('_boolean'),
                                  get_instructions_by_pysh_type('_exec')))
mut = UniformMutation(rate=0.1)
alt = Alternation(rate=0.1, alignment_deviation=10)
ops = [(alt, 0.2), (mut, 0.3), (VariationOperatorPipeline((mut, alt)), 0.5)]


if __name__ == "__main__":
    evo = SimplePushGPEvolver(n_jobs=-1, verbose=1, operators=ops,
                              atom_generators=atom_generators,
                              initial_max_genome_size=300,
                              population_size=500, max_generations=300,
                              simplification_steps=5000)
    evo.fit(error_function, 3, ['_boolean', '_boolean'])
Esempio n. 8
0

atom_generators = [
    get_instruction("_string_length"),
    get_instruction("_string_head"),
    get_instruction("_string_concat"),
    get_instruction("_string_stack_depth"),
    get_instruction("_string_swap"),
    get_instruction("_string_dup"),
    get_instruction("_integer_add"),
    get_instruction("_integer_sub"),
    get_instruction("_integer_dup"),
    get_instruction("_integer_swap"),
    get_instruction("_integer_stack_depth"),
    get_instruction("_integer_inc"), lambda: random.randint(0, 10),
    lambda: random_str()
]

if __name__ == "__main__":
    # evo = SimplePushGPEvolver(
    #     verbose=1,
    #     atom_generators=atom_generators,
    #     population_size=100,
    #     max_generations=3,
    #     simplification_steps=100,
    #     n_jobs=1)
    evo = SimplePushGPEvolver(verbose=2,
                              atom_generators=atom_generators,
                              n_jobs=-1)
    evo.fit(string_error_func, 1, ['_string'])
Esempio n. 9
0
def error_function(program, debug=False):
    errors = []
    for case in training_set:
        interpreter = PushInterpreter()
        result = interpreter.run(program, case[0], ['_vector_integer'],
                                 debug)[0]
        if result is None:
            errors.append(1e5)
        else:
            e = []
            for i in range(min(len(result), len(case[1]))):
                e.append(abs(result[i] - case[1][i]))
            e.append(abs(len(result) - len(case[1])) * 100)
            errors.append(sum(e))
    return errors


atom_generators = list(
    merge_sets(get_instructions_by_pysh_type("_integer"),
               get_instructions_by_pysh_type("_vector_integer"),
               get_instructions_by_pysh_type("_exec"),
               [lambda: random.randint(-100, 100)]))

if __name__ == "__main__":
    evo = SimplePushGPEvolver(n_jobs=-1,
                              verbose=1,
                              atom_generators=atom_generators,
                              initial_max_genome_size=400)
    evo.fit(error_function, 2, ['_vector_integer'])
Esempio n. 10
0
 def setUp(self):
     self.evo = SimplePushGPEvolver(max_generations=3,
                                    population_size=5,
                                    simplification_steps=50)
     self.ef = lambda s: [np.random.random(), np.random.random()]
Esempio n. 11
0
        # Create the push interpreter
        interpreter = PushInterpreter()
        y_hat = interpreter.run(program, [x], ['_integer'])[0]
        # Get output
        if y_hat is None:
            errors.append(1e5)
        else:
            # compare to target output
            y_target = target_function(x)
            # calculate error
            errors.append(abs(y_hat - y_target))
    return errors


atom_generators = [
    # lambda: random.randint(0, 10),
    I_add_integer,
    I_sub_integer,
    I_mult_integer,
    I_div_integer
]


if __name__ == "__main__":
    evo = SimplePushGPEvolver(n_jobs=-1, verbose=2,
                              selection_method='epsilon_lexicase',
                              atom_generators=atom_generators,
                              max_generations=50,
                              keep_linear=True)
    evo.fit(error_func, 1, ['_integer'])
Esempio n. 12
0
File: odd.py Progetto: lacava/pyshgp
        # Create the push interpreter
        interpreter = PushInterpreter()
        interpreter.state['_integer'].push(i)
        # Run program
        y_hat = interpreter.run(program, [i], ['_boolean'], debug)[0]
        # Get output
        if y_hat is None:
            errors.append(1e5)
        else:
            # compare to target output
            y = bool(i % 2)
            if y_hat == y:
                errors.append(0)
            else:
                errors.append(1)
    return errors


atom_generators = list(
    merge_sets(get_instructions_by_pysh_type("_integer"),
               get_instructions_by_pysh_type("_boolean"),
               get_instructions_by_pysh_type("_code"),
               get_instructions_by_pysh_type("_exec"),
               [lambda: random.randint(0, 100)]))

if __name__ == "__main__":
    evo = SimplePushGPEvolver(n_jobs=1,
                              verbose=2,
                              atom_generators=atom_generators)
    evo.fit(odd_error_func, 1, ['_boolean'])
Esempio n. 13
0
        if output is None:
            errors.append(1e5)
        elif len(output) != len(target):
            errors.append(1e4)
        else:
            rmse = np.linalg.norm(np.array(output) -
                                  np.array(target)) / np.sqrt(len(output))
            errors.append(rmse)
    return errors


atom_generators = list(
    merge_sets(get_instructions_by_pysh_type('_integer'),
               get_instructions_by_pysh_type('_vector'),
               get_instructions_by_pysh_type('_exec')))
mut = UniformMutation(rate=0.1)
alt = Alternation(rate=0.1, alignment_deviation=10)
ops = [(alt, 0.2), (mut, 0.3), (VariationOperatorPipeline((mut, alt)), 0.5)]

if __name__ == "__main__":
    evo = SimplePushGPEvolver(n_jobs=-1,
                              verbose=1,
                              operators=ops,
                              atom_generators=atom_generators,
                              selection_method='epsilon_lexicase',
                              initial_max_genome_size=300,
                              population_size=500,
                              max_generations=300,
                              simplification_steps=5000)
    evo.fit(error_function, 1, ['_vector_boolean'])