예제 #1
0
def test_ga_on_odd():
    X = np.arange(-10, 10).reshape(-1, 1)
    y = [[bool(x[0] % 2)] for x in X]

    instruction_set = (
        InstructionSet()
        .register_core_by_stack({"int"}, exclude_stacks={"str", "exec", "code"})
        .register_n_inputs(X.shape[1])
    )

    spawner = GeneSpawner(
        instruction_set=instruction_set,
        literals=[],
        erc_generators=[
            lambda: random.randint(0, 10),
        ]
    )

    est = PushEstimator(
        spawner=spawner,
        population_size=40,
        max_generations=10,
        simplification_steps=2)
    est.fit(X, y)

    assert isinstance(est._result.program, CodeBlock)
    assert len(est._result.program) > 0
예제 #2
0
def run_ga_on_odd_test(parallelism):
    X = np.arange(-10, 10).reshape(-1, 1)
    y = [[bool(x[0] % 2)] for x in X]

    instruction_set = (InstructionSet().register_core_by_stack(
        {"int"}, exclude_stacks={"str", "exec", "code"}))

    spawner = GeneSpawner(n_inputs=1,
                          instruction_set=instruction_set,
                          literals=[],
                          erc_generators=[
                              partial(random.randint, 0, 10),
                          ])

    est = PushEstimator(spawner=spawner,
                        population_size=30,
                        max_generations=3,
                        simplification_steps=10,
                        parallelism=parallelism)
    est.fit(X, y)

    assert isinstance(est.solution, Individual)
    assert len(est.solution.program.code) > 0

    path = "tmp.push"
    solution = est.solution.copy(deep=True)
    est.save(path)
    est.load(path)
    assert solution == est.solution
    os.remove(path)
예제 #3
0
def test_estimator_with_pandas(simple_test_spawner):
    df = pd.DataFrame({
        "x1": [-2, -1, 0, 1, 2],
        "x2": [-1, 2, -3, 4, -5],
        "y":  [2, -2, 0, 4, -10]
    })

    est = PushEstimator(
        spawner=simple_test_spawner,
        population_size=10,
        max_generations=3,
        simplification_steps=3,
        parallelism=False
    )
    est.fit(df[["x1", "x2"]], df[["y"]])

    assert isinstance(est.solution, Individual)
    assert len(est.solution.program.code) > 0
예제 #4
0
def run_ga_on_odd_test(spawner, parallelism):
    X = np.arange(-10, 10).reshape(-1, 1)
    y = [[bool(x[0] % 2)] for x in X]

    est = PushEstimator(
        spawner=spawner,
        population_size=10,
        max_generations=3,
        simplification_steps=3,
        parallelism=parallelism)
    est.fit(X, y)

    assert isinstance(est.solution, Individual)
    assert len(est.solution.program.code) > 0

    path = "tmp.push"
    solution = est.solution.copy(deep=True)
    est.save(path)
    est.load(path)
    assert solution == est.solution
    os.remove(path)
예제 #5
0
def test_estimator_with_custom_types(point_cls, point_instr_set):
    X = np.arange(-1.0, 1.0, 0.05).reshape(-1, 4)
    y = [[point_distance(point_cls(x[0], x[1]), point_cls(x[2], x[3]))] for x in X]

    spawner = GeneSpawner(
        instruction_set=point_instr_set,
        literals=[],
        erc_generators=[]
    )

    est = PushEstimator(
        spawner=spawner,
        population_size=40,
        max_generations=10,
        simplification_steps=2,
        interpreter=PushInterpreter(point_instr_set),
    )
    est.fit(X, y)

    assert isinstance(est._result.program, CodeBlock)
    assert len(est._result.program) > 0
예제 #6
0
def test_estimator_with_custom_types(point_cls, point_instr_set):
    X = np.arange(-1.0, 1.0, 0.05).reshape(-1, 4)
    y = [[point_distance(point_cls(x[0], x[1]), point_cls(x[2], x[3]))]
         for x in X]

    spawner = GeneSpawner(n_inputs=1,
                          instruction_set=point_instr_set,
                          literals=[],
                          erc_generators=[])

    est = PushEstimator(
        spawner=spawner,
        population_size=30,
        max_generations=3,
        simplification_steps=2,
        interpreter=PushInterpreter(point_instr_set),
    )
    est.fit(X, y)

    assert isinstance(est.solution, Individual)
    assert len(est.solution.program.code) > 0
예제 #7
0
def test_ga_on_odd():
    X = np.arange(-10, 10).reshape(-1, 1)
    y = [[bool(x[0] % 2)] for x in X]

    instruction_set = (InstructionSet().register_by_type(
        ["int"], exclude=["str", "exec",
                          "code"]).register_n_inputs(X.shape[1]))

    spawner = GeneSpawner(instruction_set=instruction_set,
                          literals=[],
                          erc_generators=[
                              lambda: random.randint(0, 10),
                          ])

    est = PushEstimator(spawner=spawner,
                        population_size=20,
                        max_generations=10,
                        simplification_steps=100)
    est.fit(X, y)

    assert isinstance(est._result.program, CodeBlock)
    assert len(est._result.program) > 0
예제 #8
0
    "abcde", "", "E", "Hi", "Tom", "leprechaun", "zoomzoomzoom",
    "qwertyuiopasd", "GallopTrotCanter", "Quinona", "_abc"
]).reshape(-1, 1)
y = np.array([[target_function(s[0])] for s in X])

spawner = GeneSpawner(
    n_inputs=1,
    instruction_set=InstructionSet().register_core_by_stack({"str", "int"}),
    literals=[],
    erc_generators=[
        lambda: random.randint(0, 10),
    ]
)

