Search code examples
pythonpython-3.xgenetic-algorithmmutation

Mutation of a binary vector inside a list


import random 

chosen=[[[0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1], [3], [0]], 
        [[0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0], [5], [2]]]    

def mutation(chosen, mp):
    for i in range(len(chosen)):
        if random.random() < mp:
            chosen[0][i] = type(chosen[0][i])(not chosen[0][i])
    return (chosen)

mp=0.9 #probability
mutated=mutation(chosen, mp)
print (mutated)

Assuming that chosen stands for the selected individuals in a population, I am trying to mutate the binary vectors (at random position) based on the given probability. and return it in a different list (I am still not sure if the extra list is necessary).

It's not really working as expected, anyone knows what could be wrong in the code?

  File "<ipython-input-229-91852a46fa82>", line 9, in mutation
    chosen[0][i] = type(chosen[0][i])(not chosen[0][i])

TypeError: 'bool' object is not iterable

Also, if someone knows a more convenient way for this it would be totally welcome.

Thank you!


Solution

  • I'm still guessing at what you want, but if you just want to flip one of the binary bits:

    import random
    
    chosen=[[[0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1], [3], [0]], 
            [[0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0], [5], [2]]]    
    
    def mutation(chosen, mp):
        for i in range(len(chosen)):
            if random.random() < mp:
                pos = random.randrange(len(chosen[i][0]))
                chosen[i][0][pos] = 0 if chosen[i][0][pos] else 1
    
    # before
    for item in chosen:
        print(item)
    print()
    
    mutation(chosen, 1) # 100% of the time, for now
    
    # after
    for item in chosen:
        print(item)
    

    Output (note last bit changed and 3rd bit changed in the rows):

    [[0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1], [3], [0]]
    [[0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0], [5], [2]]
    
    [[0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0], [3], [0]]
    [[0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0], [5], [2]]