请写出一段遗传算法的代码,用Python
时间: 2023-08-31 21:24:20 浏览: 102
### 回答1:
答:def GeneticAlgorithm(population, fitness_fn, ngen=100, pmut=0.1):
for i in range(ngen):
# 对种群中的每个个体评估适应度
population = [ (individual, fitness_fn(individual))
for individual in population]
# 按照适应度从高到低排序
population = [ individual[0] for individual in sorted(population, key=lambda individual: individual[1], reverse=True)]
# 选取最优秀的个体,称为父母
parents = population[:len(population)//2]
# 交叉繁殖
offspring = []
for i in range(len(parents)//2):
parent1 = parents[i]
parent2 = parents[len(parents)-1-i]
child1, child2 = crossover(parent1, parent2)
offspring.append(child1)
offspring.append(child2)
# 变异
for i in range(len(offspring)):
if random.random() < pmut:
offspring[i] = mutation(offspring[i])
# 选取新的种群
population = parents + offspring
return population
### 回答2:
遗传算法是一种模拟遗传过程的优化算法。下面是一个用Python编写的简单遗传算法的示例代码:
```python
import numpy as np
# 定义适应度函数
def fitness_func(solution):
return np.sum(solution)
# 初始化种群
def init_population(pop_size, chromosome_length):
return np.random.randint(2, size=(pop_size, chromosome_length))
# 选择操作
def selection(population, fitness_values):
fitness_sum = np.sum(fitness_values)
selection_probs = fitness_values / fitness_sum
selected_indices = np.random.choice(len(population), size=len(population), p=selection_probs)
return population[selected_indices]
# 交叉操作
def crossover(parent1, parent2):
crossover_point = np.random.randint(0, len(parent1) + 1)
child1 = np.concatenate((parent1[:crossover_point], parent2[crossover_point:]))
child2 = np.concatenate((parent2[:crossover_point], parent1[crossover_point:]))
return child1, child2
# 变异操作
def mutation(individual, mutation_rate):
for i in range(len(individual)):
if np.random.rand() < mutation_rate:
individual[i] = 1 - individual[i] # 变异位点翻转
return individual
# 遗传算法实现
def genetic_algorithm(population_size, chromosome_length, mutation_rate, generations):
population = init_population(population_size, chromosome_length)
fitness_values = np.zeros(population_size)
for generation in range(generations):
for i in range(population_size):
fitness_values[i] = fitness_func(population[i])
population = selection(population, fitness_values)
new_population = []
for i in range(0, population_size, 2):
parent1, parent2 = population[i], population[i+1]
child1, child2 = crossover(parent1, parent2)
child1 = mutation(child1, mutation_rate)
child2 = mutation(child2, mutation_rate)
new_population.append(child1)
new_population.append(child2)
population = np.array(new_population)
best_individual = population[np.argmax(fitness_values)]
best_fitness = np.max(fitness_values)
return best_individual, best_fitness
# 示例运行
population_size = 100
chromosome_length = 10
mutation_rate = 0.01
generations = 100
best_individual, best_fitness = genetic_algorithm(population_size, chromosome_length, mutation_rate, generations)
print("最优个体:", best_individual)
print("最优适应度:", best_fitness)
```
以上代码实现了一个简单的遗传算法,通过遗传算法优化一个01串的问题。代码中包括适应度函数的定义、种群初始化、选择、交叉、变异等操作的实现。最后通过遗传算法迭代,得到最优的个体和适应度。
阅读全文