遗传算法python实例
时间: 2023-10-13 21:27:07 浏览: 47
很高兴为您提供遗传算法在Python中的示例代码。遗传算法是一类优化算法,可用于解决许多实际问题。以下是一个简单的遗传算法Python示例:
```python
import random
# 创建种群
def create_population(pop_size, num_genes):
population = []
for i in range(pop_size):
individual = []
for j in range(num_genes):
individual.append(random.randint(0, 1))
population.append(individual)
return population
# 计算适应度
def fitness(individual):
# 这里编写适应度函数的代码
score = 0
for i in individual:
score += i
return score
# 选择
def selection(population):
fitnesses = [fitness(individual) for individual in population]
sum_fitnesses = sum(fitnesses)
probabilities = [fitness/sum_fitnesses for fitness in fitnesses]
selected_indices = []
for i in range(len(population)):
selected = False
while not selected:
r = random.random()
for j in range(len(probabilities)):
if r <= probabilities[j]:
selected_indices.append(j)
selected = True
break
return [population[index] for index in selected_indices]
# 交叉
def crossover(individual1, individual2):
crossover_point = random.randint(1, len(individual1) - 1)
child1 = individual1[:crossover_point] + individual2[crossover_point:]
child2 = individual2[:crossover_point] + individual1[crossover_point:]
return [child1, child2]
# 变异
def mutate(individual, mutation_rate):
for i in range(len(individual)):
if random.random() < mutation_rate:
individual[i] = 1 - individual[i]
return individual
# 主函数
def evolve(pop_size, num_genes, num_iterations, mutation_rate):
population = create_population(pop_size, num_genes)
for i in range(num_iterations):
population = selection(population)
new_population = []
for j in range(int(pop_size/2)):
individual1 = population[random.randint(0, len(population) - 1)]
individual2 = population[random.randint(0, len(population) - 1)]
children = crossover(individual1, individual2)
new_population.extend(children)
for individual in new_population:
mutate(individual, mutation_rate)
population = new_population
return max(population, key=fitness)
# 示例:
num_genes = 20
pop_size = 100
num_iterations = 1000
mutation_rate = 0.01
print(evolve(pop_size, num_genes, num_iterations, mutation_rate))
```
请注意,此代码仅用于说明目的。要根据自己的数据和问题进行修改和优化。另外,您可能需要使用其他库来处理您的数据和问题。如果您需要更多帮助,请随时问我。
阅读全文