if __name__ == "__main__":
    est = PushEstimator(
        spawner=spawner,
        population_size=300,
        max_generations=30,
        initial_genome_size=(10, 50),
        simplification_steps=500,
        parallelism=False,
        verbose=1
    )

    est.fit(X=X, y=y)
    print("Best program found:")
    print(est.solution.program.pretty_str())
    print("Errors:")
    print(est.score(X, y))
예제 #9
0
    .register(point_distance_insrt)
    .register(point_from_floats_instr)
)

print(instruction_set.keys())

spawner = GeneSpawner(
    n_inputs=2,
    instruction_set=instruction_set,
    literals=[2.0],
    erc_generators=[]
)


# Our estimator with a custom interpreter defined.
est = PushEstimator(
    spawner=spawner,
    population_size=300,
    max_generations=20,
    simplification_steps=500,
    interpreter=PushInterpreter(instruction_set),
    verbose=2
)


if __name__ == "__main__":
    est.fit(X, y)
    print(est.solution.program)
    print(est.predict(X))
    print(est.score(X, y))
예제 #10
0
print(instruction_set.keys())

spawner = GeneSpawner(
    instruction_set=instruction_set,
    literals=[2.0],
    erc_generators=[]
)


# Our estimator with a custom interpreter defined.
est = PushEstimator(
    spawner=spawner,
    population_size=500,
    max_generations=20,
    simplification_steps=1000,
    interpreter=PushInterpreter(instruction_set),
    verbose=2
)


if __name__ == "__main__":
    logging.basicConfig(
        level=logging.INFO,
        format="%(asctime)s %(levelname)s %(message)s",
        stream=sys.stdout
    )
    est.fit(X, y)
    print(est._result.program)
    print(est.predict(X))
    print(est.score(X, y))
예제 #11
0
         [equal_vectors() for _ in range(100)] + \
         [random_vectors() for _ in range(100)]
y_test = [[target_function(x[0], x[1])] for x in X_test]

spawner = GeneSpawner(
    n_inputs=2,
    instruction_set=InstructionSet().register_core_by_stack(
        {"int", "bool", "vector_int", "exec"}),
    literals=[" ", "\n"],
    erc_generators=[
        lambda: random.random() < 0.5,
    ],
)

if __name__ == "__main__":
    est = PushEstimator(search="GA",
                        population_size=500,
                        max_generations=150,
                        spawner=spawner,
                        simplification_steps=100,
                        verbose=2)

    start = time.time()
    est.fit(X=X_train, y=y_train)
    end = time.time()
    print("========================================")
    print("post-evolution stats")
    print("========================================")
    print("Runtime: ", end - start)
    print("Test Error: ", np.sum(est.score(X_test, y_test)))
예제 #12
0
    [6.3, 2.9, 5.6, 1.8, 2],
    [6.5, 3.0, 5.8, 2.2, 2],
    [7.6, 3.0, 6.6, 2.1, 2],
    [4.9, 2.5, 4.5, 1.7, 2],
    [7.3, 2.9, 6.3, 1.8, 2],
    [6.7, 2.5, 5.8, 1.8, 2],
    [7.2, 3.6, 6.1, 2.5, 2],
],
                    columns=[
                        "sepal_length", "sepal_width", "petal_length",
                        "petal_width", "label"
                    ])

spawner = GeneSpawner(
    n_inputs=1,
    instruction_set=InstructionSet().register_core_by_stack(
        {"bool", "int", "float"}),
    literals=[0, 1, 2],
    erc_generators=[lambda: random.randint(0, 10), random.random])

if __name__ == "__main__":
    est = PushEstimator(spawner=spawner,
                        population_size=300,
                        max_generations=100,
                        verbose=2)

    x = data[["sepal_length", "sepal_width", "petal_length", "petal_width"]]
    y = data[["label"]]

    est.fit(x, y)
예제 #13
0
파일: string_demo.py 프로젝트: erp12/Pysh

spawner = GeneSpawner(
    instruction_set=instruction_set,
    literals=[],
    erc_generators=[
        lambda: random.randint(0, 10),
    ]
)


if __name__ == "__main__":
    logging.basicConfig(
        level=logging.INFO,
        format="%(asctime)s %(levelname)s %(message)s",
        stream=sys.stdout
    )

    est = PushEstimator(
        spawner=spawner,
        population_size=200,
        max_generations=30,
        initial_genome_size=(10, 50),
        verbose=2
    )

    est.fit(X=X, y=y)
    print(est._result.program)
    print(est.predict(X))
    print(est.score(X, y))
예제 #14
0
파일: demo.py 프로젝트: erp12/pyshgp-demo
and the specify the tap should print before by implementing the `pre` method of `Tap`.
"""


class MyCustomTap(Tap):
    def pre(self, id: str, args, kwargs, obj=None):
        """Print population stats before the next step of the run."""
        search = args[0]
        best_individual = search.population.best()
        print()
        print("Generation:", search.generation)
        print("Best Program:", best_individual.program.pretty_str())
        print("Best Error Vector:", best_individual.error_vector)
        print("Best Total Error:", best_individual.total_error)


TapManager.register("pyshgp.gp.search.SearchAlgorithm.step", MyCustomTap())
"""
Now let's kick off our PushGP run!

We will call the estimator's `.fit` method on our training data, and then call `.score` on our 
test data. If the test errors are all zero, we found a generalizing solution!
"""

if __name__ == "__main__":
    est.fit(X=x_train, y=y_train)
    best_found = est.solution

    print("Program:\n", best_found.program.code.pretty_str())
    print("Test errors:\n", est.score(x_test, y_test))