遗传算法可以做最曲线拟合,这是因为回归模型的算法关键是最优化,而遗传算法可以做最优化。
例如,把残差当成目标函数,形如 :
然后针对a,b 做优化
我们使用 scikit-opt来编程实现,安装方法参见 官网
随机生成训练数据
import numpy as np
import matplotlib.pyplot as plt
from sko.GA import GA
x_true = np.linspace(-1.2, 1.2, 30)
y_true = x_true ** 3 - x_true + 0.4 * np.random.rand(30)
plt.plot(x_true, y_true, 'o')
![f534eede4bbb77933a6ec6284e3a5495.png](https://img-blog.csdnimg.cn/img_convert/f534eede4bbb77933a6ec6284e3a5495.png)
构造残差
def f_fun(x, a, b, c, d):
return a * x ** 3 + b * x ** 2 + c * x + d
def obj_fun(p):
a, b, c, d = p
residuals = np.square(f_fun(x_true, a,