Python遗传算法的代码
时间: 2023-11-21 13:50:59 浏览: 116
以下是一个简单的Python遗传算法的代码示例:
```python
import random
# 定义目标函数
def fitness(individual):
return sum(individual)
# 初始化种群
def init_population(pop_size, gene_size):
population = []
for i in range(pop_size):
individual = [random.randint(0, 1) for _ in range(gene_size)]
population.append(individual)
return population
# 选择操作
def selection(population):
fitnesses = [fitness(individual) for individual in population]
total_fitness = sum(fitnesses)
probabilities = [fitness / total_fitness for fitness in fitnesses]
selected = random.choices(population, probabilities, k=2)
return selected[0], selected[1]
# 交叉操作
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 mutation(individual, mutation_rate):
for i in range(len(individual)):
if random.random() < mutation_rate:
individual[i] = 1 - individual[i]
return individual
# 遗传算法主函数
def genetic_algorithm(pop_size, gene_size, mutation_rate, generations):
population = init_population(pop_size, gene_size)
for i in range(generations):
parent1, parent2 = selection(population)
child1, child2 = crossover(parent1, parent2)
child1 = mutation(child1, mutation_rate)
child2 = mutation(child2, mutation_rate)
population.extend([child1, child2])
population = sorted(population, key=lambda x: fitness(x), reverse=True)
population = population[:pop_size]
return population[0]
# 测试
best_individual = genetic_algorithm(pop_size=100, gene_size=10, mutation_rate=0.01, generations=100)
print(best_individual)
```
该代码实现了一个简单的二进制遗传算法,用于求解一个长度为10的二进制向量中所有元素之和最大的向量。其中,`init_population`函数用于初始化种群,`selection`函数用于选择操作,`crossover`函数用于交叉操作,`mutation`函数用于变异操作,`genetic_algorithm`函数是遗传算法的主函数。
阅读全文