写一个遗传算法,用python
时间: 2024-11-03 18:19:52 浏览: 4
Python遗传算法求一元函数最大值
编写一个简单的遗传算法的Python代码示例如下:
```python
import random
# 假设我们要解决的是0-1背包问题,定义一个个体(解)
def create_population(size):
return [random.choices([0, 1], k=num_items) for _ in range(size)]
# 计算每个个体的适应度(目标函数)
def fitness(individual):
total_value = sum(item * value for item, value in zip(individual, values))
total_weight = sum(weight * item for item, weight in zip(individual, weights))
return total_value / total_weight if total_weight > 0 else float('inf')
# 选择操作
def selection(population, fitness_values):
return random.choices(population, weights=[fitness_val for fitness_val in fitness_values])
# 交叉操作(这里用单点交叉)
def crossover(parent1, parent2):
cut_point = random.randint(1, len(parent1)-1)
child1 = parent1[:cut_point] + parent2[cut_point:]
child2 = parent2[:cut_point] + parent1[cut_point:]
return child1, child2
# 变异操作
def mutate(individual):
for i in range(len(individual)):
if random.random() < mutation_rate:
individual[i] = 1 - individual[i]
return individual
# 主循环
def genetic_algorithm(population_size, num_generations, crossover_rate, mutation_rate):
population = create_population(population_size)
for _ in range(num_generations):
fitness_values = [fitness(indiv) for indiv in population]
next_generation = [selection(population, fitness_values)]
while len(next_generation) < population_size:
parents = random.sample(population, 2)
children = crossover(parents[0], parents[1])
children = [mutate(child) for child in children]
next_generation.extend(children)
population = next_generation
# 返回最适应的解
return max(population, key=fitness)
# 示例参数
num_items, values, weights = 5, [10, 20, 30, 40, 50], [1, 2, 3, 4, 5]
population_size = 100
num_generations = 100
crossover_rate = 0.8
mutation_rate = 0.01
solution = genetic_algorithm(population_size, num_generations, crossover_rate, mutation_rate)
print("最优解:", solution)
```
请注意,这只是一个基础版本,实际应用中可能需要根据问题特性进行适当修改。同时,遗传算法的性能很大程度上取决于参数的选择,上述例子中的参数仅作为演示用途。
阅读全文