编写python遗传算法
时间: 2023-02-24 17:06:28 浏览: 159
基于python的遗传算法设计与实现
遗传算法是一种仿照生物进化的过程的人工智能算法。下面是一个用 Python 实现的遗传算法的简单例子。
```
import random
# 初始化种群(随机生成一组解)
def init_population(pop_size, num_bits):
population = []
for i in range(pop_size):
chromosome = ''
for j in range(num_bits):
chromosome += str(random.randint(0, 1))
population.append(chromosome)
return population
# 评估每个个体的适应度
def evaluate_fitness(population):
fitness_values = []
for i in range(len(population)):
fitness_values.append(population[i].count('1'))
return fitness_values
# 选择父母(轮盘赌选择)
def select_parents(population, fitness_values):
parents = []
total_fitness = sum(fitness_values)
for i in range(len(population)):
r = random.uniform(0, total_fitness)
s = 0
for j in range(len(population)):
s += fitness_values[j]
if s >= r:
parents.append(population[j])
break
return parents
# 交叉(一点交叉)
def crossover(parents, crossover_point):
children = []
for i in range(0, len(parents), 2):
child1 = parents[i][:crossover_point] + parents[i+1][crossover_point:]
child2 = parents[i+1][:crossover_point] + parents[i][crossover_point:]
children.append(child1)
children.append(child2)
return children
# 变异(随机改变一个基因位置的值)
def mutation(children, mutation_rate):
for i in range(len(children)):
for j in range(len(children[i])):
r = random.uniform(0, 1)
if r < mutation_rate:
if children[i][j] == '1':
children[i] = children[i][:j] + '0' + children[i][j+1:]
else:
children[i] = children[i][:j] + '1' + children[i][j+1:]
return children
# 更新种群
def update_population(population, children):
population = population + children
return population
# 遗传
阅读全文