Esempio n. 1
0
def test_fittest():

    ref = B.tensor([2, 0, 1, 1, 0, 2, 1, 1])
    d = B.tensor([2, 1, 1, 0, 1, 1, 1, 1])
    pop = B.tensor([ref, d, ref, d, ref, d])

    fitness_function = InvertedCosineSimilarity(ref)
    selector = SelectFittest()
    selected_pop, fitness_scores = selector(fitness_function, pop, pop)
    print(selected_pop)
    assert selected_pop.shape == pop.shape
    for chromosome in selected_pop:
        assert B.tensor_equal(chromosome, ref)
def test_cosine_similarity_1dpopulation(backends):
    "test the function works on a population and broadcast correctly"

    reference = [1, 0, 1, 1, 0, 1, 1, 1]
    different = [1, 1, 1, 0, 1, 1, 1, 1]

    r = B.tensor(reference)
    d = B.tensor(different)
    population = B.tensor([r, d, r])
    cs = InvertedCosineSimilarity(r)

    # similar vector have a distance of 1
    distances = cs(population)
    print("distances", distances)
    assert int(distances[0]) == 1
    assert distances[1] < 1
    assert int(distances[2]) == 1
Esempio n. 3
0
 def _flatten_population(self, population):
     """Convert the population to a 1D array as many ops (e.g norm) don't
     work on Ndimension
     """
     if len(population.shape) < 3:
         return population
     num_chromosomes = population.shape[0]
     flattened_size = int(B.prod(B.tensor(population.shape[1:])))
     return B.reshape(population, (num_chromosomes, flattened_size))
Esempio n. 4
0
    def assign(self, chromosomes):
        """Assign concrete values to the input
        """
        chromosomes = B.tensor(chromosomes)

        if chromosomes.shape != self.shape:
            raise ValueError(
                'Incompatible input shape expected: %s - got: %s' %
                (self.shape, chromosomes.shape))
        self.chromosomes = chromosomes
Esempio n. 5
0
def test_sum2d():
    t = B.randint(0, 10, (10, 10, 10))
    v = Sum().call(t)

    result = []
    for r in t:
        result.append(B.sum(r, axis=-1))
    result = B.tensor(result)

    assert v.shape == (10, )
    for idx, a in enumerate(v):
        assert v[idx].all() == result[idx].all()
Esempio n. 6
0
    def __init__(self, max_sum_value=None, **kwargs):
        """Compute the sum of the chromosomes as fitness values.

        Args:
            expected_max_sum_value (int, optional): What is the maximum value
            the sum per chromosome will reach. Used to normalize the fitness
            function between 0 and 1 if specified. Defaults to None.

        Note:
            This fitness function is used to solve the MAXONE problem.

        """
        super(Sum, self).__init__('sum_genes', **kwargs)
        if max_sum_value:
            self.max_sum_value = B.tensor(max_sum_value)
        else:
            self.max_sum_value = None
Esempio n. 7
0
    def __init__(self, reference_chromosome, **kwargs):
        """Inverted Cosine similarity function that returns 1 when chromosomes
        are similar to the reference chromose and [0, 1[ when different

        For reference implementation see
        https://github.com/scipy/scipy/blob/v0.14.0/scipy/spatial/distance.py#L267  # noqa

        Args:
            reference_chromosome (tensor1D): reference_chromosome.
        """
        super(InvertedCosineSimilarity, self).__init__('invet_cosine_sim',
                                                       **kwargs)

        # cache ref chromosome flattend
        self.ref_chromosome = B.flatten(B.tensor(reference_chromosome))

        # caching ref pop norm
        self.ref_norm = B.norm(self.ref_chromosome)
Esempio n. 8
0
def test_helloworld():
    "Solve the MAXONE problem"
    NUM_EVOLUTIONS = 10
    SHAPE = (512, 1024)
    MAX_VAL = 1

    population = genRandIntPopulation(SHAPE, MAX_VAL)

    inputs = Input(SHAPE)
    x = RandomMutations1D(max_gene_value=1)(inputs)
    outputs = UniformCrossover1D()(x)
    gf = GeneFlow(inputs, outputs, debug=0)
    fitness_function = Sum(max_sum_value=SHAPE[1])
    evolution_strategy = SelectFittest()
    gf.compile(evolution_strategy, fitness_function)
    gf.summary()
    results = gf.evolve(population, num_evolutions=NUM_EVOLUTIONS)
    assert results

    metrics = results.get_metrics_history()

    # check metrics
    for metric_name, vals in metrics.items():
        assert isinstance(vals, list)
        assert len(vals) == 10
        assert isinstance(vals[9], float)

    assert 'fitness_mean' in metrics
    assert 'fitness_max' in metrics

    # assert the engine solved the (Trivial) problem
    assert max(metrics['fitness_max']) == 1
    assert metrics['fitness_max'][9] == 1
    assert min(metrics['fitness_max']) < 1  # max sure we did improve

    # check population value
    population = results.get_populations()
    assert (population.shape) == SHAPE
    assert B.tensor_equal(population[0], B.tensor([1] * SHAPE[1]))
Esempio n. 9
0
def test_box_unbox_tensor():
    val = tensor([1, 2, 3])

    assert unbox(box(val)).all() == val.all()
Esempio n. 10
0
def test_eager():
    "when passing concrete value GF is suppposed to return a concrete value"
    val = B.tensor(42)
    assert Dummy(debug=True)(val) == val