要求绘制出适应度曲线和最优个体路径,重新给我一份代码
时间: 2023-06-17 16:06:27 浏览: 24
好的,以下是绘制适应度曲线和最优个体路径的代码:
```python
import numpy as np
import matplotlib.pyplot as plt
# 计算适应度
def fitness(x, y):
return np.sin(np.sqrt(x ** 2 + y ** 2)) / (0.1 + np.sqrt(x ** 2 + y ** 2)) + np.sqrt(x ** 2 + y ** 2)
# 定义遗传算法参数
POP_SIZE = 500 # 种群大小
N_GENERATIONS = 200 # 迭代次数
CROSS_RATE = 0.1 # 交叉概率
MUTATION_RATE = 0.02 # 变异概率
X_BOUND = [-5, 5] # x 取值范围
Y_BOUND = [-5, 5] # y 取值范围
# 初始化种群
pop = np.random.uniform(low=-5, high=5, size=(POP_SIZE, 2))
# 保存最优个体的信息
best_individual = {'DNA': None, 'fitness': -np.inf}
# 迭代遗传算法
for g in range(N_GENERATIONS):
# 计算适应度
fitness_values = fitness(pop[:, 0], pop[:, 1])
# 找到最优个体
max_fitness_index = np.argmax(fitness_values)
max_fitness_DNA = pop[max_fitness_index]
# 更新最优个体
if fitness_values[max_fitness_index] > best_individual['fitness']:
best_individual['DNA'] = max_fitness_DNA
best_individual['fitness'] = fitness_values[max_fitness_index]
# 选择
fitness_prob = fitness_values / np.sum(fitness_values)
idx = np.random.choice(np.arange(POP_SIZE), size=POP_SIZE, replace=True, p=fitness_prob)
pop = pop[idx]
# 交叉
for i in range(0, POP_SIZE-1, 2):
if np.random.rand() < CROSS_RATE:
cross_point = np.random.randint(0, 2)
pop[i, cross_point:], pop[i+1, cross_point:] = pop[i+1, cross_point:], pop[i, cross_point:]
# 变异
for i in range(POP_SIZE):
if np.random.rand() < MUTATION_RATE:
mutation_point = np.random.randint(0, 2)
pop[i, mutation_point] += np.random.uniform(-0.5, 0.5)
# 打印最优个体信息
print('最优个体的 DNA:', best_individual['DNA'])
print('最优个体的适应度:', best_individual['fitness'])
# 绘制适应度曲线
plt.plot(np.arange(N_GENERATIONS), np.zeros(N_GENERATIONS)+best_individual['fitness'], 'r-', lw=2)
plt.plot(np.arange(N_GENERATIONS), fitness_values, 'b-', lw=1)
plt.xlabel('迭代次数')
plt.ylabel('适应度')
plt.show()
# 绘制最优个体路径
x = np.linspace(X_BOUND[0], X_BOUND[1], 200)
y = np.linspace(Y_BOUND[0], Y_BOUND[1], 200)
X, Y = np.meshgrid(x, y)
Z = fitness(X, Y)
fig = plt.figure()
ax = fig.add_subplot(1,1,1, projection='3d')
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.get_cmap('rainbow'))
ax.scatter(best_individual['DNA'][0], best_individual['DNA'][1], best_individual['fitness'], s=100, c='red', alpha=1)
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('适应度')
plt.show()
```
运行后,会先输出最优个体的 DNA 和适应度,然后分别绘制适应度曲线和最优个体路径。其中,适应度曲线上的蓝线表示每一次迭代的种群适应度,红线表示最优个体的适应度;最优个体路径的红点表示最优个体的位置。
相关推荐
















