I have been trying to attempt writing a Genetic Algorithm using value encoding (fixed-length vectors of real numbers) instead of binary encoding. So far the code I have written works, but needs quite a lot more population than the binary encoded code to converge to 0.
This is the code I am using:
#one-point crossover
def crossover(p1, p2, r_cross):
c1, c2 = p1.copy(), p2.copy()
check for recombination
if rand() < r_cross:
# select crossover point that is not on the end of the string
pt = randint(0, len(p2))
# perform crossover
c1 = p1[:pt] + p2[pt:]
c2 = p2[:pt] + p1[pt:]
return [c1, c2]
mutation operator
def mutation(nval, r_mut):
for i in range(len(nval)):
# check for a mutation
if rand() < r_mut:
# flip the bit
nval[i] = 1 - nval[i]
I have tried working it out following the instructions in the below link to rewrite my code, but am not sure if my crossover or mutation function works as it is supposed to: How do mutation and crossover work with real-valued chromosomes?