使用python用遗传算法编程实现Ackley函数优化问题
时间: 2024-01-06 14:13:07 浏览: 103
python实现遗传算法求解Ackley函数.zip
5星 · 资源好评率100%
好的,下面是使用Python实现Ackley函数优化问题的遗传算法的步骤:
1.导入必要的库
```python
import numpy as np
import matplotlib.pyplot as plt
```
2.定义Ackley函数
```python
def ackley(x):
n = len(x)
sum1 = sum([x[i] ** 2 for i in range(n)])
sum2 = sum([np.cos(2 * np.pi * x[i]) for i in range(n)])
return -20 * np.exp(-0.2 * np.sqrt(sum1 / n)) - np.exp(sum2 / n) + 20 + np.exp(1)
```
3.初始化种群
```python
def init_population(pop_size, chromosome_length):
population = np.random.uniform(-32.768, 32.768, size=(pop_size, chromosome_length))
return population
```
4.计算适应度函数
```python
def cal_fitness(population):
fitness = np.zeros(population.shape[0])
for i in range(population.shape[0]):
fitness[i] = ackley(population[i])
return fitness
```
5.选择操作
```python
def selection(population, fitness):
idx = np.random.choice(np.arange(population.shape[0]), size=2, replace=False, p=fitness / np.sum(fitness))
return population[idx]
```
6.交叉操作
```python
def crossover(parents, pc):
if np.random.rand() < pc:
child1 = np.zeros(parents[0].shape)
child2 = np.zeros(parents[1].shape)
pos = np.random.randint(1, parents[0].shape[0] - 1)
child1[:pos] = parents[0][:pos]
child1[pos:] = parents[1][pos:]
child2[:pos] = parents[1][:pos]
child2[pos:] = parents[0][pos:]
return child1, child2
else:
return parents[0], parents[1]
```
7.变异操作
```python
def mutation(child, pm):
if np.random.rand() < pm:
pos = np.random.randint(child.shape[0])
child[pos] = np.random.uniform(-32.768, 32.768)
return child
```
8.遗传算法主函数
```python
def genetic_algorithm(pop_size, chromosome_length, pc, pm, max_iter):
population = init_population(pop_size, chromosome_length)
fitness = cal_fitness(population)
best_idx = np.argmin(fitness)
best_individual = population[best_idx]
best_fitness = fitness[best_idx]
for i in range(max_iter):
new_population = np.zeros(population.shape)
for j in range(int(pop_size / 2)):
parents = selection(population, fitness)
child1, child2 = crossover(parents, pc)
child1 = mutation(child1, pm)
child2 = mutation(child2, pm)
new_population[j * 2] = child1
new_population[j * 2 + 1] = child2
population = new_population
fitness = cal_fitness(population)
best_idx = np.argmin(fitness)
if fitness[best_idx] < best_fitness:
best_individual = population[best_idx]
best_fitness = fitness[best_idx]
return best_individual, best_fitness
```
9.测试代码
```python
best_individual, best_fitness = genetic_algorithm(pop_size=100, chromosome_length=2, pc=0.8, pm=0.1, max_iter=100)
print("最优解:", best_individual)
print("最优解的适应度:", best_fitness)
```
运行以上代码即可得到Ackley函数的最优解和最优解的适应度。
希望我的回答对你有所帮助!
阅读全文