遗传算法pyrhin
时间: 2023-12-22 22:18:37 浏览: 15
遗传算法(Genetic Algorithm)是一种优化问题的求解方法,它模拟了生物进化中的遗传和适应过程。下面是一个简单的遗传算法的Python实现示例:
```python
import random
# 遗传算法参数
POPULATION_SIZE = 50 # 种群大小
P_CROSSOVER = 0.9 # 交叉概率
P_MUTATION = 0.1 # 变异概率
MAX_GENERATION = 100 # 最大迭代次数
# 优化目标函数(这里以求解最大值为例)
def fitness_function(individual):
return sum(individual)
# 初始化种群
def initialize_population():
population = []
for _ in range(POPULATION_SIZE):
individual = [random.randint(0, 1) for _ in range(10)] # 假设染色体长度为10
population.append(individual)
return population
# 选择操作(这里使用轮盘赌选择)
def selection(population, fitness_values):
total_fitness = sum(fitness_values)
probabilities = [fitness / total_fitness for fitness in fitness_values]
selected = random.choices(population, probabilities, k=POPULATION_SIZE)
return selected
# 交叉操作(这里使用单点交叉)
def crossover(parent1, parent2):
crossover_point = random.randint(1, len(parent1) - 1)
child1 = parent1[:crossover_point] + parent2[crossover_point:]
child2 = parent2[:crossover_point] + parent1[crossover_point:]
return child1, child2
# 变异操作(这里使用单点变异)
def mutation(individual):
mutation_point = random.randint(0, len(individual) - 1)
individual[mutation_point] = 1 - individual[mutation_point]
return individual
# 遗传算法主程序
def genetic_algorithm():
population = initialize_population()
for generation in range(MAX_GENERATION):
fitness_values = [fitness_function(individual) for individual in population]
best_individual = population[fitness_values.index(max(fitness_values))]
if generation % 10 == 0:
print("Generation:", generation, "Best Fitness:", max(fitness_values))
if max(fitness_values) == sum(best_individual):
break
selected = selection(population, fitness_values)
next_population = []
while len(next_population) < POPULATION_SIZE:
parent1, parent2 = random.sample(selected, 2)
if random.random() < P_CROSSOVER:
offspring1, offspring2 = crossover(parent1, parent2)
else:
offspring1, offspring2 = parent1[:], parent2[:]
if random.random() < P_MUTATION:
offspring1 = mutation(offspring1)
if random.random() < P_MUTATION:
offspring2 = mutation(offspring2)
next_population.extend([offspring1, offspring2])
population = next_population
return best_individual
# 测试
best_solution = genetic_algorithm()
print("Best Solution:", best_solution)
```
上述代码是一个基本的遗传算法实现,其中包括了种群初始化、选择、交叉、变异等基本操作。你可以根据具体问题对代码进行适当修改和扩展。