1
votes

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)
2
when you pass 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 original population list. - juanpa.arrivillaga

2 Answers

3
votes

the problem is that you're making a copy in

gen_pairs(population.copy(), prob)

but you copy the outer list, but not the sublist data (it's a shallow copy). So

pr[0][:index], pr[1][:index] = pr[1][:index], pr[0][:index]

changes the original data (because pair.append(populationl[temp]) also doesn't copy but uses the same reference of sub-lists)

You have to follow the references of the sub-lists to figure that out.

Once you understood the issue, there are many ways of avoiding that. Make a copy of the sub-lists at some point.

you could do:

gen_pairs([x.copy() for x in population], prob)

to create a "deep-copy" (or copy.deepcopy(population)))

Or replace

pair.append(populationl[temp])

by

pair.append(populationl[temp].copy())
1
votes

Any time you pass an argument to a python function, you basically just pass a reference to that object, and everything you do to the object inside the function is also reflected outside. That happens even if the object has a different name outside. pairsg and prs still refer to the same list. This is analogous to how after a = [] and b = a, both a and b refer to the exact same object.

So be careful when passing mutable arguments (such as lists) to a function. Argument passing works the same for immutable arguments but you don't run into this problem because an immutable argument can't be changed.

So the solution is to not modify prs. This should work:

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])
            new.append(pr[1][:index])
            new.append(pr[0][:index])
        else:
            new.append(pr[0])
            new.append(pr[1])

    return new