Example #1
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)
Example #2
0
def simple_test_spawner():
    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),
        ]
    )
    return spawner
Example #3
0
    def produce(self, parents: Sequence[Genome],
                spawner: GeneSpawner) -> Genome:
        """Produce a child Genome from parent Genomes and optional GenomeSpawner.

        Parameters
        ----------
        parents
            A list of parent Genomes given to the operator.
        spawner
            A GeneSpawner that can be used to produce new genes (aka Atoms).

        """
        return spawner.spawn_genome(self.size)
Example #4
0
    def produce(self, parents: Sequence[Genome],
                spawner: GeneSpawner) -> Genome:
        """Produce a child Genome from parent Genomes and optional GenomeSpawner.

        Parameters
        ----------
        parents
            A list of parent Genomes given to the operator.
        spawner
            A GeneSpawner that can be used to produce new genes (aka Atoms).

        """
        self.checknum_parents(parents)
        new_genome = Genome()
        for gene in parents[0]:
            if random() < self.rate:
                new_genome.append(spawner.spawn_atom())
            new_genome.append(gene)
        return new_genome
Example #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(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
Example #6
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
Example #7
0
def target_function(s):
    """Generate a training data point."""
    return s[:-2] + s[:-2]


X = np.array([
    "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
    )
Example #8
0
#
# For example, the instruction int_from_float will NOT be registered because
# our type library does not define a type that would support the "int" stack.
#
# Our two custom instructions as well as the input instructions are also defined.
instruction_set = (
    InstructionSet(type_library=type_library, register_core=True)
    .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
)

Example #9
0
y = [[target_function(x)] for x in X]

# testing data set; testX is input, testy is output
testX = np.arange(0, 30).reshape(-1, 1)
testy = [[target_function(tx)] for tx in testX]
"""
Next we have to declare our `GeneSpawner`. 
A spawner holds all the instructions, literals, erc generators, 
and inputs that we want to appear in our genomes/programs.
It will be used by evolution to generate random genomes for our initial population and random genes for mutation.
A spawner has many parameters that can be filled and changed, 
but here we make use of as many of the default values as possible and filled in only what is necessary.
"""

spawner = GeneSpawner(n_inputs=1,
                      instruction_set="core",
                      literals=[],
                      erc_generators=[lambda: random.randint(0, 10)])
"""
We now have everything we need to configure a run of PushGP.
We will create a `PushEstimator` and parameterize it however we want. 
Let's be sure to pass an instance of our spawner.
Like earlier, we  simplified the estimator by only passing it what is necessary,
    but there are several other parameters that can be filled and changed.
"""

if __name__ == "__main__":
    est = PushEstimator(spawner=spawner,
                        simplification_steps=2000,
                        parallelism=False,
                        verbose=2)
    """
Example #10
0
                    [random_vectors() for _ in range(10)]

X_train = X_train_edge + X_train_synthetic
y_train = [[target_function(x[0], x[1])] for x in X_train]


X_test = [mirror_vectors() for _ in range(100)] + \
         [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)
Example #11
0
X_test = [[synthetic_input()] for _ in range(100)]
y_test = [target_function(x[0]) for x in X_test]

# Spawner


def random_char():
    """Return a random character."""
    return Char(choice(_possible_chars))


spawner = GeneSpawner(
    n_inputs=1,
    instruction_set=InstructionSet().register_core_by_stack(
        {"int", "bool", "string", "char", "exec", "stdout"}),
    literals=[" ", "\n"],
    erc_generators=[
        random_char,
    ],
)

if __name__ == "__main__":
    est = PushEstimator(search="GA",
                        population_size=500,
                        max_generations=150,
                        spawner=spawner,
                        simplification_steps=100,
                        last_str_from_stdout=True,
                        parallelism=True,
                        verbose=2)
y_train_synthetic = [target_function(x[0]) for x in X_train_synthetic]

X_train = X_train_edge + X_train_synthetic
y_train = y_train_edge + y_train_synthetic

X_test = [[synthetic_input()] for _ in range(100)]
y_test = [target_function(x[0]) for x in X_test]

# Spawner

instruction_set = (InstructionSet().register_by_type(
    ["int", "bool", "string", "char", "exec", "stdout"]).register_n_inputs(1))

spawner = GeneSpawner(
    instruction_set=instruction_set,
    literals=[Char(" "), Char("\n")],
    erc_generators=[lambda: Char(choice(_possible_chars)), synthetic_input],
)

# Estimator

est = PushEstimator(search="GA",
                    population_size=1000,
                    max_generations=100,
                    spawner=spawner,
                    last_str_from_stdout=True,
                    verbose=2)

if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO,
                        format="%(asctime)s %(levelname)s %(message)s",
Example #13
0
from pyshgp.push.instruction_set import InstructionSet


def target_function(a, b):
    return (2 * a * b) + (b * b)


X = np.arange(50).reshape(-1, 2)
y = np.array([[target_function(x[0], x[1])] 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),
                      ])

ep_lex_sel = Lexicase(epsilon=True)

est = PushEstimator(population_size=200,
                    max_generations=50,
                    spawner=spawner,
                    selector=ep_lex_sel,
                    verbose=2)

if __name__ == '__main__':
    logging.basicConfig(level=logging.INFO,
                        format="%(asctime)s %(levelname)s %(message)s",
                        stream=sys.stdout)
Example #14
0
def simple_gene_spawner(instr_set):
    i_set = InstructionSet()
    i_set.register_list([instr_set["int_add"], instr_set["int_sub"], instr_set["exec_if"]])
    l_set = [5, 1.2, True]
    return GeneSpawner(1, i_set, l_set, [random.random])
Example #15
0
from pyshgp.gp.selection import Lexicase
from pyshgp.push.instruction_set import InstructionSet


def target_function(x: float) -> (float, float):
    """Generate a training data point."""
    return max(0.0, x), max(0.1 * x, x)


X = np.arange(-1.0, 1.0, 0.05).reshape([-1, 1])
y = np.array([target_function(x[0]) for x in X])

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

ep_lex_sel = Lexicase(epsilon=True)

if __name__ == "__main__":
    est = PushEstimator(population_size=300,
                        max_generations=50,
                        simplification_steps=500,
                        spawner=spawner,
                        selector=ep_lex_sel,
                        verbose=2)

    est.fit(X=X, y=y)
Example #16
0
def simple_gene_spawner(atoms):
    i_set = InstructionSet()
    i_set.register_list([atoms["add"], atoms["sub"], atoms["if"]])
    l_set = [atoms["5"], atoms["1.2"], atoms["true"]]
    return GeneSpawner(i_set, l_set, [random.random])