自己举例
时间: 2023-09-23 22:03:55 浏览: 70
好的,以下是一个用遗传算法求解函数最小值的 Python 代码示例:
```
import random
# 目标函数,这里以 Rosenbrock 函数为例
def rosenbrock(x, y):
return (1 - x) ** 2 + 100 * (y - x ** 2) ** 2
# 遗传算法求解函数最小值
def genetic_algorithm():
# 设置参数
num_population = 50 # 种群大小
num_generation = 100 # 迭代次数
mutation_rate = 0.01 # 变异率
crossover_rate = 0.8 # 交叉率
# 初始化种群
population = []
for i in range(num_population):
x = random.uniform(-5, 5)
y = random.uniform(-5, 5)
fitness = rosenbrock(x, y)
population.append({'x': x, 'y': y, 'fitness': fitness})
# 迭代
for i in range(num_generation):
# 计算适应度
fitness_sum = sum([p['fitness'] for p in population])
for p in population:
p['probability'] = p['fitness'] / fitness_sum
# 选择
new_population = []
for j in range(num_population):
p1 = random.choices(population, weights=[p['probability'] for p in population])[0]
p2 = random.choices(population, weights=[p['probability'] for p in population])[0]
# 交叉
if random.random() < crossover_rate:
x = (p1['x'] + p2['x']) / 2
y = (p1['y'] + p2['y']) / 2
else:
x = p1['x']
y = p1['y']
# 变异
if random.random() < mutation_rate:
x += random.gauss(0, 0.1)
y += random.gauss(0, 0.1)
# 计算适应度
fitness = rosenbrock(x, y)
new_population.append({'x': x, 'y': y, 'fitness': fitness})
population = new_population
# 返回最优解
return min(population, key=lambda p: p['fitness'])
# 测试
result = genetic_algorithm()
print(result)
```
这个示例程序使用遗传算法求解 Rosenbrock 函数最小值。在遗传算法中,首先初始化一个种群,然后不断迭代,每一次迭代都进行选择、交叉和变异操作。最后返回种群中的最优解作为结果。这个程序可以用来研究遗传算法的优化能力,并且可以修改目标函数和参数来进行不同的实验。
阅读全文