遗传算法求解目标函数极值:以 f(x) = x^2 - 4x + 3 为例
使用遗传算法求解目标函数极值:以 f(x) = x^2 - 4x + 3 为例
本示例使用 Python 和 scikit-opt 库,通过遗传算法求解目标函数 f(x) = x^2 - 4x + 3 的极值。
首先导入所需的库和函数:
import numpy as np
import matplotlib.pyplot as plt
from sko.GA import GA
然后定义目标函数和约束条件:
def func(x):
return x ** 2 - 4 * x + 3
# 定义变量的上下界
bound = np.array([[0, 5]])
接着定义遗传算法模型并进行求解:
# 遗传算法模型
ga = GA(func=func, n_dim=1, size_pop=50, max_iter=100, lb=bound[:, 0], ub=bound[:, 1], precision=1e-7)
best_x, best_y = ga.run()
print('best_x:', best_x, '\n', 'best_y:', best_y)
运行结果为:
best_x: [2.]
best_y: [-1.]
可以看出,该函数的极小值为-1,当x=2时取到。
最后,我们可以绘制出函数的图像和求解过程中适应度函数的变化情况:
# 绘制函数图像
x = np.linspace(0, 5, 50)
y = func(x)
plt.plot(x, y)
# 绘制遗传算法求解过程中适应度函数的变化情况
plt.plot(ga.generation_best_X, ga.generation_best_Y, 'bo', alpha=0.5, label='best')
plt.plot(ga.all_history_Y, 'r-', alpha=0.5, label='average')
plt.legend()
plt.title('Result Analysis')
plt.show()
绘制出的图像如下所示:

从图像中可以看出,适应度函数在不断地降低,直到到达最小值,说明遗传算法的求解过程是有效的。
完整代码如下:
import numpy as np
import matplotlib.pyplot as plt
from sko.GA import GA
def func(x):
return x ** 2 - 4 * x + 3
bound = np.array([[0, 5]])
ga = GA(func=func, n_dim=1, size_pop=50, max_iter=100, lb=bound[:, 0], ub=bound[:, 1], precision=1e-7)
best_x, best_y = ga.run()
print('best_x:', best_x, '\n', 'best_y:', best_y)
x = np.linspace(0, 5, 50)
y = func(x)
plt.plot(x, y)
plt.plot(ga.generation_best_X, ga.generation_best_Y, 'bo', alpha=0.5, label='best')
plt.plot(ga.all_history_Y, 'r-', alpha=0.5, label='average')
plt.legend()
plt.title('Result Analysis')
plt.show()
原文地址: https://www.cveoy.top/t/topic/oeXX 著作权归作者所有。请勿转载和采集!