采用遗传算法求函数最优解,完整代码
时间: 2023-07-02 11:15:48 浏览: 108
下面是一个使用Python实现遗传算法求解函数最优解的示例代码。本代码以求解函数 f(x) = x^2 在区间 [0, 31] 上的最小值为例。
```python
import random
# 定义函数
def f(x):
return x**2
# 遗传算法参数
pop_size = 50 # 种群大小
elite_size = 5 # 精英个体数
mutation_rate = 0.1 # 变异率
generations = 30 # 迭代次数
# 初始化种群
def init_population(pop_size):
population = []
for i in range(pop_size):
individual = random.uniform(0, 31) # 随机生成一个个体
population.append(individual)
return population
# 评估适应度
def fitness(individual):
return f(individual)
# 选择
def selection(population):
fitnesses = [fitness(individual) for individual in population]
elite = sorted(range(len(fitnesses)), key=lambda i: fitnesses[i])[:elite_size] # 精英个体索引
parents = [population[i] for i in elite] # 精英个体作为父母
return parents
# 交叉
def crossover(parents):
children = []
for i in range(len(parents)):
parent1 = parents[i]
parent2 = parents[(i+1)%len(parents)]
child = (parent1 + parent2) / 2 # 均值交叉
children.append(child)
return children
# 变异
def mutation(children):
for i in range(len(children)):
if random.random() < mutation_rate:
children[i] = random.uniform(0, 31) # 随机变异
return children
# 遗传算法主函数
def genetic_algorithm(population):
for i in range(generations):
parents = selection(population)
children = crossover(parents)
children = mutation(children)
population = parents + children
best_individual = min(population, key=fitness)
return best_individual
# 测试
population = init_population(pop_size)
best_individual = genetic_algorithm(population)
print("最优解:", best_individual)
print("最小值:", f(best_individual))
```
在上述代码中,我们首先定义了待求解的函数 `f(x)`,然后定义了遗传算法的参数,包括种群大小、精英个体数、变异率和迭代次数。接着,我们实现了遗传算法的核心函数,包括初始化种群、评估适应度、选择、交叉和变异。最后,我们在主函数中调用上述函数,得到最优解和最小值。
需要注意的是,本代码仅为示例,未对遗传算法的性能做出优化。在实际应用中,需要根据具体问题进行参数调整和性能优化。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://img-home.csdnimg.cn/images/20250102104920.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.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)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.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)