ga遗传算法Python代码
时间: 2024-10-20 18:04:58 浏览: 26
货位优化遗传算法python代码.zip
GA(Genetic Algorithm,遗传算法)是一种基于自然选择和遗传机制的优化搜索算法,常用于解决复杂的优化问题。在Python中实现GA的基本步骤包括初始化种群、适应度函数评估、选择操作、交叉(Crossover)、变异(Mutation)以及迭代直到达到终止条件。
下面是一个简单的GA基本框架的Python代码示例:
```python
import numpy as np
# 初始化种群
def initialize_population(size, dimensions):
return np.random.rand(size, dimensions)
# 计算适应度函数
def fitness_function(individuals):
# 这里假设适应度函数是一个简单的求和,实际应用中根据目标函数调整
return sum(individuals**2, axis=1)
# 遗传操作
def selection(population, fitness):
parents = np.random.choice(population, size=len(population), replace=True, p=fitness / fitness.sum())
return parents
def crossover(parents, probability):
offspring = []
for _ in range(len(parents)):
if np.random.rand() < probability:
# 使用单点交叉
cut_point = np.random.randint(0, len(parents[0]))
offspring.append(np.concatenate((parents[0][:cut_point], parents[1][cut_point:])))
else:
offspring.append(parents[np.random.randint(0, 2)])
return offspring
def mutation(offspring, mutation_rate):
mutated_offspring = offspring.copy()
for individual in mutated_offspring:
for i in range(len(individual)):
if np.random.rand() < mutation_rate:
individual[i] += np.random.randn() * 0.1 # 可根据需要调整变异范围
return mutated_offspring
def ga_algorithm(pop_size, generations, dimensions, crossover_prob, mutation_prob):
population = initialize_population(pop_size, dimensions)
for generation in range(generations):
fitness_values = fitness_function(population)
selected_pop = selection(population, fitness_values)
offspring = crossover(selected_pop, crossover_prob)
offspring = mutation(offspring, mutation_prob)
# 如果有早停策略可以在这里检查最优解
population = offspring
best_solution = population[np.argmax(fitness_values)]
return best_solution, fitness_values.max()
# 示例参数设置
pop_size = 50
generations = 100
dimensions = 10
crossover_prob = 0.8
mutation_prob = 0.1
best_solution, max_fitness = ga_algorithm(pop_size, generations, dimensions, crossover_prob, mutation_prob)
print(f"最佳解:{best_solution}, 最大适应度:{max_fitness}")
阅读全文