给我Python实现的遗传算法代码
时间: 2024-04-16 16:06:24 浏览: 84
python实现遗传算法求解Ackley函数.zip
5星 · 资源好评率100%
以下是一个简单的 Python 遗传算法实现,用于最大化一个函数的值:
```python
import random
# 定义函数,这里以求 x^2 的最大值为例
def fitness(x):
return x * x
# 初始化种群
def init_population(population_size, chromosome_length):
population = []
for i in range(population_size):
chromosome = []
for j in range(chromosome_length):
chromosome.append(random.randint(0, 1))
population.append(chromosome)
return population
# 计算适应度
def calculate_fitness(population):
fitness_scores = []
for chromosome in population:
x = 0
for i in range(len(chromosome)):
x += chromosome[i] * pow(2, i)
fitness_scores.append(fitness(x))
return fitness_scores
# 选择
def select(population, fitness_scores):
selected_population = []
for i in range(len(population)):
parent1 = random.randint(0, len(population) - 1)
parent2 = random.randint(0, len(population) - 1)
if fitness_scores[parent1] > fitness_scores[parent2]:
selected_population.append(population[parent1])
else:
selected_population.append(population[parent2])
return selected_population
# 交叉
def crossover(selected_population, crossover_rate):
for i in range(0, len(selected_population), 2):
if random.random() < crossover_rate:
crossover_point = random.randint(0, len(selected_population[i]) - 1)
temp = selected_population[i][crossover_point:]
selected_population[i][crossover_point:] = selected_population[i+1][crossover_point:]
selected_population[i+1][crossover_point:] = temp
return selected_population
# 变异
def mutate(selected_population, mutation_rate):
for i in range(len(selected_population)):
for j in range(len(selected_population[i])):
if random.random() < mutation_rate:
selected_population[i][j] = 1 - selected_population[i][j]
return selected_population
# 遗传算法主函数
def genetic_algorithm(population_size, chromosome_length, num_generations, crossover_rate, mutation_rate):
population = init_population(population_size, chromosome_length)
for i in range(num_generations):
fitness_scores = calculate_fitness(population)
selected_population = select(population, fitness_scores)
selected_population = crossover(selected_population, crossover_rate)
selected_population = mutate(selected_population, mutation_rate)
population = selected_population
return max(calculate_fitness(population))
# 调用遗传算法函数
print(genetic_algorithm(100, 10, 100, 0.8, 0.01))
```
在这个实现中,我们使用了二进制编码来表示染色体的值。每个染色体都是由 0 和 1 组成的一串二进制数。在初始化种群时,我们随机生成了一些二进制数作为染色体的值。在计算适应度时,我们将每个染色体的二进制数转换为十进制数,并将其代入目标函数中计算适应度。在选择,交叉和变异中,我们使用了常见的遗传算法操作。最终,我们返回种群中适应度最高的染色体对应的目标函数的值。
阅读全文