Reputation: 25
I'm new to genetic algorithm and trying to find a way avoid selecting two same parents, but I am failed to do that.
Assume that the initial popuation is
[[0,0,0,0,1],[0,0,0,1,0],[0,0,1,0,0],[[0,1,0,0,0].
Assume that the fitness for each individual is [2,3,4,5]
.
The code used to pick parent is shown below:
def select_individual(population, scores, k=4):
first_pick = np.random.randint(0,len(population))
for second_pick in np.random.randint(0,len(population),k-1):
if scores[second_pick] < scores[first_pick]:
winner = second_pick
else:
winner = first_pick
return population[winner,:]
When I tried to used the code shown below to retrieve two parents, it returned two identical parents sometimes.
for i in range(0, len(population),2):
# Selection
parents = [select_individual(population, scores) for _ in range(len(population))]
parent_1 = parents [i]
parent_2 = parents [i+1]
print('Parent_1: ',np.round(parent_1,2))
print('Parent_2: ',np.round(parent_2,2))
One of the output, for example, is shown below:
Parent_1: [0,0,0,1,0]
Parent_2: [0,0,0,1,0]
Parent_1: [0,0,1,0,0]
Parent_2: [0,0,1,0,0]
Or
Parent_1: [0,0,0,1,0]
Parent_2: [0,0,1,0,0]
Parent_1: [0,0,0,1,0]
Parent_2: [0,0,1,0,0]
Could you please tell me that what's wrong with the code and why two selected parents are identical finally? Thank you very much!
Upvotes: 1
Views: 56
Reputation: 36
In select_individual() after you have selected your first pick you iterate over the same list to select your second pick. You could create a list where you have excluded the first_pick from 'population' and iterate over that instead.
Upvotes: 1