请你以python为语言,写一段能跑通的遗传算法代码,并将代码的应用进行文字说明
时间: 2024-10-05 22:04:55 浏览: 48
sort-algorithm-遗传算法python代码详解
在Python中,遗传算法是一种模拟自然选择过程的优化算法,通常用于解决复杂的搜索问题。下面是一个简单的遗传算法示例,我们将尝试优化一个函数,使其最小化一个特定的目标函数。这里我们使用了经典的人工鱼群(Swarm Optimization)作为遗传算法的一个实例:
```python
import numpy as np
import random
# 定义目标函数,这里以简单的一维函数为例
def fitness_function(x):
return x**2 + 10 * np.sin(x)
# 遗传算法设置
pop_size = 50 # 种群大小
num_generations = 100 # 迭代次数
gene_length = 1 # 每个个体的基因长度
mutation_rate = 0.01 # 变异概率
crossover_probability = 0.8 # 交叉概率
# 初始化种群
def initialize_population(pop_size):
return [np.random.uniform(-10, 10, gene_length) for _ in range(pop_size)]
# 计算适应度
def calculate_fitness(population):
return [fitness_function(individual) for individual in population]
# 选择操作
def selection(population, fitness_scores):
parents = np.random.choice(range(len(population)), size=pop_size, p=fitness_scores / sum(fitness_scores))
return population[parents]
# 交叉操作
def crossover(parents, crossover_probability):
offspring = []
for i in range(0, len(parents), 2):
if random.random() < crossover_probability:
point = random.randint(0, gene_length - 1)
child1 = np.concatenate((parents[i][:point], parents[i+1][point:]))
child2 = np.concatenate((parents[i+1][:point], parents[i][point:]))
else:
child1 = parents[i]
child2 = parents[i+1]
offspring.extend([child1, child2])
return offspring
# 变异操作
def mutation(offspring, mutation_rate):
mutated_offspring = []
for individual in offspring:
for i in range(gene_length):
if random.random() < mutation_rate:
individual[i] += random.uniform(-1, 1)
mutated_offspring.append(individual)
return mutated_offspring
def genetic_algorithm():
population = initialize_population(pop_size)
for generation in range(num_generations):
fitness_scores = calculate_fitness(population)
elite = population[np.argsort(fitness_scores)[:pop_size // 4]] # 保留精英
population = selection(elite + population, fitness_scores) # 更新种群
population = crossover(population, crossover_probability)
population = mutation(population, mutation_rate)
best_individual = population[np.argmin(calculate_fitness(population))]
print(f"最佳解:{best_individual}, 最优值:{fitness_function(best_individual)}")
genetic_algorithm()
```
这段代码首先定义了一个简单的单峰函数`fitness_function`,然后创建一个遗传算法流程,包括初始化种群、计算适应度、选择、交叉和变异等步骤。经过多次迭代后,它会找到该一维空间内使目标函数最小的解。
阅读全文