用Python语言实现遗传算法,请给出一个代码实例
时间: 2023-03-09 12:36:11 浏览: 103
# 以下是一个关于Python语言实现的遗传算法的代码实例:def geneticAlgorithm(population, fitness_fn, nGeneration=1000, eliteRate=0.2, mutationRate=0.01):
for i in range(nGeneration):
newPopulation = []
# 计算种群每个个体的适应度
fits = [fitness_fn(chrom) for chrom in population]
# 计算当代种群的最优解和最差解
fitness_best = max(fits)
fitness_worst = min(fits)
# 计算选择概率
selectProb = [fit / sum(fits) for fit in fits]
# 选择nGeneration*eliteRate个个体
eliteIndex = np.random.choice(range(len(population)), int(nGeneration*eliteRate), p=selectProb)
elite = [population[i] for i in eliteIndex]
newPopulation.extend(elite)
while len(newPopulation) < nGeneration:
# 交叉
crossedP = np.random.choice(elite, 2, replace=False)
newP = crossover(crossedP[0], crossedP[1])
# 变异
if np.random.random() < mutationRate:
newP = mutation(newP)
newPopulation.append(newP)
population = newPopulation
# 返回最优解
bestIndex = np.argmax(fits)
return population[bestIndex]
阅读全文