示例#1
0
def test_select_mating_pool_SUS():
    np.random.seed(11)

    evo = Evolution(
        population_size=10,
        population=np.array(list(range(1, 11))),
        genotype_size=1,
        fitness_normalization_mode='FPS',
        selection_mode='SUS',
        reproduction_mode='GENETIC_ALGORITHM',
        evaluation_function=lambda _:
        [0.3, 0.2, 0.1, 0.1, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05],
        max_generation=0,
        elitist_fraction=0.2,
        mating_fraction=0.8,  # in beer this is 1 - elitist_fraction
    )

    evo.run()
    evo.fitnesses = np.array(
        [0.3, 0.2, 0.1, 0.1, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05])

    # print("Fitnesses: {}".format(evo.fitnesses))

    assert evo.n_mating == 8
    assert evo.n_elite == 2
    assert evo.n_fillup == 0

    mating_pool = evo.select_mating_pool()

    print(mating_pool)
    assert mating_pool == [1, 1, 1, 2, 3, 4, 6, 8]

    print('SUCCESS!')
示例#2
0
def test_select_mating_pool_RWS():

    from collections import Counter
    performances = np.array([1000, 1000, 300, 200, 200, 100, 50, 50, 50, 50])
    np.random.seed(11)

    evo = Evolution(
        population_size=10,
        population=np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),
        genotype_size=1,
        fitness_normalization_mode='RANK',
        selection_mode='RWS',
        evaluation_function=lambda _: performances,
        max_generation=0,
        elitist_fraction=0.2,
        mating_fraction=0.8,  # in beer this is 1 - elitist_fraction
    )

    evo.run()

    print("Fitnesses: {}".format(evo.fitnesses))

    # assert evo.n_elite == 2 # only in genetic algorithm
    # assert evo.n_fillup == 0  # only in genetic algorithm
    assert evo.n_mating == evo.population_size

    mating_counter = Counter()

    repetitions = 10000
    for _ in range(repetitions):
        mating_pool = evo.select_mating_pool()
        for e in mating_pool:
            mating_counter[e] += 1

    # we check if the number of time each genome is selected is proportionate to the its performance (and fitness)
    # not guaranteed to work for fitness_normalization_mode == 'FPS' because of the linear scaling
    # not easy to test this further (not implemented in beer)
    for i in range(2, 9):
        assert mating_counter[i] > mating_counter[i + 1]

    print(sorted(mating_counter.items(), key=lambda kv: kv[0]))

    print('SUCCESS!')