Implement mutation operator

This commit is contained in:
coolneng 2021-06-17 19:15:50 +02:00
parent 9cafdc0536
commit ed41333e87
Signed by: coolneng
GPG Key ID: 9893DA236405AF57
1 changed files with 21 additions and 13 deletions

View File

@ -1,6 +1,7 @@
from numpy import sum, append, arange, delete, where from numpy import sum, append, arange, delete, where
from numpy.random import randint, choice, shuffle, random from numpy.random import randint, choice, shuffle, random
from pandas import DataFrame from pandas import DataFrame
from math import ceil
def get_row_distance(source, destination, data): def get_row_distance(source, destination, data):
@ -16,9 +17,7 @@ def compute_distance(element, solution, data):
distinct_elements = solution.query(f"point != {element}") distinct_elements = solution.query(f"point != {element}")
for _, item in distinct_elements.iterrows(): for _, item in distinct_elements.iterrows():
accumulator += get_row_distance( accumulator += get_row_distance(
source=element, source=element, destination=item.point, data=data
destination=item.point,
data=data,
) )
return accumulator return accumulator
@ -120,16 +119,25 @@ def element_in_dataframe(solution, element):
return not duplicates.empty return not duplicates.empty
def mutate(solution, n, probability=0.001): def select_new_gene(individual, n):
if random() > probability: while True:
return solution new_gene = randint(n)
row = solution.sample() if not element_in_dataframe(solution=individual, element=new_gene):
random_element = randint(n) return new_gene
while element_in_dataframe(solution=solution, element=random_element):
random_element = randint(n)
solution["point"].iloc[row.index] = random_element def mutate(population, n, probability=0.001):
solution["distance"].loc[row.index] = 0 expected_mutations = len(population) * n * probability
return solution individuals = []
genes = []
for _ in range(ceil(expected_mutations)):
individuals.append(randint(n))
genes.append(population[individuals[-1]].sample().index)
for ind, gen in zip(individuals, genes):
individual = population[ind]
individual["point"].iloc[gen] = select_new_gene(individual, n)
individual["distance"].iloc[gen] = 0
return population
def tournament_selection(solution): def tournament_selection(solution):