请用python写一份遗传算法
时间: 2023-03-15 22:33:41 浏览: 115
很高兴为您服务!我可以为您提供一份Python实现的遗传算法的示例代码: # 导入相关模块
import random
import numpy as np# 初始化种群
population_size = 100
population = [random.randint(1, 100) for _ in range(population_size)]# 设置遗传参数
mutation_probability = 0.05 # 突变概率
crossover_probability = 0.90 # 交叉概率# 设置迭代次数
iteration_number = 100# 定义适应度函数
def fitness(x):
# 这里的函数可以根据需要自定义
return x**2 # 用轮盘赌进行选择
def roulette_selection(population):
population_fitness = [fitness(x) for x in population]
population_probability = [fitness(x) / sum(population_fitness) for x in population_fitness]
roulette_wheel = np.cumsum(population_probability)
rand_num = random.random()
selected_index = 0
for index, value in enumerate(roulette_wheel):
if rand_num <= value:
selected_index = index
break
return selected_index# 执行迭代
for _ in range(iteration_number):
# 选择
parent1 = population[roulette_selection(population)]
parent2 = population[roulette_selection(population)] # 交叉
if crossover_probability > random.random():
crossover_point = random.randint(1, len(parent1))
child1 = parent1[:crossover_point] + parent2[crossover_point:]
child2 = parent2[:crossover_point] + parent1[crossover_point:]
else:
child1, child2 = parent1, parent2 # 突变
if mutation_probability > random.random():
mutation_point = random.randint(1, len(child1))
child1[mutation_point] = random.randint(1, 100)
child2[mutation_point] = random.randint(1, 100) # 将新一代种群替换老一代种群
population[roulette_selection(population)] = child1
population[roulette_selection(population)] = child2# 输出最终结果
print(population)
阅读全文