遗传算法python实例
时间: 2023-10-26 18:08:10 浏览: 106
下面是一个简单的遗传算法 Python 实例,用于寻找函数 f(x) = x^2 在 [-10, 10] 范围内的最大值:
```python
import random
# 定义目标函数
def f(x):
return x**2
# 遗传算法参数
pop_size = 20 # 种群大小
num_generations = 50 # 迭代次数
mutation_rate = 0.1 # 变异率
# 生成初始种群
pop = [random.uniform(-10, 10) for _ in range(pop_size)]
# 开始迭代
for _ in range(num_generations):
# 计算适应度
fitness = [f(x) for x in pop]
# 选择
selected = []
for _ in range(pop_size):
# 轮盘赌选择
total_fitness = sum(fitness)
r = random.uniform(0, total_fitness)
acc_fitness = 0
for i, x in enumerate(pop):
acc_fitness += fitness[i]
if acc_fitness > r:
selected.append(x)
break
# 交叉
offspring = []
for i in range(pop_size):
parent1 = random.choice(selected)
parent2 = random.choice(selected)
if parent1 != parent2:
child = (parent1 + parent2) / 2
offspring.append(child)
# 变异
for i in range(pop_size):
if random.uniform(0, 1) < mutation_rate:
offspring[i] += random.uniform(-1, 1)
# 更新种群
pop = offspring
# 寻找最优解
best_x = pop[0]
best_fitness = f(best_x)
for x in pop:
fitness = f(x)
if fitness > best_fitness:
best_x = x
best_fitness = fitness
print("最优解为:", best_x)
print("最大值为:", best_fitness)
```
该例子中,我们使用了轮盘赌选择、均值交叉和随机变异等基本遗传算法操作。在迭代 50 轮后,可以得到函数 f(x) 在 [-10, 10] 范围内的最大值。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)