I am trying to implement a genetic algorithm in python. I have an initial population of six individuals. I measure their fitness and probability to be in the next generation and pick three pairs for mating with mating probability of 0.7. To do the crossover I pass the pairs and the mating probability to a function.
new_population = cross_over(pairsg, mating_prob)
where pairsg are the pairs picked for mating, and mating-prob is a binary list(if 1 do cross_over, if 0 don't). The problem is that cross_over function changes the original population although population variable is never used inside it
def cross_over(prs, mp):
new = []
for pr in prs:
if mp[prs.index(pr)] == 1:
index = np.random.choice([1,2,3], p=[1/3, 1/3, 1/3])
pr[0][:index], pr[1][:index] = pr[1][:index], pr[0][:index]
for pr in prs:
new.append(pr[0])
new.append(pr[1])
return new
And this is the complete code:
from random import *
import numpy as np
#fitness function
def fit(x):
return 15*x -x**2
#covert binary list to decimal number
def to_dec(x):
return int("".join(str(e) for e in x), 2)
#picks pairs from the original population
def gen_pairs(populationl, prob):
pairsl = []
test = [0, 1, 2, 3, 4, 5]
for i in range(3):
pair = []
for j in range(2):
temp = np.random.choice(test, p=prob)
pair.append(populationl[temp])
pairsl.append(pair)
return pairsl
#mating function
def cross_over(prs, mp):
new = []
for pr in prs:
if mp[prs.index(pr)] == 1:
index = np.random.choice([1,2,3], p=[1/3, 1/3, 1/3])
pr[0][:index], pr[1][:index] = pr[1][:index], pr[0][:index]
for pr in prs:
new.append(pr[0])
new.append(pr[1])
return new
population = [[1,0,1,0], [0,1,1,0], [1,0,0,1], [1,1,1,0],[1,1,0,0],[1,0,0,0]]
fittness = [fit(to_dec(y)) for y in population]
s = sum(fittness)
prob = [e/s for e in fittness]
pairsg = gen_pairs(population.copy(), prob)
mating_prob = []
for i in pairsg:
mating_prob.append(np.random.choice([0,1], p=[0.3,0.7]))
new_population = cross_over(pairsg, mating_prob)
population.copy()you pass a shallow copy. Therefore, it is a new list with the same references to the sublists from which it was copied. When you modify those sublists, since they are the same lists, you will see these changes reflected in the originalpopulationlist. - juanpa.arrivillaga