|
6 | 6 | from src.selection.selector import Selector |
7 | 7 | from src.combination.combination import Combinator |
8 | 8 | from src.mutation.mutation import Mutator |
| 9 | +import random |
9 | 10 |
|
10 | 11 | if __name__ == '__main__': |
11 | | - values = [ |
12 | | - -0.914592, |
13 | | - -0.516787, |
14 | | - -0.246207, |
15 | | - 1.480791, |
16 | | - 0.835307, |
17 | | - 1.229633, |
18 | | - 0.133068, |
19 | | - -0.897179, |
20 | | - 0.100578, |
21 | | - -0.311975, |
22 | | - 1.411980, |
23 | | - 0.404924, |
24 | | - 1.954865, |
25 | | - 0.359503, |
26 | | - 1.255452, |
27 | | - 1.124764, |
28 | | - 1.527482, |
29 | | - 1.573845, |
30 | | - -0.562311, |
31 | | - 1.191435 |
32 | | - ] |
| 12 | + population_size = 20 |
| 13 | + generations = 50 |
33 | 14 | lower_bound = -1 |
34 | 15 | upper_bound = 2 |
35 | 16 | precision = 6 |
36 | 17 | f = lambda x: -(x ** 2) + x + 2 |
37 | 18 | combination_rate = 0.25 |
38 | | - mutation_rate = 0.1 |
| 19 | + mutation_rate = 0.01 |
| 20 | + |
| 21 | + values = [round(random.uniform(lower_bound, upper_bound), precision) for _ in range(population_size)] |
39 | 22 | coder = coder.Coder(lower_bound, upper_bound, precision) |
40 | 23 | binaries = [coder.encoder.encode(x)for x in values] |
41 | 24 | fitnesses = [f(x) for x in values] |
|
46 | 29 | combinator = Combinator(population, combination_rate) |
47 | 30 | mutator = Mutator(population, mutation_rate) |
48 | 31 |
|
49 | | - print('Initial population:') |
| 32 | + SEPARATOR = '----------------------------------------\n' |
| 33 | + |
| 34 | + print('Initial population:\n') |
50 | 35 | for c in population: |
51 | 36 | c.show() |
52 | | - |
53 | | - selected = selector.select() |
| 37 | + print(SEPARATOR) |
54 | 38 |
|
55 | | - print('\nSelected population:') |
56 | | - for c in selected: |
| 39 | + population = selector.select() |
| 40 | + print('\nSelected population:\n') |
| 41 | + for c in population: |
57 | 42 | c.show() |
58 | | - population = selected |
| 43 | + print(SEPARATOR) |
59 | 44 |
|
60 | | - print(f'Combination rate: {combination_rate}') |
| 45 | + print(f'Combination rate: {combination_rate}\n') |
61 | 46 | population = combinator.combine() |
62 | 47 |
|
63 | | - print('\nAfter combination:') |
| 48 | + print('\nAfter combination:\n') |
64 | 49 | for c in population: |
65 | 50 | c.show() |
| 51 | + print(SEPARATOR) |
66 | 52 |
|
67 | | - print(f'Mutation rate: {mutation_rate}') |
| 53 | + print(f'Mutation rate: {mutation_rate}\n') |
68 | 54 | population = mutator.mutate() |
69 | 55 |
|
70 | | - print('\nAfter mutation:') |
| 56 | + print('\nAfter mutation:\n') |
71 | 57 | for c in population: |
72 | 58 | c.show() |
| 59 | + print(SEPARATOR) |
| 60 | + |
| 61 | + coder.should_print = False |
| 62 | + selector.should_print = False |
| 63 | + combinator.should_print = False |
| 64 | + mutator.should_print = False |
73 | 65 |
|
74 | 66 | print('\n\n\n') |
75 | 67 | for i in range(49): |
|
0 commit comments