用Python语言实现遗传算法,请给出一个代码实例
时间: 2023-03-09 20:36:11 浏览: 70
# 以下是一个关于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]
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)