帮我用python语言编写一段遗传算法代码
时间: 2023-06-03 20:05:00 浏览: 98
遗传算法的一段代码
好的,我会为您提供关于遗传算法的代码实现。以下是一个简单的遗传算法的示例,用于求解一个函数的最优解。在这个示例中,我们将最小化函数 f(x) = x^2,将个体定义为实数,最大进化代数为100,种群大小为100,交叉概率为0.8,变异概率为0.1。
```python
import random
def fitness(individual):
return individual**2
def generate_population(pop_size):
population = []
for i in range(pop_size):
population.append(random.uniform(-10, 10))
return population
def selection(population):
selected = random.sample(population, 2)
return sorted(selected, key=lambda x: fitness(x))[0]
def crossover(parent_1, parent_2):
if random.random() < crossover_prob:
return (parent_1 + parent_2) / 2
else:
return parent_1
def mutate(individual):
if random.random() < mutation_prob:
return individual + random.uniform(-1, 1)
else:
return individual
def genetic_algorithm(pop_size, gens):
population = generate_population(pop_size)
for i in range(gens):
new_population = []
for j in range(pop_size):
parent_1 = selection(population)
parent_2 = selection(population)
offspring = crossover(parent_1, parent_2)
offspring = mutate(offspring)
new_population.append(offspring)
population = new_population
return min(population, key=lambda x: fitness(x))
if __name__ == '__main__':
pop_size = 100
gens = 100
crossover_prob = 0.8
mutation_prob = 0.1
result = genetic_algorithm(pop_size, gens)
print("最优解为:", result)
```
以上是一个遗传算法的简单实现,您可以根据自己的需求修改代码并调整参数。希望能对您有所帮助!
阅读全文