deffitness_function(solution): fitness = 0 for i inrange(chromosome_length): fitness = fitness + solution[i] * 2**i # Return the fitness of a solution fitness = fitness/(2**chromosome_length-1)*5 return fitness*math.exp(math.sin(2*math.pi*fitness))
染色体单点交叉函数
1 2 3 4 5 6 7 8
defone_point_crossover(chromosome1, chromosome2): # Select a random crossover point crossover_point = random.randint(1, len(chromosome1) - 1) # Create two new offspring chromosomes by swapping genetic information offspring1 = chromosome1[:crossover_point] + chromosome2[crossover_point:] offspring2 = chromosome2[:crossover_point] + chromosome1[crossover_point:] # Return the two new offspring chromosomes return offspring1, offspring2
# Initialize the population population = [] for i inrange(population_size): chromosome = [] for j inrange(chromosome_length): chromosome.append(random.randint(0, 1)) population.append(chromosome)
import random import math # Run the genetic algorithm for generation inrange(generations): # Evaluate the fitness of each solution in the population fitness_scores = [] for chromosome in population: fitness_scores.append(fitness_function(chromosome))
# Select the fittest individuals for reproduction selected_population = [] for i inrange(population_size//3): chromosome1 = random.choices(population, weights=fitness_scores)[0] chromosome2 = random.choices(population, weights=fitness_scores)[0] selected_population.append(chromosome1) selected_population.append(chromosome2) if random.random() < crossover_rate: offspring1, offspring2 = one_point_crossover( chromosome1, chromosome2) selected_population.append(offspring1) selected_population.append(offspring2)
# Apply mutations to the selected population mutated_population = [] for chromosome in selected_population: for i inrange(chromosome_length): if random.random() < mutation_rate: chromosome[i] = 1 - chromosome[i] mutated_population.append(chromosome)
# Replace the old population with the new population population = mutated_population
# Print the fittest solution for each generation print("Generation:", generation, "Fittest solution:", max(fitness_scores))