-
Notifications
You must be signed in to change notification settings - Fork 0
/
genetic_algorithm.py
138 lines (114 loc) · 5.27 KB
/
genetic_algorithm.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
from necklace_model import Necklace
import random
import numpy as np
import matplotlib.pyplot as plt
class GeneticAlgorithm():
def __init__(self):
# Set standard model
self.__model = Necklace(4, 1)
population = [self.__model]
# Rates for updating population
def set_model(self, model):
self.__model = model
def run(self,population_size=100,num_gens=1,crossover_rate=0.1,mutation_rate=0.1,clone_rate=0.1):
"""
Runs the genetic algorithm with given parameters
:return:
"""
# Create population
population = []
for k in range(population_size):
nkl = self.__model.get_copy()
nkl.shuffle_state()
population.append(nkl)
energiesArr = np.empty(num_gens)
energiesVBSFArr = np.empty(num_gens)
# Iterate over all generations
for o in range(num_gens):
# Crossovers
idx_cross1 = random.sample(range(0,population_size),int(crossover_rate/2*population_size))
idx_cross2 = random.sample(range(0,population_size),int(crossover_rate/2*population_size))
for i,j in zip(idx_cross1,idx_cross2):
population[i].crossover(population[j])
# Mutants
idx_mutants = random.sample(range(0,population_size),int(mutation_rate*population_size))
for i in idx_mutants:
population[i].mutate()
# Clone the individuals with lowest energy
pop_energies = [x.get_energy() for x in population]
sort_idx = np.argsort(pop_energies)
for i in range(int(clone_rate*population_size)):
population.append(population[sort_idx[i]].get_copy())
pop_energies.append(population[sort_idx[i]].get_energy())
# Reduce population size to original one
pop_energies = [indiv.get_energy() for indiv in population]
sort_idx = np.argsort(pop_energies)
new_generation = []
sum_energy = 0
for i in range(population_size):
new_generation.append(population[sort_idx[i]])
sum_energy += pop_energies[sort_idx[i]]
population = new_generation
# Set energies
energiesArr[o] = sum_energy / population_size
if o == 0: energiesVBSFArr[o] = np.min(pop_energies)
elif energiesVBSFArr[o-1] > np.min(pop_energies): energiesVBSFArr[o] = np.min(pop_energies)
else: energiesVBSFArr[o] = energiesVBSFArr[o-1]
return energiesArr, energiesVBSFArr
def run_expanded(self,population_size=100,num_gens=1,crossover_rate=0.1,mutation_rate=0.1,clone_rate=0.1):
"""
Runs the genetic algorithm with given parameters on the expanded necklace model
:return:
"""
# Create population
population = []
for k in range(population_size):
nkl = self.__model.get_copy()
nkl.expand()
nkl.shuffle_expanded()
population.append(nkl)
# Arrays for storing energy
energiesArr = np.empty(num_gens)
energiesVBSFArr = np.empty(num_gens)
# Iterate over all generations
for o in range(num_gens):
# Crossovers
idx_cross1 = random.sample(range(0,population_size),int(crossover_rate/2*population_size))
idx_cross2 = random.sample(range(0,population_size),int(crossover_rate/2*population_size))
for i,j in zip(idx_cross1,idx_cross2):
population[j] = population[i].crossover_expanded(population[j])
# Mutants
idx_mutants = random.sample(range(0,population_size),int(mutation_rate*population_size))
for i in idx_mutants:
population[i].mutate_expanded()
# Clone the individuals with lowest energy
pop_energies = [x.get_energy() for x in population]
sort_idx = np.argsort(pop_energies)
for i in range(int(clone_rate*population_size)):
population.append(population[sort_idx[i]].get_copy())
pop_energies.append(population[sort_idx[i]].get_energy())
# Reduce population size to original one
pop_energies = [indiv.get_energy() for indiv in population]
sort_idx = np.argsort(pop_energies)
new_generation = []
sum_energy = 0
for i in range(population_size):
new_generation.append(population[sort_idx[i]])
sum_energy += pop_energies[sort_idx[i]]
population = new_generation
# Set energies
energiesArr[o] = sum_energy / population_size
if o == 0: energiesVBSFArr[o] = np.min(pop_energies)
elif energiesVBSFArr[o-1] > np.min(pop_energies): energiesVBSFArr[o] = np.min(pop_energies)
else: energiesVBSFArr[o] = energiesVBSFArr[o-1]
return energiesArr, energiesVBSFArr
if __name__ == '__main__':
nkl = Necklace(20,2)
ga = GeneticAlgorithm()
ga.set_model(nkl)
energies,energiesVBSF = ga.run_expanded(population_size=1000,num_gens=200,clone_rate=0.5,crossover_rate=0.1,mutation_rate=0.5)
plt.plot(energies)
plt.savefig('test.png')
plt.close()
plt.plot(energiesVBSF)
plt.savefig('test2.png')