python实现遗传算法实例
时间: 2023-11-18 17:12:25 浏览: 100
遗传算法实例(python实现)
3星 · 编辑精心推荐
以下是一个简单的 Python 遗传算法实现示例:
```python
import random
# 定义遗传算法参数
POPULATION_SIZE = 100 # 种群大小
GENERATIONS = 50 # 迭代次数
MUTATION_RATE = 0.1 # 突变率
# 定义问题
OBJECTIVE_FUNCTION = lambda x: sum(x) # 目标函数
NUM_VARIABLES = 5 # 变量数量
VARIABLE_RANGE = (-5, 5) # 变量范围
# 初始化种群
population = []
for i in range(POPULATION_SIZE):
individual = [random.uniform(*VARIABLE_RANGE) for _ in range(NUM_VARIABLES)]
population.append(individual)
# 迭代
for generation in range(GENERATIONS):
# 评估适应度
fitness = [OBJECTIVE_FUNCTION(individual) for individual in population]
# 选择
total_fitness = sum(fitness)
probabilities = [f / total_fitness for f in fitness]
selected_indices = random.choices(range(len(population)), weights=probabilities, k=len(population))
selected_population = [population[i] for i in selected_indices]
# 交叉
new_population = []
for i in range(0, len(selected_population), 2):
parent1 = selected_population[i]
parent2 = selected_population[i+1]
child1 = []
child2 = []
for j in range(NUM_VARIABLES):
if random.random() < 0.5:
child1.append(parent1[j])
child2.append(parent2[j])
else:
child1.append(parent2[j])
child2.append(parent1[j])
new_population.append(child1)
new_population.append(child2)
# 突变
for i in range(len(new_population)):
for j in range(NUM_VARIABLES):
if random.random() < MUTATION_RATE:
new_population[i][j] = random.uniform(*VARIABLE_RANGE)
population = new_population
# 输出最优解
best_individual = max(population, key=OBJECTIVE_FUNCTION)
print("Best individual:", best_individual)
print("Objective value:", OBJECTIVE_FUNCTION(best_individual))
```
该示例实现了一个遗传算法来求解一个简单的多元函数最大值问题。在每一代中,种群通过选择、交叉和突变产生新一代个体,并且适应度高的个体具有更高的概率被选择。该算法最终输出最优解和对应的目标函数值。
阅读全文