画图比较遗传算法优劣的python代码
时间: 2023-11-12 09:46:50 浏览: 96
基于图的遗传算法_python_代码_下载
以下是一个简单的Python程序,用于比较遗传算法和随机搜索在解决函数优化问题中的表现:
```python
import numpy as np
import matplotlib.pyplot as plt
def fitness_func(x):
# 定义适应度函数,这里使用Rosenbrock函数作为例子
return sum(100*(x[1:]-x[:-1]**2)**2 +(1-x[:-1])**2)
def init_pop(pop_size, n_dim):
# 初始化种群
pop = np.random.rand(pop_size, n_dim)
return pop
def selection(pop, fitness):
# 选择操作
idx = np.random.choice(np.arange(len(pop)), size=len(pop), replace=True, p=fitness/fitness.sum())
return pop[idx]
def crossover(parents, n_offsprings):
# 交叉操作
offsprings = np.zeros((n_offsprings, parents.shape[1]))
for i in range(n_offsprings):
idx1, idx2 = np.random.choice(np.arange(len(parents)), size=2, replace=False)
cross_pt = np.random.randint(0, parents.shape[1])
offsprings[i, :cross_pt] = parents[idx1, :cross_pt]
offsprings[i, cross_pt:] = parents[idx2, cross_pt:]
return offsprings
def mutation(offsprings, mut_rate):
# 变异操作
for i in range(len(offsprings)):
if np.random.rand() < mut_rate:
mut_pt = np.random.randint(0, offsprings.shape[1])
offsprings[i, mut_pt] = np.random.rand()
return offsprings
def ga(pop_size, n_dim, n_gen, mut_rate):
# 遗传算法主函数
pop = init_pop(pop_size, n_dim)
best_fitness = []
for i in range(n_gen):
fitness = np.array([fitness_func(x) for x in pop])
best_fitness.append(fitness.min())
parents = selection(pop, fitness)
offsprings = crossover(parents, len(pop)-len(parents))
offsprings = mutation(offsprings, mut_rate)
pop = np.vstack([parents, offsprings])
return best_fitness
def random_search(n_trials, n_dim):
# 随机搜索主函数
best_fitness = []
for i in range(n_trials):
x = np.random.rand(n_dim)
best_fitness.append(fitness_func(x))
return best_fitness
if __name__ == '__main__':
np.random.seed(0)
pop_size = 50
n_dim = 10
n_gen = 100
mut_rate = 0.1
n_trials = 500
ga_results = ga(pop_size, n_dim, n_gen, mut_rate)
rs_results = random_search(n_trials, n_dim)
plt.plot(ga_results, label='GA')
plt.plot(rs_results, label='Random Search')
plt.legend()
plt.xlabel('Generation/Trial')
plt.ylabel('Best Fitness')
plt.show()
```
上述代码中,首先定义了一个Rosenbrock函数作为优化目标,然后实现了遗传算法和随机搜索两个函数。在主函数中,通过调用这两个函数来得到优化过程中的最佳适应度值。最后,使用matplotlib库将结果可视化。
阅读全文